Wednesday, 28 August 2013

Create & consume WCF Service using svcutil

First we will see how to create simple WCF service and then we will consume our service. Let’s create simple WCF service that greets on calling.
-          Go to File -> New ->Website->WCF service. Give SimpleWCFService as name to project.

-          Right click on the project -> Add New Item. Select WCF Service. Give name Service.svc.


-           It will add class Service.cs and interface IService.cs in the folder App_folder 

-          Open IService.cs and add method signature for Greet(). Remember to add [OperationContract] attribute at the top of the method signature otherwise it cannot be called by client application.


-          Open Service.cs and implement menthod Greet().

-          Now build website & run. You will see you have created service successfully.

Now it’s time to consume your web site. You can consume WCF service in the client application by adding reference of the service to the project or you can create proxy for WCF service using svcutil and then use proxy to consume the WCF service. We will use proxy created by svcutil.exe
Using proxy created by svcutil
We will create on simple web application and consume our SimpleWCFService.
First create web application (File-> New ->Project. Give name as SipmpleWebsite to project)


-          Now to consume WCF service we need to proxy. To create proxy we will use svcutil.
Open Visual Studio Command Prompt and enter below command

Svcutil “http://localhost/SimpleWCFService/Service.svc”  /out:C:\SimpleProxy.cs  /config:simple.config

The above command will create SimpleProxy .cs and Simple.config file.

 Now in the web application, right click on the project -> Add Existing Item-> browse for SimpleProxy .cs and Simple.config file and add them to the project

-          Copy contents of simple.config into web.config (Copy ServiceModel node from simple.config to web.config). Your web.config might look like this

-          Now add Web form to the application (right click on the project-> Add New Item -> Select Web Form

-          Now if you rebuild solution here, you may get errors – “The type or namespace name ‘ServiceModel’ does not exist….”. To resolve this add reference to System.ServiceModel & then rebuild solution.
-          Now everything is ready, just instantiate serviceclient and call method.
-          You have successfully consumed WCF service. You will get greeting on your client application web form.