Monday, June 18, 2012

First WCF Program for First Time WCF Programmers

Part 1
Every first time program starts with “HelloWorld” and so as here J

Create a new blank solution for adding the client, host and service projects for testing the WCF application.


Now add a project to the solution. The project type should be WCF Service Library. This project by default adds references to System.ServiceModel and an interface and a class required for creating a WCF service. System.ServiceModel namespace contains classes, enumerations, and interfaces necessary to build service and client applications. To make the service look simple, remove all the code and add the code mentioned in the below screenshots by changing the file names of the interface and the service classes.








Your service should look as below. [ServiceContract] decorates an interface that tells to the clients what is the service name that they should be contracting with. [OperationContract] tells the clients what are the operations the service is going to support. If you do not want any of the operations to be exposed to the clients, you need not decorate them with the [OperationContract]. But, there should be at least one operation that should be supported by the service otherwise, exposing the service has no purpose.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;



namespace HelloWorldService

{

    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.

    [ServiceContract]

    public interface IHelloWorld

    {

        [OperationContract]

        string ShowData(string message);



    }

  

}

Now implement the changed interface in the class. Here we are trying to print a message and timestamp of when the request from the client has been received.












using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;



namespace HelloWorldService

{

    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.

    public class HelloWorld : IHelloWorld

    {



        #region IHelloWorld Members



        public string ShowData(string message)

        {

            return string.Format("Message {0} received at {1}", message, DateTime.Now);

        }



        #endregion

    }

}

Now we need to host the service. There are many ways a WCF service can be hosted. You can host a service in a console application, IIS, windows services and windows forms. You can refer for basic understanding of WCF services from Microsoft site http://msdn.microsoft.com/en-us/library/ms731082(v=vs.90).aspx



In our example we are going to host the service in a console application. So, create a project of type WindowsàConsole Application. Add references to the project “HelloWorld” and “System.ServiceModel”. These references are needed in order to host the service by knowing the type of the service and the related classes needed for hosting the service.









using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using HelloWorldService;



namespace Host

{

    class Program

    {

        static void Main(string[] args)

        {

            using (ServiceHost host = new ServiceHost(typeof(HelloWorld)))

            {



                host.AddServiceEndpoint(typeof(IHelloWorld), new NetTcpBinding(), "net.tcp://localhost:9000/HelloWorld");

                host.Open();

                Console.ReadLine();

            }

        }

    }

}




Now create a host by instantiating the ServiceHost class.” typeOf(HelloWorld)” tells what is the type of the service that the host application is going to support.

Now we need to add a service endpoint. In a simple terms, End Point specifies what is the service name, where it is located and what is the binding it is supporting. 

End Point = A + B + C; A à Address of the service BàBinding CàContract.

In our example, the contract name is typeOf(IHelloWorld) and the binding is NetTcpBinding and the address is “net.tcp://localhost:9000/HelloWorld”.

Now we need to open the host in order to serve the requests from the clients. Console.ReadLine() was added just to keep on waiting till you close the console application.

Now build and run the host application. If everything goes fine with no errors then the host application is good.


Now we need to create a client application to test the service. The client application basically should know what is the service contract type and the operations it is going to support, address of the location where the service is available and the binding that the service supports or uses for communication. If we control both the clients and service, then we can directly put the code for the service interface in the client application (Program class) in order to let the client know the service and operation types.



In real world scenarios, we would be generating WSDL files and would be sharing with the clients. But for simplicity, let us copy the interface code in the client program class.


Now we need to create a proxy of the service. ChannelFactory class is a generic class that can be used to create more than one type of channel. CreateChannel method takes the parameters as the binding type and address of the endpoint.

After creating the instance of the service, now call the service method.












using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;



namespace Client

{

    [ServiceContract]

    public interface IHelloWorld

    {

        [OperationContract]

        string ShowData(string message);



    }

    class Program

    {

        static void Main(string[] args)

        {

            IHelloWorld proxy = ChannelFactory<IHelloWorld>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/HelloWorld"));

            Console.WriteLine(proxy.ShowData("Hello World From Client"));

            Console.ReadLine();



        }

    }

}





Now run both the host first and then client. You should see the message in the client application as in the below screenshot:


We will see how to create a WSDL file and do the configurations for the service host and the clients declaratively unlike as in the above example. Declarative way of programming and communicating makes the WCF services easier to learn and program. Developers can concentrate more on the actual code rather than configuration stuff.

If you find any difficulty in following this code, please feel free to ask. I would love to help you in resolving the problems.

Happy coding!!!

Part 2

3 comments:

Anonymous said...

Nice article for starters...

LeatherBiker040 said...

Helped me to start, even though visual studio 2015 has a slightly difference interface. Advice: make your pictures bigger, they are a bit too small to read. Will there be an article about the magic in the address of the service?

Akki said...

Hey Harald, First of all sorry I did not go through your comment. Thanks for the suggestion and I would definitely make a note of it about the pictures being smaller. I did plan yet about writing the article yet. I will definitely will let you know once I do it.

Post a Comment