Search
Sponsor
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Tue, 21-Oct-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
38050
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

Understanding the basics of WCF Service

Dhiraj5079
Posted by under WCF category on for Intermediate level | Views : 186949 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 4.88 out of 5
16 vote(s)
The aim of this article is to explain the basics of WCF in a manner as simple as possible.
It is assumed that the reader doesn’t know anything about WCF or .NET 3.0, however he/she is expected to know .NET 2.0 and/or simple facts like what is a web service.
While writing this article (or any other) I always try to avoid difficult technical words, which may confuse the reader. I have tried to put it in as simple words as possible.
At the end of this article, I would hope you understand at least some of the key WCF areas and possibly be inspired enough to try out a project on your own.

1.Introduction


The aim of this article is to explain the basics of WCF in a manner as simple as possible.It is assumed that the reader doesn’t know anything about WCF or .NET 3.0, however he/she is expected to know .NET 2.0 and/or simple facts like what is a web service.While writing this article (or for any other) I always try to avoid difficult technical words, which may confuse the reader. I have tried to put it in as simple words as possible.At the end of this article, I would hope you understand at least some of the key WCF areas and possibly be inspired enough to try out a project on your own.

2.Contents

1. Introduction

2. The most suitable reader for this article.

3. Prerequisites

4. A brief overview of demo service

5. Explanations of fundamentals involved

6. The demo Service with code

7. Conclusion



The Most suitable reader for this article

Any .NET Developer who wants to start with WCF can be most benefitted from  this article.

3. Prerequisites

 To run the code supplied with this article you need to install .NET 3.0 API   available with Visual Studio 2008.

 

4. A brief overview of demo service


In this demo WCF service we are trying to carry out the following functionality:

a)     Create a service
b)    Host the service
c)     Create a client for the service
d)    Let the client interact with the service.

To achieve the above functionality we will create three inter related assemblies as mentioned below:

     a)   SampleService.dll – this is the actual WCF service that allows clients to connect
b)   SampleHost.dll – this is the dll that hosts WCF service, SampleService.dll
c)   SampleClient.dll – this is the client assembly which communicates with SampleService.dll.

 

          Note that the programming language used here is C#.

 

5. Explanations of fundamentals involved

 

Assuming that the reader has no Background in WCF, there are a number of key concepts that needs to be explained in order for the full application to be understood.

So I will just explain each of these a little bit at a time, so that the final application will be a little easier to understand.

 

Key Concepts:

a) What is WCF?

WCF stands for Windows Communication Foundation.

WCF is advanced API (Application Programming Interface) for creating distributed applications using .NET framework.

It is introduced in .NET 3.0.

Distributed system in its simplest form is two executable running and exchanging data.

WCF API is found in System.ServiceModel namespace.

WCF is based on basic concepts of Service oriented architecture (SOA)

 

b) What is a WCF Service?

         A WCF service is a program that exposes a collection of Endpoints (connections) for communicating with either client applications or other service applications.
       

c) What are the components of WCF application?

                          There are three main components of a WCF application

i)      a WCF service
ii)     a WCF service host
iii)     a WCF service client

         d) What is the “ABC” of a WCF Service?

“ABC” of WCF stands for addresses Bindings and contracts respectively.

                i) Addresses:   This is location of the service in the form of an

                URI (Uniform resource Identifier) generally mentioned

                In the config file.

 

                ii) Bindings: This includes the type of network protocol  used by the

                Service. For Example HTTP, TCP/IP or others.

               

                iii) Contracts:  This is in fact the methods exposed by the WCF service.

 

e) What is a Service Contract in WCF application?

Service contract is the name of the attribute which is applied to an interface in   a WCF service.

 

 

f) What is an Operation Contract in WCF application?

Operation contract is the name of the attribute which is applied to a   method inside the interface of a WCF service

 

 

6. 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.

You can contact me by clicking my blog link below. 

 

Page copy protected against web site content infringement by Copyscape
About the Author

Dhiraj5079

Full Name: Dhiraj Kumar
Member Level: Starter
Member Status: Member
Member Since: 3/10/2010 7:33:08 AM
Country: India

http://dhiraj5079.blogspot.com/

Dhiraj Kumar is a passionate .NET enthusiast and Microsoft Certified Technology Specialist. Currently working at What's on India,Mumbai , India.
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Posted by: Vuyiswamb on: 3/19/2010

Am impressed by you. Nice Article Keep it up. Soon we will add the voting System to keep the quality of Article better. Your Article is wonderful and you get to the point. Well done.



Posted by: Dhiraj5079 on: 3/19/2010

Thanks a lot! Vuyiswa

Posted by: Hamedzero on: 5/24/2010

Thank you,
It's a realy good and simple article about WCF

Posted by: Govindsharma53 on: 8/4/2010

great article for starters in WCF...

Posted by: Ganeshmandlik on: 9/20/2010 | Points: 10

