Step Towards Windows Communication Foundation: Part 3


Basic program to develop WCF enable service with hosting as well as client to consume it:

In this article we will see how to develop our first WCF service without using a Visual Studio template. Follow the steps given. For some basics of WCF please see my previous articles:

Part 1
Part 2

Step 1:

Start a new console application and provide the name STEPONESERVICE.

Step 2:

Before proceeding, add a reference to the two namespaces for getting WCF functionality to our console application; they are System.ServiceModel and System.ServiceModel.dll.

Step 3:

As recommended by WCF, define an interface with rules inside it. To this interface add "ServiceContract" attribute. So that we can use this as a contract in WCF Endpoint & expose it to multiple clients.

[ServiceContract]
    interface IAuthor
    {
        [OperationContract]
        string GetAuthorName(int _authid);
        [OperationContract]
        void AddAuthor();
    }

Step 4:

Implementing the interface i.e. created. This task is nothing to do with WCF endpoint & other processing but for better support with respect to performance as well as other features, WCF recommends some of the .Net object to use & also to avoid. Eg. It prefer to use Generic Classes instead of normal classes. Some features of WCF will not be compatible with not preferred objects. In our example we will create a class & implement the interface for functionality.

class Author:IAuthor
    {
        public string GetAuthorName(int _authid)
        {
            string _connection = "Data Source=server2;User Id=sa;Password=123;DataBase=CSAUTHOR";
            Console.WriteLine("Request Made :" + DateTime.Now.ToString());
            SqlConnection _conn = new SqlConnection(_connection);
            _conn.Open();
            string _sql = "Select Author_Name From Author Where Author_Id=" + _authid;
            SqlCommand _cmd = new SqlCommand(_sql, _conn);
            SqlDataReader _rdr = _cmd.ExecuteReader();
            if (_rdr.Read())

                return _rdr[0].ToString();
           
else

                return "-1";           

        }

        public void AddAuthor()
        {
           //Implement
        }
    }


Step 5:

Once the component is prepared then we have to define an Endpoint and Host it in a WCF supported environment. One of the options to host a WCF created service is to use a program written with "ServiceHost" class of WCF. In the main part of our program create an Endpoint and use a "ServiceHost" class to start the service.

static void Main(string[] args)
        {
//Creating instance of ServiceHost class for hosting our service
            ServiceHost obj = new ServiceHost(typeof(Author));
            //Add endpoint
            obj.AddServiceEndpoint(typeof(IAuthor), new BasicHttpBinding(), "Http://localhost:8001/Author");
            obj.AddServiceEndpoint(typeof(IAuthor), new NetTcpBinding(), "net.tcp://localhost:8002/Author1");
            obj.Open();
            Console.WriteLine("Service Started. Press Any Key To Exit");
            Console.ReadKey();
            obj.Close();
        }

Consuming WCF Service:

WCF supports many different ways of consuming a service. The basic distributed programming principle of creating proxy and communication with service is the most preferred way to access the service.

Proxy is also a class built in client language which acts as a service to client. It has all methods that a service provides inside it and code to convert this call to a remote call.

In WCF we have classes that create proxies programmatically, which means at runtime. This is very good for some logics but very complex to handle. In the program "ChannelFactory" is a class that creates a proxy based on an URL provided and contract info channel is a term which we use to refer a socket that we build with server. ChannelFactory is a class that can process all WCF channels.

ChannelFactory creates a class at runtime not at designtime. It requires endpoint info(A,B,C). In our example we will take ServiceContract in client program which is actually built using endpoint. For starting our client program take a look step-by-step.

Step 1:

Start the console application; make the name STEPONECLIENT.

Step 2:

Add a ServiceContract which we have built in service i.e. interface.

 
[ServiceContract]
    interface IAuthor
    {
        [OperationContract]
        string GetAuthorName(int _authid);
        [OperationContract]
        void AddAuthor();
    }


Step 3:

In Main write the program to create an instance of channelfactory by passing endpoint information.

//Create Instance of ChannelFactory Class
            ChannelFactory<IAuthor> obj = new ChannelFactory<IAuthor>(new BasicHttpBinding(), new EndpointAddre("Http://localhost:8001/Author"));

Step 4:

Once ChannelFactory is configured with required information then establish the socket with the server using the CreateChannel method of it.

IAuthor reg = obj.CreateChannel();

Step 5:

Once the socket is built, then start invoking methods and display results.

int _authid = int.Parse(Console.ReadLine());
           Console.WriteLine(reg.GetAuthorName(_authid));


Conclusion:

In this article we have seen the basic program to create WCF service with self hosting using ChannelFactory class.

Up Next
    Ebook Download
    View all
    Learn
    View all