pavanarya

Let us share the knowledge

Getting Started With WCF(Windows Communication Foundation) and creating our first service —Part 1

with 3 comments

Hi,
I am planning to write a series of articles on WCF(windows communication foundation). This is my first one in the series.

History Of WCF
WCF was first introduced in framework 3.0.
WCF was used for developing distributed application.

WCF includes all the features that were present in various technologies like Remoting,MSMQ,COM+,web services.

Advantages of WCF services

1.Remoting cannot be used for communicating with other platforms like Java but with WCF we can communicate with .Net components or any other language.

2.WCF provides more security and reliability that asmx web services.

3. Web service supports http,tcp and custom protocols where as WCF can be used with many protocols like TCP,Named pipes,MSMQ and custom protocols.

4.Web services can be hosted only on IIS where as WCF services can be hosted on IIS,Windows services,self hosting(console application)

Creating our first WCF services

1. Create an empty web application and name it as WCFTest1

2. Now right click on WCFTest1 project and click on add new item.

3. Now select WCF Service from the list and name it as MyService.svc

4. Now it will add following items to our project

i.IMyService.cs
ii.MYService.svc

5.It makes few changes to our pre existing web.config file.

So what is this IMyService.cs

So whenever we create a wcf service it contains two parts.

i. An interface that contains methods and variables that wcf service exposes.

ii. Now a class file should implement this interface in order to expose these methods and variables to external world.
(MyService.svc.cs) implements our interface(IMyService.cs)
This is how our project looks like

IMyService.cs

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

namespace WCFTest1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMyService" in both code and config file together.
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        string  DoWork();

        [OperationContract]
        UserDetails getUserDetails();
    }

   [DataContract]
    public class UserDetails
    {
        [DataMember]
       public string firstname;

        [DataMember]
        public string lastname;

        [DataMember]
        public int age;
    }
}

Here our wcf service exposes only 2 methods to external world.
1.DoWork()
2.getUserDetails()

DoWork() returns a string , getUserDetails() return Employee class.

Employee class contains various attributes like firstname,lastname and age

MyService.svc.cs

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

namespace WCFTest1
{
    public class MyService : IMyService
    {
        public string DoWork()
        {
            return "Testing service";
        }

        public UserDetails getUserDetails()
        {
            UserDetails details = new UserDetails();
            details.age = 23;
            details.firstname = "Pavan Kumar";
            details.lastname = "Aryasomayajulu";
            return details;
        }
    }
}

web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WCFTest1.MyService" behaviorConfiguration="WCFTest1.MyServiceBehaviors">
        <endpoint name="Test" address="http://localhost:1709/MyService.svc"  binding="basicHttpBinding" listenUri="http://localhost:1709/MyService.svc" contract="WCFTest1.IMyService"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WCFTest1.MyServiceBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Making use of the service at client side

1. Right click on MyService.svc and click on browse

2.Now it opens in the browser and copy the wcf url.

3. Now create a console application and click on add service reference.

4. paste the url (http://localhost:1709/MyService.svc) there.

5. Now this will create an app.config file and a client proxy.

6. App.config file contains all the data required for communicating with the service.

7. Now we can call our methods inside the wcf service from our main() inside Program.cs

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

namespace WFCTestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            WCF.MyServiceClient c = new WCF.MyServiceClient();
            
            string a=c.DoWork();
        }
    }
}

WCF Service without interface

So whenever we create a wcf service it creates an interface and a class that implements the interface.
So it comes into our mind that IS IT NECESSARY TO HAVE AN INTERFACE??

The answer to this question is it is not mandatory to have an interface. We can directly have a class.

So i am removing my IMyService.cs and modifying MyService.cs

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

namespace WCFTest1
{
    [ServiceContract]
    public class MyService
    {
        [OperationContract]
        public string DoWork()
        {
            return "Testing service";
        }

        [OperationContract]
        public UserDetails getUserDetails()
        {
            UserDetails details = new UserDetails();
            details.age = 23;
            details.firstname = "Pavan Kumar";
            details.lastname = "Aryasomayajulu";
            return details;
        }
    }

    [DataContract]
    public class UserDetails
    {
        [DataMember]
        public string firstname;

        [DataMember]
        public string lastname;

        [DataMember]
        public int age;
    }
}

So if we compare my previous MyService.cs file and this there are few changes.

I am decoration each method with [OperationContract] attribute and decorating the class MyService with [ServiceContract].

I am also having a class called Employee decorated with [DataContract].

Also a small change is needed in the web.config file

Please change this line 

<endpoint name="Test" address="http://localhost:1709/MyService.svc"  binding="basicHttpBinding" listenUri="http://localhost:1709/MyService.svc" contract="WCFTest1.IMyService"></endpoint>

to

<endpoint name="Test" address="http://localhost:1709/MyService.svc"  binding="basicHttpBinding" listenUri="http://localhost:1709/MyService.svc" contract="WCFTest1.MyService"></endpoint>

I am going to end this post at this point.

Till now we saw how to create a wcf service and how to use that at client side.


We might have number of questions like what is the content inside the web.config file.??

what are these operationcontract,servicecontract,datacontract??


I am going to write another post on these things.

Thank you so much for going through this post and please let me know if you have and queries or suggestion.

thanks,
pavan

About these ads

Written by pavanarya

August 20, 2012 at 6:36 pm

Posted in WCF

3 Responses

Subscribe to comments with RSS.

  1. very nice article :)

    Suvendu

    August 20, 2012 at 10:11 pm

  2. [...] my previous post Getting started with WCF, we saw how to create a wcf service in visual studio and the history of wcf services. Now in this [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: