WCF: Step-by-Step Tutorial

This is a getting started tutorial to Windows Communication Foundation (WCF) Services. I have discussed a simple service to calculate the area of a rectangle; yup, very simple ;)

1. First you need to download and install Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation).

Oops, looks like it needs a windows validation (bit of a problem if you have a pirate copy :P )

2. Once the installation is complete, start Visual Studio to create the project.

Goto File->New->Web Site, and you’ll see a new template called WFC Service.

Click OK to create an empty WCF Service.

3. Time to get started with the coding

Service.svc

<% @ServiceHost Language=C# Debug="true" Service="GeometryService" CodeBehind="~/App_Code/Service.cs" %>

Only a small change here – the name of the service

Web.config

<?xml version="1.0"?>
 
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <system.serviceModel>
    <services>
      <!-- Before deployment, you should remove the returnFaults behavior configuration to avoid disclosing information in exception messages -->
      <service name="GeometryService" behaviorConfiguration="GeometryServiceBehavior">
        <endpoint contract="IGeometryService" binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="GeometryServiceBehavior" >
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 
  <system.web>
    <compilation debug="true"/>
  </system.web>
 
 </configuration>

Enable metadata publishing and change the name of the service.

Service.cs

using System;
using System.ServiceModel;
using System.Runtime.Serialization;
 
// A WCF service consists of a contract (defined below as IMyService, DataContract1), 
// a class which implements that interface (see MyService), 
// and configuration entries that specify behaviors associated with 
// that implementation (see <system.serviceModel> in web.config)
 
[ServiceContract()]
public interface IGeometryService
{
 [OperationContract]
 int GetArea(Rectangle rect);
 [OperationContract]
 int GetPerimeter(int width, int height);
}
 
public class GeometryService : IGeometryService
{
 public int GetArea(Rectangle rect)
 {
  return rect.Area();
 }
 
 public int GetPerimeter(int width, int height)
 {
  Rectangle rect = new Rectangle(width, height);
  return rect.Perimeter();
 }
}
 
[DataContract]
public class Rectangle
{
 int width;
 int height;
 
 public Rectangle(int width, int height)
 {
  Width = width;
  Height = height;
 }
 
 [DataMember]
 public int Width
 {
  get { return width; }
  set { width = value < 0 ? 0 : value; }
 }
 
 [DataMember]
 public int Height
 {
  get { return height; }
  set { height = value < 0 ? 0 : value; }
 }
 
 public int Area()
 {
  return Height * Width;
 }
 
 public int Perimeter()
 {
  return 2 * (Height + Width);
 }
}

This is the code for the service.

4. Run the service – click F5 :)

This is what you get on the browser. So, lets do what they want.

5. Run the following on you command on Visual Studio Command Prompt

svcutil.exe http://localhost:1479/GeoWFCService/Service.svc?wsdl

Watch out, the path might be different ;) . And if you don’t know what Visual Studio command prompt is

6. Let’s create the client

Create (or rather add) a new project; this could even be a website

7. Then run the service – Ctrl + F5

8. Add a web reference to the service

8. Copy the GeometryService.cs created by svcutil in step 5 to the clients working (main) folder and add them to the project

You should also copy the configurations of output.config created by svcutil to app.config

9. Again time for coding

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace GeoWFCClient
{
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
  }
 
  private void calculateButton_Click(object sender, EventArgs e)
  {
   GeometryServiceClient gsclient = new GeometryServiceClient();
 
   /* The overloaded constructor of Rectangle is not present here */
   Rectangle rect = new Rectangle();
 
   rect.Width = Int32.Parse(widthTextBox.Text);
   rect.Height = Int32.Parse(heightTextBox.Text);
 
   areaTextBox.Text = gsclient.GetArea(rect).ToString();
   perimeterTextBox.Text = gsclient.GetPerimeter(rect.Width, rect.Height).ToString();
  }
 }
}

Set the textboxes and labels with appropriate names.

10. When you compile you’ll get a set of error because some assemblies are not referenced. Add references to them

11. Now see how it works

Start the service if haven’t done so already, and run the client

Wow! It works :D

Ok, hope you learned something with this and I got to go study for exam :P

Tags: , , , , ,

  1. Shen’s avatar

    This really helped me in getting started with WCF. Thanks for the simple and excellent article.

  2. gsp’s avatar

    i am getting beloww error continuously:

    Could not find default endpoint element that references contract ‘IGeometryService’ in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element

    Please help who already soved this problem..

  3. Mekonnen’s avatar

    it is a nice tutorial to get started with WCF

  4. sushil’s avatar

    Thks man it’s working nicely for me n finally i have start worked on wcf… :)

  5. Vishwajit’s avatar

    Wow !! it worked … Thanks for sharing this simpler example to get start with WCF Services

  6. Naresh’s avatar

    thanx man……….great way to start WCF………..

  7. Rajesh’s avatar

    Nice Article….

  8. Amit’s avatar

    Seems to different

  9. Krishan’s avatar

    Thats good as for a short detail of WCF.But there should be some description o the terms used in WCF like ABCs etc.

  10. Santhosh’s avatar

    That was really helpful. Simple and to the point.
    Good Work, Thank you….

  11. Rahul’s avatar

    very good for bigners

  12. Srinath’s avatar

    Really It is a very good article…. Thank you….

  13. Rahul Trivedi’s avatar

    That was really good one…
    It will help me to get service working

    Thanks

  14. Syed Basheeruddin’s avatar

    Thanks….for the nice article…..i’m able to get start with WCF

  15. t’s avatar

    Thanks! very good tutorial!

    @gsp, the error you are getting is maybe because you haven’t published the main poject(the one not “client”), make sure to publish it and update the “ServiceReference” in Client project. Try building it again & it should work.

  16. Vijay Kolekar’s avatar

    Hi Friend,

    thank you very much,these are very easy steps and i learnt in a hour.
    :)

  17. Phil’s avatar

    Has anyone tried to create this example in VisualStudio 2008 using .Net 3.5? I can’t get past step 4. I get “System.InvalidOperationException: The type ‘GeometryService’, provided as the Service attribute value in the ServiceHost directive could not be found.”

    ServiceHost

    Web.config

    namespace
    namespace GeometryService

  18. Phil’s avatar

    These got lost in my original post.

    ServiceHost
    <>

    Web.config
    <>

  19. Phil’s avatar

    One more try without the

    ServiceHost
    ServiceHost Language=”C#” Debug=”true” Service=”GeometryService” CodeBehind=”Service.svc.cs”

    Web.config
    service name=”GeometryService” behaviorConfiguration=”GeometryServiceBehavior”

  20. Sumant Vakala’s avatar

    Nice article. Its really helpful.

  21. pavani’s avatar

    How to host WCFservice as windows service? can anyone help me out?

  22. Cezar’s avatar

    I would add
    gsClient.Close();
    at the end of the calculateButton_Click event

  23. ssmani’s avatar

    i got this error from commandprompt

    svcutil.exe is not recogonized as an internal or external command

  24. Jitendra’s avatar

    Thanks ,It’s very good article…..

  25. Foon’s avatar

    I’ve tried this example on VS2008 and like Phil says, I can’t get past Step 4

  26. vishy’s avatar

    Excellant article for begginer to understand ..

  27. srinu’s avatar

    its very nice..

  28. vidhyashok’s avatar

    Very good article to start WCF
    Thank you

  29. Ponkarthik’s avatar

    Hi it’s very nice article it’s working nicely in Localhost but if i published in Some sever with static IP It’s showing error That Meta data can not downloaded

    can u help me???

  30. Brijesh’s avatar

    wow!!!,,this is really superb!! article i have read….

    Thanx A Ton……………:)

  31. Alagar’s avatar

    It is Simply the best…

  32. Sunny’s avatar

    Excellent Article. Short and Sweet :)

  33. Rizwan’s avatar

    string myXMLfile = Server.MapPath(@”/CoffeProductList.xml”);
    List Prod = new List();
    ServiceClient ser = new ServiceClient();
    Prod = ser.ProductList(myXMLfile).ToList();
    foreach (Product p in Prod)
    {
    test productUserControl = (test)LoadControl(”Web.ascx”);
    productUserControl .ProdName = p.ProdName;
    productUserControl .Prodvalue = p.Prodvalue;
    productUserControl .ProdType = p.ProdType;
    tUserControl.ClickAddtoCart += new Shop.onClick(roductUserControl_ClickAddtoCart);
    Panel.Controls.Add(productUserControl );

    string myXMLfile = Server.MapPath(@”/ProductList.xml”);
    DataSet MyProducts = new DataSet();
    MyProducts.ReadXml(myXMLfile);
    DataTable MyTable = MyProducts.Tables[0];
    int intRC;
    intRC = MyProducts.Tables[0].Rows.Count;
    //LblProdCost.Text = Convert.ToString(MyTable.Rows.Count);
    foreach (DataRow dr in MyTable.Rows)
    {

    Web ProductUserControl = (Web)LoadControl(”Web.ascx”);
    ProductUserControl .ProdName=dr["Name"].ToString();
    ProductUserControl .Prodvalue = dr["Type"].ToString();
    ProductUserControl .ProdType = dr["value"].ToString();
    Panel.Controls.Add(ProductUserControl );

  34. nasri’s avatar

    :) , very nice, this was my first WCF service .
    thank you very much

· 1 · 2