Wednesday, May 31, 2017

Difference between char, varchar and nvarchar

Char DataType

Char datatype which is used to store fixed length of characters. Suppose if we declared char(50) it will allocates memory for 50 characters. Once we declare char(50) and insert only 10 characters of word then only 10 characters of memory will be used and other 40 characters of memory will be wasted.

varchar DataType
Varchar means variable characters and it is used to store non-unicode characters. It will allocate the memory based on number characters inserted. Suppose if we declared varchar(50) it will allocates memory of 0 characters at the time of declaration. Once we declare varchar(50) and insert only 10 characters of word it will allocate memory for only 10 characters.


nvarchar DataType

nvarchar datatype same as varchar datatype but only difference nvarchar is used to store Unicode characters and it allows you to store multiple languages in database. nvarchar datatype will take twice as much space to store extended set of characters as required by other languages.


So if we are not using other languages then it’s better to use varchar datatype instead of nvarchar.
varchar is single byte, nvarchar is double byte

Attached Dependency Property

Attached dependency property as being the property equivalent of an extension method.
You basically attach a new property to an existing object. Without actually modifying the object definition.
 Which is especially handy when inheritance is not possible, like in sealed objects.

 The most important application, as far as I am concerned, is that you can make something bindable that is not
bindable out of the box. If some value(s) a GUI component can only be set by a method, you cannot use it from MVVM,
for example. By making an attached dependency property that passes on the new value to said method you work around that.
 See below for how you make such a callback.

So how do you make an attached dependency property?

You make a static class, in which the property is declared and 'hosted'


public static class DependencyPropertyHoster
{
  public static readonly DependencyProperty MyPropertyNameProperty =
    DependencyProperty.RegisterAttached("MyPropertyName", 
    typeof(TargetPropertyType), 
    typeof(DependencyPropertyHoster), 
    new PropertyMetadata(CallBackWhenPropertyIsChanged));

  // Called when Property is retrieved
  public static TargetPropertyType GetMyPropertyName(DependencyObject obj)
  {
    return obj.GetValue(MyPropertyNameProperty) as TargetPropertyType;
  }

  // Called when Property is set
  public static void SetMyPropertyName(
     DependencyObject obj, 
     TargetPropertyType value)
  {
    obj.SetValue(MyPropertyNameProperty, value);
  }

  // Called when property is changed
  private static void CallBackWhenPropertyIsChanged(
   object sender, 
   DependencyPropertyChangedEventArgs args)
  {
    var attachedObject = sender as ObjectTypeToWhichYouWantToAttach;
    if (attachedObject != null )
    {
      // do whatever is necessary, for example
      // attachedObject.CallSomeMethod( 
      // args.NewValue as TargetPropertyType);
    }
   }
}
This is roughly the equivalent of
public partial class ObjectTypeToWhichYouWantToAttach
{
  TargetPropertyType _myPropertyName;
  TargetPropertyType MyPropertyName
 {
   get
   {
     return _myPropertyName;
   }
   set
   {
     if( _myPropertyName != value )
     {
        //CallBackWhenPropertyIsChanged...
     }
   }
  }
}

The whole thing works by naming convention. So if you call your property "MyPropertyName", then:


  • Your DependecyProperty needs to be called MyPropertyNameProperty
  • Your Set method needs to be called SetMyPropertyName
  • Your Get method needs to be called GetMyPropertyName

When you register your property the way I do, the members in the RegisterAttached method call are, from left to right:

  • The name of your property (as a string, yes)
  • Property value type (here “TargetPropertyType”, but of course that can be anything)
  • Type of the hosting class (i.e. DependencyPropertyHoster in this case)
  • Callbackmethod to be called when the property is changed.

Monday, May 29, 2017

Value Type and Garbage Collector Role

Garbage Collector play no role in de allocation of value type variable.

The stack is a block of pre-allocated memory one million bytes in size. Sometimes we use portions of that block of memory to store local variables of value type.The stack never changes in size; it's a one-million-byte block of pre-allocated memory.

The stack is divided into two contiguous regions, which we'll call the "valid" and "invalid" sections of the stack. On x86 architectures the ESP register points to the boundary between those regions.

The stack is an implementation detail of a specific version of the runtime.

In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.

Difference between stack and Heap

The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.

Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).
  • Both are stored in computer RAM.
  • Stack is faster than heap.
  • Variables created on the stack will go out of scope and automatically deallocated.
  • Data items on stack are allocated and deallocated by CPU; therefore memory will be managed efficiently, there will be no memory leaks and memory will not become fragmented.
  • Variables once allocated on to the stack cannot be resized.
  • Variables allocated from heap region can be resized using realloc()
  • Memory allocated from stack is called static memory allocation.
  • While, memory allocated from heap is called dynamic memory allocation.
Can you implement IDisposable for value type ?
Structs being a value type can inherit IDisposable interface

Friday, May 26, 2017

Hosting a WCF service

A WCF service can be hosted in following ways

1. Self Hosting: 
       A WCF service can be self hosted using console application or windows forms.

        Benifit

  1.         Support all bindings.
  2.         Easy to debug no need to attach separate process
  3.         Flexi to support the life time of binding using Open() and Close method of service.


2. Hosting can be done using Window Service. --

Advantage
          Support all types of bindings
          In this type you can debug WCF  by attaching the WCF to Client

Disadvantage
  Difficult to Debug ( need to attach window service to client for debugging)
  Need to host on production server


3. Third way is hosting a WCF using IIS but in this support only HTTP binding it does not support Non HTTP Binding.
4. Using Window Activation Services, it supports all types of binding.

Thursday, May 25, 2017

Binding in WCF-21

What is Binding in WCF service?

Binding defines how the client will communicate with WCF service. Binding tell about three things in communication. There are different binding available in WCF like basiHttpBinding, wsHttpBinding, TCP,....

1. Transport Protocol (ex - HTTP, TCP, NamedPipe, MSMQ)
2. Message Encoding ( ex. text/Xml, Binary)
3. Protocol (ex. reliable messaging, transport support)

In WCF you can create your custom binding also.

For speed you can choose netTCP binding, if you have same platform on both end.

For communication client and WCF service should same configuration entry.

Configure WCF service endpoint dynamically in code

Endpoint and behavior setting can be write in code instead of config file.

As depicted below. It is written in host.

 using (ServiceHost host = new ServiceHost(typeof(CalculatorService.CalculatorService)))
            {
                ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior()
                {
                    HttpGetEnabled=true
                };


                host.Description.Behaviors.Add(serviceMetadataBehavior);
                host.AddServiceEndpoint(typeof(CalculatorService.ICalculatorService), new BasicHttpBinding(), "CalculatorService");

                host.Open();
                WriteLine("Host Started @ " + DateTime.Now.ToString());
                ReadKey();
                host.Close();
            }

And app.config file would defined as below

  <system.serviceModel>
    <services>
      <service name="CalculatorService.CalculatorService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9001"/>
          </baseAddresses>
        </host>
      
      </service>
    </services>
  

  </system.serviceModel>

Interview MPS

1. What is the benefit of MVCC?
2. Project architecture.
3. MVC is stateful or stateless
4. How ASP .Net is stateful?
5. Write the regular expression for a word which contains 'age' but age word should not captured.
6. What is the use of pdflib and pdftron?
7. Have you worked on procedure?
8. Have you worked on database?
9. Is WPF MVC or not?

Shared by Arvind


Wednesday, May 24, 2017

Unhandled Exception in WCF

If any exception occurred in WCF that is not handled than it break the communication, we can not use the proxy again, to use it we have to new its object again.

Same thing will happen in case of WCF service throwing a .Net exception that's why it is another why a WCF service should not throw a .Net exception.

It is not true for basicHttpBinding because basicHttpBinding does not have session. wsHttpBinding have secure session so in case of wsHttpBinding communication will break.

How to Handle it?

Need to handle exception at service level and should throw FaultException.

WCF interview questions

1. Explain the WCF architechture.

WCF architecture consists
2. Advantages of WCF

  1. Service Oriented
  2. Location Independent
  3. Language Independent
  4. Platform Independent
  5. Support Multiple operation
  6. WCF can maintain transaction like COM+ Does
  7. It can maintain state
  8. It can control concurrency
  9. It can be hosted on IIS, WAS, Self hosting, Windows services.
It has AJAX Integration and JSON (JavaScript object notation) support.
  • WCF can be configured to work independently of SOAP and use RSS instead.
  • To improve communication, transmission speed needs to be optimized. This is done by transmitting binary-coded XML data instead of plain text to decrease latency.
  • Object life-cycle management and distributed transaction management are applicable to any application developed using WCF.

What is the difference between WCF and Web services?

Explain transactions in WCF?

A transaction is a logical unit of work consisting of multiple activities that must either succeed or fail together.
The following are the types of the Transactions:
  1. Atomic
  2. Long Running

Phases of WCF Transaction:

  • Prepare Phase - In this phase, the transaction manager checks whether all the entities are ready to commit for the transaction or not.
  • Commit Phase - In this phase, the commitment of entities get started in reality.

What is one-way operation?

When an operation has no return value, and the client does not care about the success or failure of the invocation. WCF offers one-way operations to support this sort of fire-and-forget invocation,: once the client issues the call, WCF generates a request message, but no correlated reply message will ever return to the client. 
  1. [OperationContract(IsOneWay = true)]  
  2.     void Add(double n1, double n2);  

Explain what is DataContractSerializer?

WCF provides a message-oriented programming framework. Internally WCF represents all the messages by a Message class. When WCF transmits a message it takes a logical message object and encodes it into a sequence of bytes. After that WCF reads those bytes and decodes them in a logical object. The process forms a sequence of bytes into a logical object; this is called an encoding process. At runtime when WCF receives the logical message, it transforms them back into corresponding .Net objects. This process is called serialization. 

DataContractSerializer
WCF supports three basic serializers:
  • XMLSerializer
  • NetDataContractSerializer
  • DataContractSerializer
WCF deserializes WCF messages into .Net objects and serializes .Net objects into WCF messages. WCF provides DataContractSerializer by default with a servicecontract. We can change this default serializer to a custom serializer like XMLSerializer.
NetDataContractSerializer

NetDataContractSerializer is analogous to .Net Remoting Formatters. It implements IFormatter and it is compatible with [Serializable] types. It is not recommended for service oriented design.

What is Transaction Propagation? And how WCF support it?

Transaction propagation is the ability to propagate a transaction across the boundaries of a single service. Or in other words, we can say that a service can participate in a transaction that is initiated by a client. 

To enable transaction propagation, we need to set the value of the TransactionFlow property of the binding being used. This can be done programmatically as follows: 
  1. WSHttpBinding bindingBeingUsed = new WSHttpBinding();  
  2. bindingBeingUsed.TransactionFlow = "true";  
Or it can be done decoratively by updating the configuration file as follows:
  1.   
  2.       
  3.         "binding1" transactionFlow="true" />   


  •     






  •   The default value for the TransactionFlow property is "False".

    Do all WCF bindings support Transaction Propagation?

    No. Not all WCF bindings support transaction propagation. Only the following list of bindings support it:
    • wsHttpBinding
    • netTcpBinding
    • netNamedPipeBinding
    • wsDualHttpBinding
    • wsFederationHttpBinding

    What is WCF throttling?

    WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.

    WCF throttling provides the prosperities maxConcurrentCalls, maxConcurrentInstances, and maxConcurrentSessions, that can help us to limit the number of instances or sessions are created at the application level.


    maxConcurrentCallsThis specifies the maximum number of messages processed across the service host. The default value for this property is 16 (WCF 4.0 is improved to default is 16 * Processor Count).
    maxConcurrentInstancesThis specifies the maximum number of instances of a context object that executes at one time with the service. The default is Int32.MaxValue.
    maxConcurrentSessionsThis specifies the maximum number of sessions at one time within the service host object. The default value is 10 (WCF 4.0 increases that to 100 * Processor Count).


    What is WCF Concurrency and How many modes are of Concurrency in WCF?

    WCF Concurrency means “Several computations are executing simultaneously.

    WCF concurrency helps us configure how WCF service instances can serve multiple requests at the same time.
    We can use the concurrency feature in the following three ways:
    • Single
    • Multiple
    • Reentrant
    Single: A single request will be processed by a single thread on a server at any point of time. The client proxy sends the request to the server, it process the request and takes another request.

    Concurrency

    Multiple: Multiple requests will be processed by multiple threads on the server at any point of time. The client proxy sends multiple requests to the server. Requests are processed by the server by spawning multiple threads on the server object. 

    Reentrant: The reentrant concurrency mode is nearly like the single concurrency mode. It is a single-threaded service instance that receives requests from the client proxy and it unlocks the thread only after the reentrant service object calls the other service or can also call a WCF client through call back.

    What is Instance Context Mode in WCF?
    Answer: An Instance Context mode defines how long a service instance remains on the server.


    Whenever the client sends a request to a WCF service, what exactly happens behind the scenes? Basically after making a client request the WCF service will create a service class instance at the service that will do the operations involved and then it will return the response back to the client. In this request and response process the service instance object has been created in the process.

    The WCF framework has defined the following three Instance Context modes:

    PerCall: A new instance of the service will be created for the request from the same client or a different client, meaning every request is a new request. In this mode no state is maintained.In per-call service, every client request achieves a new dedicated service instance and its memory consumption is less as compared to other types of instance activation.


    1. [ServiceContract]  
    2. interfaceIMyContract  
    3. {...}  
    4. [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]  
    5. classMyService:IMyContract  
    6. {...}  
    Per-Session Service: A new Instance will be created for every new client session and the scope of that object will be the scope of that session.
    1. [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]  
    2. classMyService:IMyContract  
    3. {...}  
    Singleton Service: A single instance will be created for the service object that will take care of all the requests coming from the same client or a different one.

    By decorating the service with a service behavior, an Instance Context mode can be set.

    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)] 


    What is Security Implementation in WCF? How many are there?
    WCF supports following securities:
    • Message
    • Transport
    • TransportWithMessageCredential

    Message Security
    Message security uses the WS-Security specification to secure messages. The message is encrypted using the certificate and can now safely travel over any port using plain http. It provides end-to-end security.

    Transport Security
    Transport security is a protocol implemented security so it works only point to point. As security is dependent on protocol, it has limited security support and is bounded to the protocol security limitations.

    TransportWithMessageCredential:
    This we can call a mixture of both Message and Transport security implementation.

    Tuesday, May 23, 2017

    WPF interview Questions

    1. Can you explain the complete WPF object hierarchy?



    Object: - As WPF is created using .NET so the first class from which WPF UI classes inherits is the .NET object class.
    Dispatcher: - This class ensures that all WPF UI objects can be accessed directly only by the thread who own him. Other threads who do not own him have to go via the dispatcher object.
    Dependency: - WPF UI elements are represented by using XAML which is XML format. At any given moment of time a WPF element is surrounded by other WPF elements and the surrounded elements can influence this element and this is possible because of this dependency class. For example if a textbox surrounded by a panel, its very much possible that the panel background color can be inherited by the textbox.
    Visual: - This is the class which helps WPF UI to have their visual representation.
    UI Element: - This class helps to implement features like events, input, layouting etc.
    Framework element: - This class supports for templating , styles , binding , resources etc.
    And finally all WPF controls textbox , button , grids and whatever you can think about from the WPF tool box inherits from the framework element class.

    Does that mean WPF has replaced DirectX?

    No, WPF does not replace DirectX. DirectX will still be still needed to make cutting edge games. The video performance of directX is still many times higher than WPF API. So when it comes to game development the preference will be always DirectX and not WPF. WPF is not an optimum solution to make games, oh yes you can make a TIC TAC TOE game but not high action animation games.
    One point to remember WPF is a replacement for windows form and not directX.

    So is XAML meant only for WPF ?

    No,XAML is not meant only for WPF.XAML is a XML-based language and it had various variants.
    WPF XAML is used to describe WPF content, such as WPF objects, controls and documents. In WPF XAML we also have XPS XAML which defines an XML representation of electronic documents.
    Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross-platform browser plug-in which helps us to create rich web content with 2-dimensional graphics, animation, and audio and video.
    WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this XAML and invokes workflow accordingly.

    Can you explain the overall architecture of WPF?



    What is the need of WPF when we had windows forms?

    CodeRemember: - ABCDEFG
    A - Anywhere execution ( Windows or  browser application)
    B - Bindings ( less coding)
    C - Common look and feel ( resource and styles) -- one style can be bind to all text box
    D - Declarative programming (XAML)
    E - Expression blend animation ( Animation ease)
    F - Fast execution ( Hardware acceleration)
    G - Graphic hardware independent ( resolution independent)

    Explain the difference between static and dynamicresource?

    static resource declared in xaml while dynamic resource can be set from code behind.

    When should we use static resource over dynamic resource ?

    Dynamic resources reduce application performance because they are evaluated every time the resource is needed. So the best practice is use Static resource until there is a specific reason to use dynamic resource. If you want resource to be evaluated again and again then only use dynamic resource.

    What are the benefits of MVVM?

    Separation of concern: -
    Increased UI Reusability: 
    Automated UI Unit testing: 


    Monday, May 22, 2017

    SOAP Fault

    WCF serializes the exception in SOAP fault because exception are not allowed to be passed by WCF.

    SOAP  fault are in XML format and platform independent. Soap fault contains

    1. Fault Code
    2. Fault Reason
    3. Detail Element etc.

    Detail element can be used to include any custom xml.

    SOAP are formatted based  on SOAP 1.1. and 1.2
    To view SOAP fault messages we need to enable message logging.
    See How to enable Message Logging

    You can see SOAP 1.1  fault message in .svcLog at the path what we have given in webconfig file.

    If we have includeExceptionDetailInFault is set to false than the fault message for Calculator service would be like that


    If includeExceptioDetailInFault is true than the fault message would be like that



    You can see SOAP 1.2 messages after changing the binding to wsHttpBinding.


    After changing the binding, SOAP message will not show you the exact reason of exception, as depicted in above picture. Even includeExceptionDetainInFault is true.


    By default security is on here you can see log message after only setting the security to None. What log message is appear on browser may be different for SOAP fault. In case of of wsHttpBinding  and with security it shows the correct message on browser but doesn't show correct error message in SOAP fault until unless you set Security to None in host app.config file even you have set includeExceptionDetainInFault to true.




    After setting the Security to None the message would be like that.



    If include includeExceptionDetailInFaults is false and  Security is None than below SOAP 12. would received








    Enable tracing and Logging in WCf-9

    To view SOAP fault messages we need to enable message logging in client or in service host.

    1. Open the webconfig file by right click then click on Edit WCF Configuration and select Diagnostics.
    2. Enable Auto Log Flush.
    3. Enable Message Logging
    4. Enable Tracing





    Now expand Diagnostic and Select Message Logging

    1. Set LogEntireMessage =true

    HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

    Solution:


    <system.webServer>
        <defaultDocument>
          <files>
            <add value="WebForm1.aspx" />
          </files>
        </defaultDocument>
        <directoryBrowse enabled="false" />
      </system.webServer>

    In place of WebForm1.aspx you need to put your webform name.

    HTTP could not register URL http://+:10001/. Your process does not have access rights to this namespace

    Solution : Open the Visual Studio IDE with 'Run as Administrator' and reopen your solution. It worked for me.

    Endpoints in WCF

    All the communication in WCF occurs through endpoints.

    Endpoint consist three things

    1. Address : Specify the web address through which WCF service can be accessed. This is an URL
    2. Binding : Specify how client should bind with WCF service. WCF provides different binding like netTCPBinding, basicHttpBinding,msmqBinding etc.
    3. Contract : WE need to give interface name of WCF service here.

    Example :

    <endpoint address="http://localhost:9001/CalculatorService" binding="basicHttpBinding" contract="CalculatorService.ICalculatorService"/>       

    Thursday, May 18, 2017

    Layout in WPF

    There are five types of layout. All layout controls have a common base class named panel.

    1. Stack Panel
    2. Wrap Panel
    3. Canvas
    4. Dock Panel
    5. Grid

    Stack Panel -  

    Stack panel shows the elements in the form of stack. Orientation can be change Horizontal or Vertical.

    Wrap Panel-

    Wrap panel wrap the control according to available space.

    Canvas -

    On canvas, you can put the element on a particular position by setting top and left property.

    Dock Panel- 

    This is similar to the functionality of dock property of windows form. Multiple controls can be placed with different dock like top,bottom, left, right or full.

    Grid -

    We can place the control in grid in the form of row and column.





    Wednesday, May 10, 2017

    Exception handling in WCF

    WCF does not send exception detail in detail instead it throw a fault exception due to security reason. but some time we need the detailed exception for debugging purpose. We can achieve this using IncludeExceptionDetailInFault=True in config file.

    <behavior name="includeExceptionDetails">
    <serviceDebug includeExceptionDetailInFault="true" />
    </behavior>

    Also we can do it using ServiceBehavior attribute with IncludeExceptionDetails=true in class file.


    What happens when an exception occurs in a WCF service?
    OR What is SOAP fault?
    How are WCF service exceptions reported to client application?
    Ans Whenever any exception occured in WCF the exception is serialized in SOAP fault before
    returned to the client and bydefault exception detail not included in the SOAP fault due to
    security reaosn


    Why use FaultExceptions?
    This type of solution is very helpful in situations where the client and server are of different platforms. For examle, you might have client applications in Java or PHP. So, if there is any .NET specific exception in the service, we can't send the fault exception to the client directly, since client will not understand .NET based exceptions. They only need to know that an exception has occurred and if possible, a reason for it. So it becomes very important to use FaultExceptions normally only or use the strongly-typed fault exceptions.


    What is Global Error Handling
    Global Error Handling is writing the error handler code at centralize location instead for each function. We can do it using IErrorHandler interface.

    CalculatorService

    ExtensionDataObject in WCF

    We use IExtensionDataObject to preserve unknown elements during serialization and deserialization
    of DataContract

    On the service sisde, at the time of deserialization the unkwon elements from the client are
    store in ExtensionDataObject.To send data to the client, the service has to serialize data into XML.
    During this serialization process the data from ExtensionObjectOject is serialized into XML as it was
    provided at the time of service call.

     To use Extension object we need to make service class singleton by using ServiceBehavior attribute

    ServiceBehavior (InstanceContextMode = InstanceContextMode.Single)

    Drawback of IExtensibleDataObject

    Since the extension data is store in memory, the attacker may flood the server with request that contains large number of unknown elements which can lead to system out of Memory.

    How to turn of IExtensibleDataObject

    One way is removed IExtensibleDataObject from each class where it is used. And second one is through config file.

    <behaviors>
    <serviceBehaviors>
    <behavior name="ignoreExtensionData">
     <dataContractSerializer ignoreExtensionDataObject="True" />
    </serviceBehaviors>
    </behaviors>


    Third way is using ServiceBehaviors attribute
    [ServiceBehaviors (IgnoreExtensionDataObject="true")]

    Backward compatible WCF contract changes


    Most importantly, the following operations will not cause old clients to break:

    Service contracts (methods)

    Adding method parameters: No break,The default value will be used when called from old clients.
    If you have add a parameter in a function than WCF use default value concept automatically for this method.

    Removing methods parameters: The values sent by old clients will be ignored silently.

    If you have removed any parameter from any existing method, than client still not break. The extra parameter will be ignore by service itself.

    Adding new methods: Obviously, old clients won't call them, since they don't know them.

    If you have added new method in service than client still not break, since client has not any knowledge of this new method.

    Modifying parameter types : An exception will occur if the incoming type from the client cannot be converted to the parameter data type.

    If you have modify the parameter type whether it is passed or return WCF will try to convert passed parameter to the desired if it does not succeed than throw an error,

    Adding new methods: Obviously, old clients won't call them, since they don't know them.

    Removing existing methods: An exception will occur.


    Data contracts (custom classes for passing data)
    1. Adding non-required properties. No error

    1. Removing non-required properties. : throw exception

    Thus, unless you mark the new DownloadLink field as IsRequired (default is false), your change should be fine.

    Difference Between DataContract and MessageContract

    In datacontract we don't have much control over SOAP messages, only name and order
    can be change using datacontract. While MessageContract gives full control over
    SOAP messages by providing access to SOAP header and body sections using MessageHeader
    and MessageBodyMember attributes. If you want to include additional information in SOAP header
    than use SOAP message.

    Why do we use Message Contract in WCF
    MessageContract gives full control over the SOAP messages. For example, it allows is to
    include custom information in the SOAP header.

    What kind of custom information?
    User credential to invoke the service.

    Why do you need to pass user credential in the header? Can't you pass them as method parameters?
    We can, but user credentials are periphery  to what the method has to do. So, it would make more
    sense to pass them out of band in the header, rather than as additional parameters.

    Soap messages are in xml format, so anyone can read the credential? How will you protect 
    sensitive data?
    Using MessageContract we can sign and encrypt messages. Use ProtectionLevel named parameter.

    Tuesday, May 9, 2017

    MessageContract

    A message contract used to control the structure of response and request, You can send information in soap header using message contract.

    With the help of message header we can implement security by passing credential in header part.The SOAP header is implemented in the namespace system.web.services.protocol.

    MessageHeader and MessageBodyMember?

    A Message Header is applied to a member of a message contract to declare the member within the message header.

    [MessageContract]
    public class EmpRequest
    {
    [MessageHeader]
    public string EmpId;
    }


    Message Body Member

    A Message Body Member is applied to the member of a message contract to declare the members within the message body.

    [MessageContract]
    public class EmpResponse
    {
    [MessageBodyMember]
    public Emp Obj;
    }


    When you go for Message Contract and when for Data Contract

    If you want more control on your SOAP Message then you should go for a Message Contract.Do not mix message contract and data contract.

    Friday, May 5, 2017

    Four Different ways to use knowntype attribute

    Data Contract -: 

    Data Contract attribute is used for the type of data that will be sent/received between a service and a client. Some time data is not know to client an example is derived type, in that case there will be some problem in De-Serialization. De-Serialization engine could not recognize the derived data contract and will threw error.
    • Global Level
      • Using Code at base type
      • Using Web.config
    • Service Contract Level
    • Operation Contract Level


    Global using Code


    [KnownType(typeof(Santro))]
    [KnownType(typeof(Maruti))]
    [DataContract]
    public class Car
    {
    }
    [DataContract]
    public class Santro : Car
    {

    [OperationContract]
    void GetModal( );
    }
    [DataContract]
    public class Maruti : Car
    {
    [OperationContract]
    void GetModal( );
    }

    using on base type it is applicable for all functions.

    Global Level using config


    <system.runtime.serialization>
         <dataContractSerializer>
                      <declaredTypes>
                                 MyService.Car, 
                                                    MyService, Version=, 
                                                    Culture=Neutral, PublicKeyToken=null”>
                                             <knownType type=”MyService.Santro, 
                                                    MyService, Version=<version here>, 
                                                    Culture=Neutral, PublicKeyToken=null” />
                                             <knownType type=”MyService.Maruti, 
                                                    MyService, Version=<version here>, 
                                                    Culture=Neutral, PublicKeyToken=null” />
                                </add>
                      </declaredTypes>
         </dataContractSerializer>
    </system.runtime.serialization>


    Service Contract 


    [ServiceKnownType(typeof(Car))]
    [ServiceKnownType(typeof(Truck))]
    [ServiceContract]
    public Interface ICarService
    {
    [OperationContract]
    Vehicle AddNewCar(Car car);

    [OperationContract]
    bool UpdateCar(Car car);
    }
    will  be applicable for all functioned declared within this interface but not for other interfaces.


    Operation Contract Level


    [ServiceContract]
    public Interface ICarService
    {
          [ServiceKnownType(typeof(Santro))]
          [ServiceKnownType(typeof(Maruti))]
          [OperationContract]
          Vehicle AddNewCar(Car car);
          [OperationContract]
          bool UpdateCar(Car car);  
    }

    will be applicable only for contract on which ServiceKnownType is defined.

    Wednesday, May 3, 2017

    use of switchValue in WCF

    switch value used to specify which type of messages you want to write in log.
    Possible values are All, Error,Information etc.

    knowntype attribute in WCF

    KnownTypeAttribute class allows you to specify the types that should be included for consideration during deserialization.
    The WCF service generally accepts and returns the base type. If you want to use inherired type at this point
    than you have to use knowntype attribute.

    Life without knowntype
    Wihtout knowntype, you can not use a subclass of contract class, with the help of
    knowtype you can make subclass of contract class.

    Example :

    using System.Runtime.Serialization;  
    using System.ServiceModel;  
      
    namespace WcfDemo  
    {  
        [ServiceContract]  
        public interface IEmp  
        {  
            [OperationContract]  
            Emp GetEmp();  
      
            [OperationContract]  
            Emp  GetEmpById(Emp  builder);  
        }  
          
        [KnownType(typeof(DayBasic))]  
        [KnownType(typeof(ContractBasis))]  
        [DataContract]  
        public class Emp  
        {  
            [DataMember]  
            public int EmpId { get; set; }  
      
            [DataMember]  
            public string EmpName { get; set; }  
      
            [DataMember]  
            public string MobileNo { get; set; }  
      
            public enum EmpType { DayBasic = 1, ContractBasis = 2 }  
        }  
      
        public class Permanent : Emp
        {  
            public int AnnualSalary{ get; set; }  
         
        }  
      
        public class ContractBasis : Emp  
        {  
            public int TotalAmount { get; set; }  
            public int DayComplited { get; set; }  
        }  
    }  

    Followers

    Link