Tuesday 20 October 2015

How to work with WCF?


Windows Communication Foundation (WCF) is a framework for building service-oriented applications.
Let's see how to create a simple service in WCF.

Open Visual Studio. Go to File->New->Project->WCF Service Application

Give name to your application such as WcfService.
Now one service is created by default. Get rid of that because we want to implement our service.
So delete service1.svc and IService1.cs.

[Note: Services have .svc extension]

Now right click on the project name and Add New item(OR ctrl+shift+A ) --> WCF Service.

Give your service name as MyService and click add.
MyService.svc and IMyService.cs is added to your project.
MyService.svc is our Service and IMyService.cs is Interface.


In IMyService.cs we can declare our methods and since MyService.svc inherits from IMyService.cs so we have to implement all methods in our service that is defined in Interface.

By default we have void DoWork() declared in interface and implemented in our service.Delete

   [OperationContract]
   void DoWork();

from IMyService.cs and 

   public void DoWork()
   {
   }

from MyService.svc.cs.

Now add some Method to IMyService.cs as

   [OperationContract]
   string welcome(string name);
   [OperationContract]
   int Sum(int FN,int SN);

Now Go to MyService.svc.cs.

On public class MyService : IMyService line double click on IMyService and press ctrl+.(Dot)
You get 'Implement interface IMyService'. Click on that to generate function signature and change according to following
OR
just paste following in MyService.svc.cs.

        public string welcome(string name)
        {
            return "Hello "+name;
        }

        public int Sum(int FN, int SN)
        {
            return FN + SN;
        }

Now run your project. On left side you see the methods. Click on welcome().
In welcome window give the value of parameter name in Request and Click Invoke Button.

If Security warning appears click on OK and you see your output in Response beneath Request in
Welcome window.

Similarly Click on Sum() and pass value for parameter FN and SN and you get the result.

Now, Let me cover some theory part also.

Contracts: In WCF, All services exposes the contracts. The contract is a platform independent 
and standard way of descibing what the services does.

Service Contract: Describe what operation client can perform on the services.

Data Contract: Defines which data type are passed to and from the service.

Note: Without Service Contract attribute the contact is not visible to WCF clients.

No comments:

Post a Comment