Hi,

I really thankful to u!!!!!!!!!!!

Great Explanation!!!!!!!!!!!!!

Keep it up.

Thanks & Regards,
Ganesh Mandlik,


Posted by: Smack on: 10/20/2010 | Points: 10

Good artilcle .But am stuck with the command promt in creating a proxy client.

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.

The cmd promt code is not success in my machine.Any help in how to proceed is enough.

Posted by: AppiAppi on: 10/25/2010 | Points: 10

trying the same giving space before out

Posted by: Prakashgajera on: 1/15/2011 | Points: 25

Hi ,

This article is realyyy nice !!!!!

i have allowed the exact mentioned step to understand wcf service.but i m getting bellow error when i enter my question in my sample client and press enter

Could not connect to http://localhost:8080/SampleService. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8080.

can any one give me how to overcome this.

thanks - prakash

Posted by: Rmistry on: 1/17/2011 | Points: 25

Hi,
The article is too good for beggineers in WCF..
But even i am getting the same error of "Could not connect to http://localhost:8080/SampleService. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8080. "

Kindly help.

Regards,
Rupa Mistry.

Posted by: Klbaiju on: 2/3/2011 | Points: 25

svcutil.exe is not exists in my system . the what i have to do

Regards
K L BAIJU

Posted by: Manugupta on: 2/3/2011 | Points: 25

Please provide implementation of IAnswer interface, I implemented like that -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleServiceLib
{
public interface IAnswer
{
string ObtainAnswer(string Question);
}
}

If its correct then why its throwing error "The contract name 'SampleServiceLib.IAnswer' could not be found in the list of contracts implemented by the service 'SampleService'."

Please help.

Many thanks,

Posted by: Vijayiner on: 3/28/2011 | Points: 25

hi,
it's really great application...
i have learn the because knowledge of the WCF... Thanks you very much...
After following the step by step process, i am getting the below error,

"An error occurred while receiving the HTTP response to http://localhost:8080/SampleService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.:"
what i can do ...
please help me to see the output...

Thanks
Vijay r

Posted by: Laghaterohan on: 4/4/2011 | Points: 25

I am getting following error when i ask the question..

Could not connect to http://localhost:8080/SampleService. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8080.

Posted by: Murad.haider2003 on: 4/12/2011 | Points: 25

"The type or namespace name 'AnswerClient' could not be found (are you missing a using directive or an assembly reference?"
hi, i am experiencing the aforementioned problem... please tell me how to fix it??

Regards
Haider


Posted by: As12df on: 5/19/2011 | Points: 25

"An error occurred while receiving the HTTP response to http://localhost:8080/SampleService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.:"

fix it
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();
}

}


}

Posted by: Shoeb2222 on: 6/22/2011 | Points: 25

Great work, Keep it up.

Posted by: Harinath_abb on: 6/29/2011 | Points: 25

Very useful for beginners. Thanks for the article.
Note: Pls update the fix "Console.ReadLine()" to run the client properly.

Posted by: Pinky on: 7/10/2011 | Points: 25

hi
good code but 1 error occur.
i have add sampleservice.dll file in proxy folder . but when type in cmd svcutil.exe sampleservice.dll
one error occur .
error is cannot read sampleservice.dll
plz tell me any solution of this problem?

Posted by: Nageshc on: 12/7/2011 | Points: 25

Hi Smack
Answer For You Question !!!!

Step 1 : we have to Create one Folder in C:\ drive named as :Proxy
Step 2 :Go to Command Prompt Change the Directory to C :\ drive
In the Beginning we will see like this : C:\ Documents and Settings\ YourName>
So just do cd..
Then we wil see in Command Prompt like this: C:\ Documents and Settings> by doing the above command.
Step 3: Again do cd..
Then we wil see in Command Prompt like this: C:\ > OK.
So now we are in "C" Drive
Step 4: type cd Space folder name( cd Proxy) then click on Enter
Then we wil see in Command Prompt like this: C:\ Proxy>
It means your in Proxy Folder, Now you can access the Files inside the Proxy Folder(those are 1)SvcUtil.exe
and 2)SampleService.dll)
Note:Please make Sure that your DLL Name Should NOT WITH SPACE.(SampleService.dll)
Step 5: Now you drive be the C:\ Proxy>
after this type /Paste above Two Files
Then we wil see in Command Prompt like this: C:\ Proxy>SvcUtil.exe SampleService.dll Click on Enter.
Note: Plase Provide Gap Between those two file(Click one time on Space bar)

Then It This Command will Create to You Files in Your Proxy folder.


Regards
Nagesh








Posted by: Willie321 on: 5/25/2012 | Points: 25

Good day,

i need some help. I need Demo the WCF Service required to pull JSE Stock data in JSON format. can you please help me?

Login to post response

Comment using Facebook(Author doesn't get notification)