Archive

Archive for the ‘WCF’ Category

About InstanceContextMode in WCF

December 8, 2014 Leave a comment

InstanceContextMode tells how the instanceContext object need maintain/handle/available for the incoming messages.

What is the Use of InstanceContextMode?

Basically it tell how the object create for the request/response must be handle across the service.

In our Business requirement let see what are all different type of requirement you may face

1) For some of you request you may need to maintain information for the each user and its scope of information is limited to each user (SESSION)

EX:- While a client request to service first time new instance will get created after that request come form same client will handle by the same instance until it gets disconnected/Expired.

2) Some time you need to maintain the information common to all user request to share the information across all the clients

EX: Update each share value to the requested users.

3) Some other request just you want to pass information to service, which may return the value back to client or may not based on your need.

Let see how we can implement it using WCF InstanceContextMode
There are 3 different type of InstanceContextMode

1) PerCall
– For every request separate InstanceContext object gets created and destroyed after respond back to the client, just Request/Response pattern.
– Decorate [ServiceBehaviour(InstanceContextMode=InstanceContextMode.PerCall)] for the class that you want to include the InstanceContextMode.

2) PerSession
– When first time request comes from the client new object will gets created, after that when ever subsequent call comes from the same client, the request are handle by the same instance object. This object will alive in service untill the client get disconnect or that instance object goes to ideal mode for some time. Default session expire time is 10 min.
– Decorate [ServiceBehaviour(InstanceContextMode=InstanceContextMode.PerSession)] for the class that you want to include the InstanceContextMode.

3) Single
– This object is global for all the request/response. When ever new request are comes from the client it won;t create new instance because of that performance gets improved.
– Decorate [ServiceBehaviour(InstanceContextMode=InstanceContextMode.Single)] for the class that you want to include the InstanceContextMode.

Note:-

You need to decorate corresponding servicebehaviour attribute in the class, else it will behave as request/response fromat and also based on how you create object in client side to call the service.

To download the sample code click here

Advertisements

Callback in WCF using wsDualHttpBinding

December 5, 2014 Leave a comment

When shall we go for wsDualHttpBinding?

Your service need to perform lot of operation after getting the information from the client side, which consume more time to return result back to the client.

Normally time consuming operation in server side will block the client to perform other operation. So  ‘wsDualHttpBinding’ will be ideal solution for this kind of problem.

Suppose if your client not depend on the result produce by the service at that time we can go for ‘wsDualHttpBinding’ .

If you need to implement callback between client and service at that time we can go for ‘wsDualHttpBinding’.

Because of some operation (or) result taking place in server side must not affect the client side access or other request the ideal choice is ‘wsDualHttpBinding’

wsDualHttpBinding is binding which sends the request in one http channel and response will be sent back to the client in another http channel

 

If you are using ‘dualHttpBinding’ you need to create two interface one interface is to get the request from the client and one more is send the response back to the client as callback

The below mentioned interface is to send the response back to the client and the ‘OperationalContract’ used to send the response back to the client must be decorated with the property ‘IsOneWay=true’ as shown below.

CalbackInterface

Another Interface mentioned below is to get the request from the client, this interface  must also be decorated with the property ‘IsOneWay=true’  inside the ‘OperationalContract’ attribute as mentioned below. Also we need to refer using which interface (or) channel we are going to send the response back to the client. We already declare the callback interface now need to establish relationship with the ‘ServiceContract’ as mentioned below.

ServiceContract

In the above code we are mentioned ‘INotificationServiceCalback’ as the callback interface by using ‘CallbackContract’ property of ServiceContract.

 

In the web.Config we need to specify ‘wsDualHttpBinding’ in the binding property.

WebConfig

 

The Implementation of service contract

ImplementationofDuplex

You can find the Code sample here

Unhandled exception in WCF

February 6, 2014 Leave a comment

We will call Business logic layer or DAL through the Web service or WCF if any fault occurs in any layer that uncaught exception will propagate upto service layer, normally at service layer uncaught exception will converted into soap fault exception. Once uncaught exception reaches service layer, it may or may not be exposed to the client, depending upon ‘IncludeExceptionDetailsInFaults’ boolean value which define under the <ServiceBehaviour> section.

By default service won’t share the exception detail with the client since ‘IncludeExceptionDetailsInFaults=False’. This is because if you get any exception in DAL like connection string based exception or any SQL operation error it will directly exposed to client which is not advisable. So when ‘IncludeExceptionDetailsInFaults’ is set to False service general exception information like ‘InternalServiceFault’ will throw to the client, but the exception we received was not very useful.

ServiceDebug

when you want to debug what kind of exception exactly you are getting you can turn on the ‘IncludeExceptionDetailsInFaults’. Once you turn on you can able to
see all kind of exception detail, its stacktrace are also included in the general exception information.

Suppose if you are using ‘wsHttpBinding’ it will use session at that time if you face unhandled exception you can’t use your exception any more, similarly your client
channel also become useless.

Error Message: Retrieving the COM class factory for component with CLSID {C5CBD7B2-490C-45F5-8C40-B8C3D108E6D7} failed due to the following error: 80040154 Class not registered

June 21, 2013 Leave a comment

This error is because of x64 bit machine. To fix this error, Right-click the project node in Solution Explorer and click Properties. Click on Configuration Properties.Click on Configuration Manager. click on New under Platform and change it to x64 and see if it fixes the problem. If it doesn’t then change the platform to x86.

Categories: WCF

Steps to create and deploye Windows Service

June 21, 2013 Leave a comment

To create and deploy the WCF Service as the Windows Service in step by step. The following article describe about.

  1. Steps to Create Windows Service using WCF
  2. Steps to Deploy Windows Service using installutil.exe

Steps to Create Windows Service using WCF

  • Create new project using VS2012, Select File > New Project from the Menu.

New Project

  • Select Windows Service template from New Project dialog.

Create Winodw Service

  • Right click on designer and select Property and set ServiceName and Name

ServiceInstaller Property

  • Drag an EventLog component to the designer, from the Components section of the Toolbox.

Drag and Drop EventViewer in Design screen

  • Press F5 and use the below code.

Sample Code

public MyFirstWindowsService()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("WSMessage"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "WSMessage", "NewWSLog");
            }
            eventLog1.Source = "WSMessage";
            eventLog1.Log = "NewWSLog";

        }

        protected override void OnStart(string[] args)
        {
            string str = "Service Start at :" + DateTime.Now.ToString();
            eventLog1.WriteEntry(str);

        }

        protected override void OnStop()
        {
            string str = "Service Stopped at :" + DateTime.Now.ToString();
            eventLog1.WriteEntry(str);
        }

Now Windows service is ready and it is ready to write message to Event handler while start and stop event is triggered.

Steps to Deploy Windows Service using installutil.exe

  • Right-click Service1.cs and select View Designer from Solution Explorer

Select Property for Service.cs file from solution explorer

  • Right-click, and then click Add Installer in View Designer Screen. The two installers is added to your project inside ProjectInstaller.cs screen.
  • Right click on serviceInstaller1 from ProjectInstaller.cs and make sure the Service Name property is set to MyFirstWindowsService and Start Type property is set to Automatic.

Select process PropertyServiceInstaller Property

  • Right click on serviceProcessInstaller1 from ProjectInstaller.cs and Set the Account property to LocalSystem. This will cause the service to be installed and to run on a local service account.

ServiceProcessInstallerProperty

  • Build the project

Steps to install

  • Open the Developer Visual Command Prompt in Administrator mode
  • installutil.exe C:\MyNewService\bin\MyNewService.exe
  • Open the Control panel and check the ‘MyNewService’ is started else start service.
Categories: WCF Tags:

The maximum message size quota for incoming messages (65536) has been exceeded.

January 15, 2013 Leave a comment

The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.

Make sure that the readerQuotas settings are the same both on client and server side.Also if you are transferring some file or large object consider to increase the httpRunTime elements maxRequestLength value in the system.web section.

Configure the corresponding binding section in Web.Config  as below

<binding name="Binding1" closeTimeout="00:10:00" openTimeout="00:10:00"
      sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647" portSharingEnabled="true">
      <readerQuotas maxArrayLength="2147483647" maxNameTableCharCount="2147483647"
          maxStringContentLength="2147483647" maxDepth="2147483647"
          maxBytesPerRead="2147483647" />
      <security mode="None" />
    </binding>

Contract in WCF

November 23, 2012 Leave a comment

Contract

A contract is a Standard way of describing way a service can do. In the real world contract is an agreement between two or more parties about doing service or some other things. Similarly in WCF it is the agreement between the Service and Clients, through which message can be passed to and from service endpoints.

The Contract consist of three major types

1)      Service contract

2)      Data contract

3)      Message contract

4)      Polices and binding

Service Contract

Service contract is a class or an interface that specifies the direction and type of message. This contract describes the operation, that can be avail by our world. Example: – To know the current market price based on the company shares. So Service contract is a gate way to the external application to avail the functionality and operations and there must be atleast one operation contract.

Data Contract

Data Contract describe data structures that are used by the service to communicate with clients. It also describes the custome data type which is exposed to the client. The system define datatype are automatically identify by the client, because it is already define in XML schema defination language doument(XSD), but custom created class or datatype cannot be identified by the client.

Example:- Product datatype, by using  DataContract client can understand that Product is the custom datatype for a method that is returning or passing the parameter.

If ‘DataMember’ attributes are not specified for a properties in the class that property can’t be passed to or from web service.

For more:- http://msdn.microsoft.com/en-us/library/ms733127(v=vs.100).aspx

Message Contract:-

Message contract allow the service to interact directly with messages. It can be typed or untyped and are useful in interoperability. Message contract provide control over the soap header and bodies. MessageContracts are used to explicitly describe the soap message format.

WCF runtime provide SOAP message formatting for comminication between client and service.If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

For more:- http://msdn.microsoft.com/en-us/library/ms730255(v=vs.100).aspx

Policy and Binding

Policies and bindings stipulate the conditions required to communicate with a service. For example, the binding must (at a minimum) specify the transport used (for example, HTTP or TCP), and an encoding. Policies include security requirements and other conditions that must be met to communicate with a service.

%d bloggers like this: