Basic WCF Tutorial for Beginners


I will be explaining a simple WCF service execution, using a sample project (collated from the MSDN Documentation). Lets create a Visual Studio Solution with two console application projects.
They are:
1. Service Part – Console Application
2. Client Part – Console Application
Let me take you through the Service Part:
1. Create a sample console application & Import the System. ServiceModel; & System.ServiceModel.Description; references.
2. Create an Interface with interface attribute as ServiceContract with a sample namespace for the service. This will be the Contract between the client &
the WCF service. The interface methods will have function attributes as OperationContract
// Define a service contract.
[ServiceContract(Namespace = “http://Microsoft.ServiceModel.Samples”)] //Namespace of the cs file
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
3. Define the class Calculator inheriting the Interface & implementing the 4 functionalities.
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine(“Received Add({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 – n2;
Console.WriteLine(“Received Subtract({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine(“Received Multiply({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine(“Received Divide({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
}
4. In the main function of the Console Application, we implement the WCF service creation logic:
4.2  Create a service Host for the type as CalculatorService class & Uri as baseaddress
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
4.3  Enable metadata exchanges, using ServiceMetadataBehavior from the System.ServiceModel.Description
ServiceMetadataBehavior smdb = new ServiceMetadataBehavior();
smdb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smdb); //Add the behavior to the servicehost
4.4  Start (and then stop) the service
selfHost.Open();
4.5 Close the service once done
Console.WriteLine(“The service is ready.”);
Console.WriteLine(“Press <ENTER> to terminate service.”);
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
Full Code (Program.cs):
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract(Namespace = “http://Microsoft.ServiceModel.Samples&#8221;)]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine(“Received Add({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 – n2;
Console.WriteLine(“Received Subtract({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine(“Received Multiply({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine(“Received Divide({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// Step 1 of the address configuration procedure: Create a URI to serve as the base address.
// Step 2 of the hosting procedure: Create ServiceHost.
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
// Step 3 of the hosting procedure: Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), “CalculatorService”);
// Step 4 of the hosting procedure: Enable metadata exchange.
ServiceMetadataBehavior smdb = new ServiceMetadataBehavior();
smdb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smdb);
// Step 5 of the hosting procedure: Start (and then stop) the service.
selfHost.Open();
Console.WriteLine(“The service is ready.”);
Console.WriteLine(“Press <ENTER> to terminate service.”);
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (Exception ex)
{
Console.WriteLine(“An exception occurred: {0}”, ex.Message);
selfHost.Abort();
}
}
}
}
With this the Service Part is done.You can run the Project to see the service Starting up. This normally takes time to load. Now we will create a client to listen to this service.
Let me take you through the ClientPart :(Console Application in the same solution as that of the service or you can create a new solution also)
1. Create a Console Application for the ClientPart, to listen to the Service & do some computation. Add the ServiceModel reference dll.
2. Goto Visual Studio Command Prompt. Go to the directory of your client console application,
say “C:\Users\<user name>\My Documents\Visual Studio 10\Projects\Service\Client
3. Go to your Service console application & run the service.
4. Once the service is up & running, execute the svcutil.exe command like this:
svcutil.exe /language:cs /out:GeneratedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
This will generate 2 files for you, the app.config (WCF configuration file) and the GeneratedProxy.cs file (the Proxy implementation of the service)
5. Import these two files to the Client console application. To view the app.config file, you need to select “All Files(*)” option in the file types.
6. Go to the Program.cs. Instantiate the  CalculatorClient (from the GeneratedProxy.cs)
Full Code (Program.cs):
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace ServiceModelSamples
{
class Client
{
static void Main()
{
//Step 1: Create an endpoint address and an instance of the WCF Client.
CalculatorClient client = new CalculatorClient();
// Step 2: Call the service operations.
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine(“Add({0},{1}) = {2}”, value1, value2, result);
// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine(“Subtract({0},{1}) = {2}”, value1, value2, result);
// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine(“Multiply({0},{1}) = {2}”, value1, value2, result);
// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine(“Divide({0},{1}) = {2}”, value1, value2, result);
//Step 3: Closing the client gracefully closes the connection and cleans up resources.
client.Close();
Console.WriteLine();
Console.WriteLine(“Press <ENTER> to terminate client.”);
Console.ReadLine();
}
}
}
Now we have both the service & the client ready in our solution.
To execute:

Step 1: Set the Service Project as the startup project & press Ctrl + F5, not F5. Ensure that the console screen says Service is up & running.
Step 2: Set the Client Project as the startup project & press Ctrl + F5. The console screen popups up with the results displayed. The service console screen
will have the status of received & returned values.
I am attaching some screenshots here to give you some heads up.
The Service Up & Running:
The Service & the Client Up & Running together:
Hope this was useful.
Special Note: This tutorial is taken from MSDN directly! But since contents were scattered across pages i just collated all of them to help readers understand the concept.
  1. Very soon this website will be famous among all blogging and site-building viewers, due to it’s
    pleasant posts

    Reply

  2. Hi just wanted to give you a brief heads up and let you know a
    few of the images aren’t loading correctly.
    I’m not sure why but I think its a linking issue.

    I’ve tried it in two different internet browsers and both show
    the same results.

    Reply

  3. Is essentially like an marketing programme which you do not have to
    essentially spend. They appear your Facebook web page on their site and let other individuals to
    like it. When they like your Facebook page they will earn credits to market their own Facebook fan pages.
    facebook likes hack [www.ikonnext.com]

    Reply

  4. It’s very simple to find out any topic on web as compared to books, as I found this paragraph at this website.

    Reply

  5. Excellent post. I used to be checking constantly this weblog and I’m inspired!
    Extremely helpful information specially the remaining part
    🙂 I care for such info much. I was seeking this particular info for a long time.
    Thanks and good luck.

    Reply

  6. Why users still make use of to read news papers when in this technological globe
    everything is presented on web?

    Reply

  7. prabhakar n. rao May 10, 2012 at 10:09 AM

    For novice or beginners this is really x’lent, thanks a lot, it’s useful
    for those appearing or preparing for 70-513.
    raosir

    Reply

  8. Hi all,

    Please explain below concepts for beginner level and request to provide us the ref link and ppt if any.

    WCF Architecture & Advantages
    contracts &Bindings
    Consuming WCF in ASP.NET application.
    Hosting WCF
    Handling Errors by Using WCF.

    I have interview on Thursday before that anyone can help me on below concepts its will be grateful.

    Thanks
    SS

    Reply

  9. gud one. thnx 🙂

    Reply

  10. Nav :very useful….

    nice

    Reply

  11. It is not very nice to copy an article from someplace esle without giving credit

    This article is an exactl copy of the Microsoft MSDN documentation

    Reply

    1. Yes Michael, you are right. I missed the note.
      Thanks.I have added a note at the bottom.

      Reply

    2. 🙂 Yep your right..credit is due to the original author…

      Reply

  12. helped me lot

    Reply

  13. This is very very helpfull as well as nice tutorial.

    Reply

  14. Why not point to the original instead of copying it? http://msdn.microsoft.com/en-us/library/ms730210.aspx

    Reply

    1. Yes it is taken from MSDN! But since contents were scattered across pages i just collated all of them to help readers understand the concept.

      Reply

  15. very useful….

    Reply

Leave a Reply to August Cancel 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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: