Saturday, June 9, 2012

Duplex Client Program

First We have to  develop a Duplex communication service  then now we have consume that service.so please following steps:
  1. In a new website add service reference for creating Proxy.
  2. Design the new form according to requirement sothat we pass inputs as well as outputs from wcf service.
  3. Add a new class and implement callback interface for Getting or Posting results.
Write following Code in MyCall.cs

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;

      /// <summary>
      /// Summary description for MyClass
      /// </summary>
        public class MyClass : CourierTrackNamespace.ICourierTrackCallback
        {
            public MyClass()
            {
                       
            }
         public static string Info1;
         public void Result(string info)
         {
             Info1 = info;
          }
         }


                                  
Write following Code in Default.cs
           using System;
           using System.Collections.Generic;
           using System.Linq;
           using System.Web;
           using System.Web.UI;
           using System.Web.UI.WebControls;
          using System.ServiceModel;

          public partial class _Default : System.Web.UI.Page
          {
           protected void Page_Load(object sender, EventArgs e)
          {

           }
          protected void Timer1_Tick(object sender, EventArgs e)
         {
              lblres.Text = MyClass.Info1;
          }

           protected void btnOrder_Click(object sender, EventArgs e)
          {
           InstanceContext ic = new InstanceContext(new MyClass());
           CourierTrackNamespace.CourierTrackClient obj = new     CourierTrackNamespace.CourierTrackClient(ic);
           obj.PlaceOrder(int.Parse(txtinput.Text));
           Timer1.Enabled = true;
           }
         }

Write following Code in Default.aspx

  • Here Some Points to Noted:
             Timer-interval=1000; and Enabled view=false;

 

Friday, June 8, 2012

.Net Remoting


Remoting is a technology that helps you to communicate between different applications regardless of whether they reside on the same computer or on different computers. Even these applications can have different operation systems.
Remoting needs:
1. A server object that expose the functionality to callers outside its boundary
2. A client that makes calls to the server object
3. A transportation mechanism to pass the calls from one end to the other

Developing a sample for .Net Remote Communication:

 Create a Remotable Object:

A remotable object is an object that inherits from MarshalByRefObject.
Create a new C# class library project. Add a class called Test, and put in the following code. Add a reference to System.Runtime.Remoting in the project, otherwise the TcpChannel will not be found. Compile the class to make sure you have everything correct.

 Please follow these steps to write a Remoting code:

 

1- Create a class library name it Service : in class library you just have a class named Test
namespace Service
{
public class Test:MarshalByRefObject
{
public Test()
{
Console.WriteLine("New Object!");
}
public string PrintYourAddress()
{
string myaddress = AppDomain.CurrentDomain.BaseDirectory;
Console.WriteLine("This is myaddress " + myaddress);
return myaddress;
}
public void WriteInServer()
{
Console.WriteLine("I wrote time in server " + DateTime.Now.ToShortTimeString());
}
}
}
2- Create a console application name it Server: you have to write some code in Main method. You need to add System.Runtime.Remoting to your references. Furthermore you need to add Service library to this project.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
namespace Server
{
class Program
{
static void Main(string[] args)
{
HttpChannel ch = new HttpChannel(4000);
ChannelServices.RegisterChannel(ch);
//because this is written in server so we need to use Service type methods
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Service.Test), "ServiceURI", WellKnownObjectMode.Singleton);
Console.WriteLine("Server is Started...");
Console.ReadLine();
}
}
}
3- Create a windows application name it Client: First of all you need to add reference service. Add two buttons and in button clicks add these code also you need to add some code in FormLoad event
Test t;
private void Form1_Load(object sender, EventArgs e)
{
RemotingConfiguration.RegisterWellKnownClientType(typeof(Test), "http://localhost:4000/ServiceURI");
t= new Test();
}
private void button1_Click(object sender, EventArgs e)
{
t.WriteInServer();
}
private void button2_Click(object sender, EventArgs e)
{
string str = t.PrintYourAddress();
MessageBox.Show(str);
}

Duplex Contract/Communication

A duplex Contract defines two logical sets of operations: A set that the Service exposes for the Client to call and a set that the Client exposes for the Service to call. The programming model for defining a duplex Contract is to split each set in a separate type (each type must be a class or an interface) and annotate the contract that represents the service's operations with ServiceContractAttribute, referencing the contract that defines the client (or callback) operations. In addition, ContractDescription contains a reference to each of the types thereby grouping them into one duplex Contract.
Similar to Bindings, each Contract has a Name and Namespace that uniquely identify it in the Service's metadata.
Each Contract also has a collection of ContractBehaviors that are modules that modify or extend the contract's behavior.

Duplex Communication
Duplex Communication
 Some Important Points to note:

  • Sender and Receiver can exchange multiple messages.
  • Sender and Receiver establishes  a socket for to communication.
  • A duplex service contract is a message exchange pattern which both endpoints can send messages to the other independently. 
  • It gives Rich Communication[One-Way Communication ].
  • It uses dual channel Binding.eg: WsdualBinding.
  • Decalre the Callback interfece.
  • Add callbackcontract property of ServiceContractAttribute to indicate the callback interface
  • CallOperationcontext.Current.GetcallbackChannel to get the callback interface.
  • Fire callback interface methods in free your time.
  The following is an example of a duplex contract.
 Steps for developing duplex contract:
  1. Start new website -->wcf service.
  2. Delete the default wcf service and add new wcf service.In interface file create service contract with methods to run at server and an additional interface which is a callbackinterface for  this service wcf provides optio in servicecontract and other areas to specify perticular communication.
  3. Implement the main inteface according to requirement.
  4. Goto Config file and change wsHttpBinding to wsDualBinding because this binding only provides the Duplex style of communication.
          Write following code  in  ICourierTrack.cs
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Runtime.Serialization;
            using System.ServiceModel;
            using System.Text;

           [ServiceContract(SessionMode=SessionMode.Required,CallbackContract
               =typeof(ICourierTrackcallback))]
            public interface ICourierTrack
           {
               [OperationContract]
             void PlaceOrder(int value);
            }
               //callback interface
             public interface ICourierTrackcallback
             {
                        [OperationContract(IsOneWay=true)]
              void Result(string info);
            }

          Write following code  in  CourierTrack.cs


             using System;
             using System.Collections.Generic;
             using System.Linq;
             using System.Runtime.Serialization;
             using System.ServiceModel;
             using System.Text;

            [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
           public class CourierTrack : ICourierTrack
           {
           public ICourierTrackcallback callback
           {
            get
           {
            return OperationContext.Current.GetCallbackChannel<ICourierTrackcallback>();
            }
          }


          public void PlaceOrder(int value)
         {
            callback.Result("Special Order Accepted by Manager");
           System.Threading.Thread.Sleep(7000);
           callback.Result("Order Dispatched by dispatch team-ref- a23sd-");
           System.Threading.Thread.Sleep(7000);
           callback.Result("Order in Air-ref-accecing-"+value.ToString());
           System.Threading.Thread.Sleep(4000);
           callback.Result("Order recd by local client- Thanks U");
          }
        }


   Write following code  in  CourierTrack.svc
       <%@ ServiceHost Language="C#" Debug="true" Service="CourierTrack"                      CodeBehind="~/App_Code/CourierTrack.cs" %>
 
   Write following code  in  webconfig file
       <system.serviceModel>
       <services>
       <service behaviorConfiguration="ServiceBehavior" name="Service">
       <endpoint address="" binding="wsDualHttpBinding" contract="IService">
       <identity>
       <dns value="localhost"/>
       </identity>
       </endpoint>
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
        <service behaviorConfiguration="CourierTrackBehavior" name="CourierTrack">
        <endpoint address="" binding="wsDualHttpBinding" contract="ICourierTrack">
         <identity>
         <dns value="localhost"/>
         </identity>
            </endpoint>
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
           </service>
         </services>
          <behaviors>
           <serviceBehaviors>
          <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
           <serviceDebug includeExceptionDetailInFaults="false"/>
           </behavior>
          <behavior name="CourierTrackBehavior">
         <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
        </serviceBehaviors>
       </behaviors>
       </system.serviceModel>

ScreenShots for Developing Duplex service:





Thursday, June 7, 2012

Instance Management

                             Instance management refers to the way a service handles a request from a client. Instance management is set of techniques WCF uses to bind client request to service instance, governing which service instance handles which client request. It is necessary because application will differ in their need for scalability, performance, durability, transaction and queued calls.

                             In wcf this refers to how wcf creates instances for serving the requests.Wcf provides almost all instance patterns for building effective wcf service.

Modes Of Service Instances :

  • Per-Call instance mode
  • Per-Session instance mode
  • Singleton Instance Mode

1. Per-Call instance mode:  

 A new service instance is created and destroyed for every call.

  • When we configure a WCF service as per call, new service instances are created for every method call you make via a WCF proxy client.
  • The WCF client makes the first method call (method call 1).
  • A new WCF service instance is created on the server for this method call.
  • The WCF service serves the request and sends the response and the WCF instance is destroyed and given to the garbage collector for clean up.
  • Now let’s say the WCF client makes a second method call, a new instance is created, the request is served, and the WCF instance is destroyed.
  • In other words, for every WCF client method call, a WCF service instance is created, and destroyed once the request is served.

Per-Call
                                                             Per-Call Service


2.Per-Session instance mode :

One Service instance per clients.Clients can't share instance with other clients.
  • The client creates the proxy of the WCF service and makes method calls.
  • A WCF service instance is created which serves the method response.
  • The client makes one more method call in the same session.
  • The same WCF service instance serves the method call.
  • When the client finishes its activity, the WCF instance is destroyed and served to the garbage collector for clean up.
Per-Session
Per-session Service

3. Singleton Instance Mode:

All clients share same service instance and use InstanceContextMode of ServiceBehavior attribute to indicate it.

  • WCF client 1 requests a method call on the WCF service.
  • A WCF service instance is created and the request is served. The WCF service instance is not destroyed, the service instance is persisted to server other requests.
  • Now let’s say some other WCF client, e.g., client 2, requests a method call.
  • The same WCF instance which was created by WCF client 1 is used to serve the request for WCF client 2. In other words, only one global WCF server service instance is created to serve all client requests.
Singleton Service

Singleton Service



Monday, June 4, 2012

Fault Contract

                         Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.
In order to support interoperability and client will also be interested only, what wents wrong? not on how and where cause the error.
By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.
Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error accorded in the service to client. This help as to easy identity the what error has accord. Let us try to understand the concept using sample example.
Step 1: I have created simple calculator service with Add operation which will throw general exception as shown below
//Service interface
[ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
//Service implementation
 
 public  class SimpleCalculator : ISimpleCalculator
    {
    
        public int Add(int num1, int num2)
        {
            //Do something
            throw new Exception("Error while adding number");
            
        }

    }

Step 2: On client side code. Exceptions are handled using try-Catch block. Even though I have capture the exception when I run the application. I got the message that exceptions are not handled properly.

try
   {
      MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy
       = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
      Console.WriteLine("Client is running at " + DateTime.Now.ToString());
      Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
      Console.ReadLine();
   }
   catch (Exception ex) 
   {
      Console.WriteLine(ex.Message);
      Console.ReadLine();
   }
 
 
 
Step 3: Now if you want to send exception information form service to client, you have to use FaultException as shown below.
        public int Add(int num1, int num2)
        {
            //Do something
            throw new FaultException("Error while adding number");
            
        }
Step 4: Output window on the client side is show below.

 
 
Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.
  • Define a type using the data contract and specify the fields you want to return.
  • Decorate the service operation with the FaultContract attribute and specify the type name.
  • Raise the exception from the service by creating an instance and assigning properties of the custom exception.
Step 6: Defining the type using Data Contract
    [DataContract()]
    public class CustomException
    {
        [DataMember()]
        public string Title;
        [DataMember()]
        public string ExceptionMessage;
        [DataMember()]
        public string InnerException;
        [DataMember()]
        public string StackTrace;        
    }
Step 7: Decorate the service operation with the FaultContract
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        [FaultContract(typeof(CustomException))]
        int Add(int num1, int num2);
    }
Step 8: Raise the exception from the service
        public int Add(int num1, int num2)
        {
            //Do something
            CustomException ex = new CustomException();
            ex.Title = "Error Funtion:Add()";
            ex.ExceptionMessage = "Error occur while doing add function.";
            ex.InnerException = "Inner exception message from serice";
            ex.StackTrace = "Stack Trace message from service.";
            throw new FaultException(ex,"Reason: Testing the Fault contract") ;
            
        }
Step 9: On client side, you can capture the service exception and process the information, as shown below.
   try
   {
      MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy 
      = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
       Console.WriteLine("Client is running at " + DateTime.Now.ToString());
       Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
       Console.ReadLine();
    }
    catch (FaultException<MyCalculatorService.CustomException> ex)
     {
        //Process the Exception
     }

Message Contract

Message

Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination.
WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP message contain Envelope, Header and Body.SOAP envelope contails name, namespace,header and body element. SOAP Hear contain important information which are not directly related to message. SOAP body contains information which is used by the target.
Diagram Soap envelope

Message Pattern

It describes how the programs will exchange message each other. There are three way of communication between source and destination
  1. Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
  2. Request/Replay - It is two way communications, when source send message to the target, it will resend response message to the source. But at a time only one can send a message
  3. Duplex - It is two way communication, both source and target can send and receive message simultaniouly.

What is Message contract?

As I said earlier, WCF uses SOAP message for communication. Most of the time developer will concentrate more on developing the DataContract, Serializing the data, etc. WCF will automatically take care of message. On Some critical issue, developer will also require control over the SOAP message format. In that case WCF provides Message Contract to customize the message as per requirement.
WCF supports either RPC(Remote Procedure Call) or Message style operation model. In the RPC model, you can develop operation with Ref and out parameter. WCF will automatically create the message for operation at run time. In Message style operation WCF allows to customize the message header and define the security for header and body of the message.

Defining Message Contract

Message contract can be applied to type using MessageContract attribute. Custom Header and Body can be included to message using 'MessageHeader' and 'MessageBodyMember'atttribute. Let us see the sample message contract definition.
[MessageContract]
public class EmployeeDetails
{
    [MessageHeader]
    public string EmpID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public string Designation;
    [MessageBodyMember]
    public int Salary;
    [MessageBodyMember]
    public string Location;
}
When I use this EmployeeDeatils type in the service operation as parameter. WCF will add extra header call 'EmpID' to the SOAP envelope. It also add Name, Designation, Salary, Location as extra member to the SOAP Body.

Rules :

You have to follow certain rules while working with Message contract
  1. When using Message contract type as parameter, Only one parameter can be used in servicie Operation
    [OperationContract]
    void SaveEmployeeDetails(EmployeeDetails emp);
    
  2. Service operation either should return Messagecontract type or it should not return any value
    [OperationContract]
    EmployeeDetails GetEmployeeDetails();
    
  3. Service operation will accept and return only message contract type. Other data types are not allowed.
    [OperationContract]
    EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp);
     
Note: If a type has both Message and Data contract, service operation will accept only message contract.