Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

The demo Service with code

Before I start, I would like to remind you again that this is the simplest of WCF service only for understanding purpose. In real world you might have to build/face much more complicated WCF service.

I have divided this part in five sub-parts as below.
a) Building the WCF service
b) Building the WCF host
c) Building the Proxy to be used by client
d) Building WCF client
e) Testing the working of the whole application. 


a) Building the WCF service 

To understand the service better we will build the service as a c# class library project. Follow the following steps:

In my case it created the class1.cs with content as below.
         i)   Open Visual Studio 2008
ii)  Select Create ProjectàC# class library name it “Sample Service”
iii)  It will crate a .cs file in the project. Open that file.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace SampleService

{

    public class Class1

    {



    }



}

Change the namespace SampleService to SampleServiceLib,
Rename the Class1 to SampleService.
Rename the Class1.cs file in the solutionExplorer to SampleService.cs
Add the namesapce using System.ServiceModel at the top.

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;





namespace SampleServiceLib

{

    public class SampleService

    {

    }

}
The SampleService.cs file should now look like below.

iv) At this point the project will not build, so please add a reference to System.Service Model.
For this, Go to solution Explorer ,Right click on the reference Add Reference .NET Tab Select System.ServiceModel  OK.

  Now you can successfully build the Project.

v) Create an interface named IAnswer in this file inside  SampleServiceLib namespace.Create a method inside the interface IAnswer, named ObtainAnswer The attributes for the interface and the method should be ServiceContract and OperationContract respectively

         vi) Implement the IAnswer  interface in SampleService class as

Shown in the code sample below.
 namespace SampleServiceLib

{

    public class SampleService : IAnswer

    {

       public string ObtainAnswer(string Question)

        {

return "My Profession is Software Development";



        }

    }



    [ServiceContract]

    public interface IAnswer

    {



        [OperationContract]

        string ObtainAnswer(string Question);



    }



}

vii)   Now ad a constructor to the class SampleService and the final code should look like this.Build this project. 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;



 



namespace SampleServiceLib

{



    public class SampleService : IAnswer

    {



        public SampleService()

        {

Console.WriteLine("Ask question to SampleService....");



       }



        public string ObtainAnswer(string Question)

        {



            return "Your Profession is Software Developer";



        }



    }



 



    [ServiceContract]

    public interface IAnswer

    {



        [OperationContract]

        string ObtainAnswer(string Question);

    }



}


 viii) Save the sample service Project by File Save All. Then build it so that you will get a SampleSevice.dll in its bin\release directory.


 b) Building the WCF host

A WCF host may be IIS (Internet Information Server) , Windows Service, A console application etc.The simplest of them is a console application host. So we will demonstrate that here.
Follow the following steps: 
i) Open Visual Studio 2008
ii) Select Create ProjectàC#  Console Application name it “Sample Host”
iii) From Solution Explorer,Add the reference of System.ServiceModel to this project as before and
iv) also add the reference of SampleServiceLib.dll from SmpleService Class library project you created before by addreference Browse Tab Browse to the    SampleServiceLib.dll in the project SampleService’s Bin/release folder.
v) Open its Program.cs file and add the following two namespace to the

Using Section.
Using System.ServiceModel
Using SampleServiceLib

vi)               Build the project successfully.
vii)             Add the following console.Writeline codes to program.cs so that the final Program.cs Should look Like as below.

 
 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using SampleServiceLib;



namespace SampleHost

{

   class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Sample Host of Sample Service is running....");

            using (ServiceHost servicehost = new ServiceHost(typeof(SampleService)))

            {

                servicehost.Open();

                Console.WriteLine("The SampleService is ready now...");

                Console.WriteLine("Press enter to terminate the SampleService...");



            }

            Console.ReadLine();

        }

    }

}


viii) Adding the config File to the Host :
                Go to the Solution Explorer of the Sample Host
          Right Click Add New Item Application Configuration File
          A file named app.config will be added to the solution.
          Initial content of the file is given below


          <?xml version="1.0" encoding="utf-8" ?>



        <configuration>



     </configuration>

ix)               Add the code inside the configuration tag of app.cofig so that the final app.cofig should look like as below 

 <?xml version="1.0" encoding="utf-8" ?>



<configuration>



  <system.serviceModel>



 



 



    <services>



      <service name="SampleServiceLib.SampleService" behaviorConfiguration="SampleServiceMEXBehavior">



        <endpoint address="http://localhost:8080/SampleService"  binding="basicHttpBinding" contract="SampleServiceLib.IAnswer"></endpoint>



      



        <endpoint address="mex" binding="mexHttpBinding" contract="SampleServiceLib.IAnswer"></endpoint>



        <host>



          <baseAddresses>



            <add baseAddress="http://localhost:8080/SampleService"/>



 



          </baseAddresses>



 



 



        </host>



 



      </service>



 



    </services>



 



 



    <behaviors>



      <serviceBehaviors>



        <behavior name="SampleServiceMEXBehavior" >



         



          <serviceMetadata httpGetEnabled="true" />



        </behavior>



      </serviceBehaviors>



    </behaviors>



 



 



  </system.serviceModel>



</configuration>

x)                 Build the Service host application and run it. You should get a console Window while host is running.


c)     Building the Proxy to be used by client

Before building a client you need to build a proxy of the service which the client will use to interact with the service.
A proxy is nothing but a .cs file and a .config file generated by a tool called svcutil.exe using your service Sampleservice.dll
Steps to create the Proxy:
i) Create a Proxy folder in your c:\ drive.
ii) Search for the svcutil.exe file on your computer and copy it to the Proxy folder.
iii) Copy the dll of the service you created (sampleservice.dll) to this Proxy folder.
iv) Go to Start Run cmd
v)  On the command prompt change the directory to Proxy folder.
vi)  Run the following command
C:\ Proxy  svcutil.exe SampleService.dll
This will create a few files in the current directory like
.wsdl, .xsd etc
vii)  The run the following command
C:\ Proxy svcutil.exe *.wsdl *.xsd  /language:C# 
      /out:SampleProxy.cs /config:app.config
       It will create two files in the Proxy folder
SampleProxy.cs and app.config.
These are your proxy files to be used in the Client.
viii)  Open the SampleProxy.cs file, it has the AnswerClient class which has the ObtainAnswer Method from SampleService.
d)    Building WCF client

i)    Open Visual Studio 2008
ii)   Select Create ProjectàC# Console Application name it “SampleClient”
iii)  From Solution Explorer,Add the reference of System.ServiceModel to  the project as before. 
iv)  Add the two proxy file SampleProxy.cs and app.config to the solution.
v)   Open the app.config File .You will find that inside of client Tag,the endpoint tag does not have “address” attribute.
vi) add the attribute address="
http://localhost:8080/SampleService" to the endpoint tag of the app.config file.
vii) Now add code to Program.cs so that final Program.cs should look like as below
    

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;



 



namespace SampleClient

{

    class Program

    {



        static void Main(string[] args)

        {

            Console.WriteLine("Ask question");

            //the name AnswerClient is generated autometically by svcutil.exe tool which creates

           //chat proxy and app.cofig

            //by browsing the service url after reference.



            using (AnswerClient client = new AnswerClient())

            {

                Console.WriteLine("Your Question:  ");

                string question = Console.ReadLine();

                string answer = client.ObtainAnswer(question);

                Console.WriteLine(answer);

                Console.ReadLine();

            }



 



        }



    }



}

 viii) Build the application. Now the client is ready. 

e)     Testing the working of the whole application

To Test the service follow the steps below.
i)  Run the Sample Host  Application
ii)  Run the client application
iii)  Write the following question on client console “What is my Profession”
iv)  The reply fro service will come as “Your Profession is Software Developer.”
Conclusion

I have enjoyed writing this WCF Service article and I hope you will enjoy reading it. In real world you may have to face far more complicated WCF services than this sample.

No comments:

Post a Comment