Wednesday, 16 October 2013

Various ways to invoke a WCF Service from client



In this post we are going to see how to invoke a WCF service in client. For that now we are going to create a WCF service and host using windows service.

Step 1 . Open visual studio 2010
Step 2   Create a New Project by select WCF Service Library.


Service have created with default methods which is mention as follows.

public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }



Service Contract is :

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }


Step 3  Add new Project "Select Windows Service Template"

Step 4  Add Reference of IService Contract to the windows Service.
            public partial class Service1 : ServiceBase
    {
        ServiceHost host = new ServiceHost(typeof(WCF1.Service1));
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                System.Threading.Thread.Sleep(20000);
                host.Open();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        protected override void OnStop()
        {
            host.Close();
        }
    }

Add the above code to the program of windows service.

Step 5  Add a App.Config file.

Now add important thing in App.config file for  Host service in computer : ABC 
i.e is A - Address, B- Binding , C - Contract

<system.serviceModel>
    <services>
      <service name="WCF1.Service1">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8085/sam"/>
            <add baseAddress="net.tcp://localhost:9085/sam"/>
          </baseAddresses>
        </host>
        <endpoint address="testservice" binding="wsHttpBinding" contract="WCF1.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="testservice" binding="netTcpBinding" contract="WCF1.IService1"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information,
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes,
          set the value below to true.  Set to false before deployment
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>


Now Install the windows service in computer now WCF service is hosted in two bindings TcpBinding and WsHttpBinding. Tcp uses 9085 port and Http uses 8085 port for connecting to client.
Now Service is ready, Here we have two ways to connect a client to service

Two ways
1. Create a Proxy by add reference and call the object uses the client.
2. using ChannelFactory

Invoke WCF service using client. Create a Console application

Method 1:

Add a Service Reference using the address "http://localhost:8085/sam/testservice" for Http now proxy class is created automatically.

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();           
            Console.WriteLine(client.GetData(3););
            Console.Read();

Output : 

You Entered : 3


Method 2:

 In method 2 we are using Channel Factory to call the Service in this method , there is one advantage if the contract is changes with additional method. we don't need to worry about that because we are getting the instance from the create channel , to work just we need to add the service contract as reference.

we need binding , address and channellFactory object to create a instance of service.

            WSHttpBinding bind = new WSHttpBinding();
            NetTcpBinding tcpbind = new NetTcpBinding();
                
            EndpointAddress addr = new EndpointAddress(@"net.tcp://localhost:9085/sam/testservice");
            ChannelFactory<WCF1.IService1> serv = new ChannelFactory<WCF1.IService1>(tcpbind, addr);
            WCF1.IService1 servpro=    serv.CreateChannel();
            string f=servpro.GetData(3);
            Console.WriteLine(f);
            Console.Read();


Output : 

You Entered : 3



From  this post i hope that you are able to understand the various method of invoking a WCF service from client.

No comments:

Post a Comment