Getting Started with WCF – Simple WCF Service and WCF Client

This tutorial explains how to create a simple WCF Service and a simple WCF Client. For this tutorial you will need Visual Studio 2010 and knowledge of C#.

If you are new to WCF, to find out more go to Microsoft WCF Developer Center.

Creating WCF Service

Creating Service

1) Open Visual Studio 2010. Click on File -> New Project -> Visual C# -> Console Application. In the “Name” textbox enter “WCFServiceExample”. (Make sure target framework is 4.0)

2) Add refernece to System.ServiceModel. Right-click References -> Add Reference. Go to .Net tab and select System.ServiceModel (version 4.0.0.0)

3) In Program.cs file, add:

using System.ServiceModel;
using System.ServiceModel.Description;

4) Define a service contract. Add the following code to Program.cs file:

[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
	[OperationContract]
	double Add(double n1, double n2);
	[OperationContract]
	double Subtract(double n1, double n2);
}

5) Add a class with service contract method implementations. Add the following code to Program.cs file

public class CalculatorService : ICalculator
{
	public double Add(double n1, double n2)
	{
		double result = n1 + n2;
		return result;
	}

	public double Subtract(double n1, double n2)
	{
		double result = n1 - n2;
		return result;
	}
}

6) Now we need to set up the service. Add following code to Main() method in Program.cs, so that Main() looks like this:

static void Main(string[] args)
{
	//address for the service
	Uri baseAddress = new Uri(
		"http://localhost:8000/ServiceModelSamples/Service");
	//Service host instance to host this service
	ServiceHost selfHost = new ServiceHost(typeof(CalculatorService),
		baseAddress);

	try
	{
		//Add endpoint that exposes the service
		selfHost.AddServiceEndpoint(typeof(ICalculator),
			new WSHttpBinding(), "CalculatorService");

		//Enable metadata exchange
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
		smb.HttpGetEnabled = true;
		selfHost.Description.Behaviors.Add(smb);

		//Open ServiceHost and wait for incoming messages.
		selfHost.Open();
		Console.WriteLine("The service is ready.");
		Console.WriteLine("Press to terminate service.");
		Console.WriteLine();
		Console.ReadLine();

		// Close the ServiceHostBase to shutdown the service.
		selfHost.Close();
	}
	catch (CommunicationException ce)
	{
		Console.WriteLine("An exception occurred: {0}", ce.Message);
		selfHost.Abort();
	}
}

Thats all you need to do to create WCF service. Full code inside Program.cs file should look like this:

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

namespace WCFServiceExample
{
	class Program
	{
		static void Main(string[] args)
		{
			//address for the service
			Uri baseAddress = new Uri(
			"http://localhost:8000/ServiceModelSamples/Service");

			//Service host instance to host this service
			ServiceHost selfHost = new ServiceHost(
				typeof(CalculatorService), baseAddress);

			try
			{
				//Add endpoint that exposes the service
				selfHost.AddServiceEndpoint(
					typeof(ICalculator),
					new WSHttpBinding(),
					"CalculatorService");

				//Enable metadata exchange
				ServiceMetadataBehavior smb =
					new ServiceMetadataBehavior();
				smb.HttpGetEnabled = true;
				selfHost.Description.Behaviors.Add(smb);

				//Open ServiceHost
				//and wait for incoming messages.
				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 (CommunicationException ce)
			{
				Console.WriteLine("An exception occurred: {0}",
				ce.Message);
				selfHost.Abort();
			}
		}

		[ServiceContract(
			Namespace = "http://Microsoft.ServiceModel.Samples")]
		public interface ICalculator
		{
			[OperationContract]
			double Add(double n1, double n2);
			[OperationContract]
			double Subtract(double n1, double n2);
		}

		public class CalculatorService : ICalculator
		{
			public double Add(double n1, double n2)
			{
				double result = n1 + n2;
				return result;
			}

			public double Subtract(double n1, double n2)
			{
				double result = n1 - n2;
				return result;
			}
		}
	}
}

Creating WCF Client

1) Open Visual Studio 2010. Click on File -> New Project -> Visual C# -> Console Application. In the “Name” textbox enter “WCFClientExample”. (Make sure target framework is 4.0)

2) Add refernece to System.ServiceModel. Right-click References -> Add Reference. Go to .Net tab and select System.ServiceModel (version 4.0.0.0). In Program.cs file, add:

using System.ServiceModel;

3) Now add WCF service reference. Start the WCF Service created previously. Right-click Referneces -> Add Service Reference. Enter http://localhost:8000/ServiceModelSamples/Service as Address and click Go. Enter WCFService as Namespace. Click OK.

4) Create WCF client instance inside Main() with:

WCFService.CalculatorClient client = new WCFService.CalculatorClient();

5) Now call service operations. Inside Main() add following code:

// 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);

6) All that is left to do now is to close client gracefully. Add following code to Main():

client.Close();

That is all that is needed to create WCF client. Full code inside Program.cs file should look like this:

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

namespace WCFClientExample
{
    class Program
    {
        static void Main(string[] args)
        {
            WCFService.CalculatorClient client =
				new WCFService.CalculatorClient();

            //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);

            //Closing the client gracefully closes the connection
			//and cleans up resources.
            client.Close();

            Console.WriteLine();
            Console.WriteLine("Press Enter to terminate client.");
            Console.ReadLine();
        }
    }
}

And that is it. Start the Service exe file first, and then start the Client exe file. The client should perform Add and Subtract functions and display results. Press Enter key on both Service and Client to close them down.

Advertisements

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