C#

Simple Self Hosted WCF Service in C#

Self Hosting : 

In this post we will explain about self host service using console application in windows application. This referred as self hosting WCF service, the exact meaning of Self Hosted is provides the user to host the service in any application that could be Console Application or Windows forms etc. Earlier we saw about What is WCF service on dot net platform. We can host WCF service in IIS and windows service also.
Service can also be in-pro i.e. client and service in the same process. Now let's us create the WCF service which is hosted in Console application. We will also look in to creating proxy using 'Client Base' class.

Step 1 :  First let's start create the Service contract and it implementation. Create a console application and name it as WCF_NewsService. This is simple service which return News.
Step 2 : Add the System.ServiceModel and System.runtime.serialization reference to the project.
Step 3 : Now right click the project name  in solution explorer and got to the add new item and select WCF Service option in window  and give name News_Service and click  Add
Once you add this WCF Service some function and class files added into the solution explorer
Step 4 : an INews_Service interface, Add ServiceContract and OperationContract attribute to the class and function as shown below. You will know more information about these contracts in later session. These contracts will expose method to outside world for using this service.

INews_Service.cs
using System;


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

namespace WCF_NewsService
{
    
    [ServiceContract]
    public interface INews_Service
    {
        [OperationContract]
        TOInews Getnews(int a);

    }

    [DataContract]
    public class TOInews
    {
        private int _id;
        private string _header;
        private string _body;

        [DataMember]
        public int ID
        {
            get { return _id; }
            set { _id = value; }
        }

        [DataMember]
        public string Header
        {
            get { return _header; }
            set { _header = value; }
        }

        [DataMember]
        public string Body
        {
            get { return _body; }
            set { _body = value; }
        }
    }
}
Step 5 :  Open New_Service file and right click on INews_Service go to the implement Interface and delete the DoWork() method which unused for us. And write code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCF_NewsService
{
   
    public class News_Service : INews_Service
    {


        #region INews_Service Members

        public TOInews Getnews(int a)
        {
            TOInews objtoinews = new TOInews();

            switch (a)
            {
                case 1:
                    {
                        objtoinews.ID = 1;
                        objtoinews.Header = "Mumbai News";
                        objtoinews.Body = "2013 Code contest quiz orgnize by TOI";
                        break;
                    }
                case 2:
                    {
                        objtoinews.ID = 2;
                        objtoinews.Header = "Pune News";
                        objtoinews.Body = "commonwealth fraud in pune ";
                        break;
                    }
                case 3:
                    {
                        objtoinews.ID = 3;
                        objtoinews.Header = "Solapur News";
                        objtoinews.Body = "New IT hub in Solapur";
                        break;
                    }
           
                default:
                    {
                        break;
                    }
            }

            return objtoinews;
           
        }

        #endregion
    }
}
Step 6 :  Now after completing write code in service we have to Start our service using console application  Below code show the implementation of the host process.

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

namespace WCF_NewsService
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(News_Service));
            host.Open();
            Console.WriteLine("Host Open Sucessfully ...");
            Console.ReadLine();
        }
    }
}
 Step 7 : 
now open app.config file and change some setting
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
     
     
     
      <bindings>
        <basicHttpBinding>
          <binding name="Pramod"></binding>
        </basicHttpBinding>
      </bindings>
     
     
       
     
      <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
     
     
     
        <services>
            <service name="WCF_NewsService.News_Service">
                <endpoint address="News_Service"
                          binding="basicHttpBinding"
                          contract="WCF_NewsService.INews_Service"
                          bindingConfiguration="Pramod">
                    <identity>
                        <dns value="localhost" />
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8732/Design_Time_Addresses/WCF_NewsService/News_Service/" />
                    </baseAddresses>
                </host>
            </service>
        </services>
     
     
     
     
    </system.serviceModel>
</configuration>
Step 8 : Run your application and see message in console screen.


Now create consumer for consume the service. Again you have to create new application and write code in Program.cs file, 
Before writing code these file we need add service reference of NewsService Project
For adding the service reference right click to WCF_NewsConsumer in solution explorer and go to the Add Service reference.. copy the URL from Service project and paste it in Address location and give appropriate name to the Service.
Here I am giving name as Proxy_TOInews for namespace pupose and click OK
After adding the reference add namespace 
using WCF_NewsConsumer.Proxy_TOInews;



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCF_NewsConsumer.Proxy_TOInews;

namespace WCF_NewsConsumer
{
    class Program
    {
        static void Main(string[] args)
        {
            Proxy_TOInews.News_ServiceClient proxy = new News_ServiceClient("BasicHttpBinding_INews_Service");
            TOInews Tnews = new TOInews();

            Console.WriteLine("Enetr News Id :");
            string newsid = Console.ReadLine();

            Tnews = proxy.Getnews(Convert.ToInt32(newsid));

            News nws = new News();
           
            nws.cID = Tnews.ID;
            nws.cHeader = Tnews.Header;
            nws.cBody = Tnews.Body;

            Console.WriteLine(" News from:" + nws.cID + "\r\r \n " + nws.cHeader + "\r\r \n " + nws.cBody + "");
            Console.ReadLine();

        }

        public class News
        {
            private int _id;
            private string _header;
            private string _body;

            public int cID
            {
                get { return _id; }
                set { _id = value; }
            }

            public string cHeader
            {
                get { return _header; }
                set { _header = value; }
            }

            public string cBody
            {
                get { return _body; }
                set { _body = value; }
            }
           
        }
    }
}

Now run the Both application and enter new id and hit enter key .


No comments:

Post a Comment