Pages

Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Thursday, July 9, 2009

Getting Started with WCF Service

In this post, I will walk you through creating your first Windows Communication Foundation Service. Those new to WCF should read my previous post to understand the basics concepts of WCF Service.


Introduction

Before a WCF Service can be consumed by a client application, the following three steps are required:

Service: The actual WCF Service which provides business functionality
Host: A hosting environment which hosts the service
Client: A client application/service which invokes the WCF Service

In the following sections, we will create a solution which consists of three separate projects representing the service, host and the client respectively. I will be using Visual Studio 2008 to create the application.


Getting Started

1. Start a new instance of Visual Studio 2008.
2. Click on File -> New Project. From Project types pane, select Visual Studio Solutions
3. From the Template pane, select Blank Solution
4. Enter WCFIntroduction for Project Name. Also specify the location according to you working preference

This will create a blank solution as shown in figure 1. Let us now create the actual WCF Service.


Fig 1



Creating the Service

1. In the solution explorer, right click on ‘WCFIntroduction’ and select Add -> New Project.
2. Select Class Library template and name it as WCFCalculator. Make sure that the location is set to ..\WCFIntroduction as shown in figure 2. Click OK to create the project.


Fig 2



3. The newly created project contains a single file ‘Class1.cs’. Rename it to ‘WCFCalculatorService.cs’. We will return to this file shortly.
4. From the solution explorer, right click on ‘WCFCalculator’ project and select ‘Add Reference’. The ‘Add Reference’ dialog appears. From the .NET tab, select ‘System.ServiceModel’ and click OK. A reference to the respective namespace is added which is required to work with WCF Services
5. Again right click on ‘WCFCalculator’ project and select Add -> New Item. Select ‘Class’ template, name it as ‘IWCFCalculatorService.cs’ as shown in figure 3 and click Add
6. This will create a new class file ready to be coded


Fig 3


7. Change the class definition to ‘public interface IWCFCalculatorService’. Type in the code as shown in listing 1 and save the file

Listing 1


using System;
using System.ServiceModel;

namespace WCFCalculator
{
[ServiceContract(Namespace = "http://youruniquedomain")]
public interface IWCFCalculatorService
{
[OperationContract]
int AddNumbers (int x, int y);
}
}


8. Let us now return to the ‘WCFCalculatorService.cs’ file. Open it and type in the following code:


Listing 2


using System;
using System.ServiceModel;

namespace WCFCalculator
{
public class WCFCalculatorService : IWCFCalculatorService
{
public int AddNumbers (int x, int y)
{
return x + y;
}
}
}


Compile this project to make sure there are no errors. We have just created a very basic WCF Service used to add two numbers. The next step is to host this service in a hosting environment. In the following section, we will create a windows console application which will host this service.



Hosting the Service

1. Right click on the solution ‘WCFIntroduction’ and select Add -> New Project.
2. Select ‘Console Application’ template, name it as ‘Host’ as shown in figure 4 and click OK


Fig 4

3. Right click on ‘Host’ project and select Add Reference. From the .NET tab, select System.ServiceModel. From the Projects tab, select ‘WCFCalculator’ and press OK
4. The Host project consists of one file ‘Program.cs’. Open this file and type in the code as shown in listing 3


Listing 3


using System;
using System.ServiceModel;

namespace Host
{
class Program
{
static void Main (string[] args)
{
using (ServiceHost host = new ServiceHost (typeof (WCFCalculator.WCFCalculatorService), new Uri ("http://localhost:8000/WCFCalculator")))
{
host.AddServiceEndpoint (typeof (WCFCalculator.IWCFCalculatorService), new BasicHttpBinding (), "WCFCalculatorService");
host.Open ();

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


5. Compile this project. Make sure that the Host project is set as Startup Project (You can do so by right clicking on Host project and select ‘Set as Startup Project’). Press Ctrl+F5 to run this project. You should see a command window with message ‘Press to terminate service...’ as shown in figure 5. This means the service is up and runninig. Keep this window open (service is active). Next we will create a client application which will interact with this service. Let us return to our solution.


Fig 5


Consuming the Service – Client Application

1. Right click on solution ‘WCFIntroduction’ and select Add -> New Project
2. Select ‘Console Application’ template, name it as Client and click OK as shown in figure 6


Fig 6

3. Add a reference to System.ServiceModel namespace (as done in the above steps)
4. This project consists of a single file ‘Program.cs’. Open this file and type in the code as shown in listing 4


Listing 4


using System;
using System.ServiceModel;

namespace Client
{
class Program
{
static void Main (string[] args)
{
EndpointAddress endPoint;
IWCFCalculatorService proxy;
int result;

endPoint = new EndpointAddress ("http://localhost:8000/WCFCalculator/WCFCalculatorService");
proxy = ChannelFactory.CreateChannel (new BasicHttpBinding (), endPoint);
result = proxy.AddNumbers (2, 3);

Console.WriteLine ("2 + 3 = " + result.ToString ());
Console.WriteLine ("Press to terminate client...");
Console.ReadLine ();
}
}
}


5. Here is the tricky part. In the above code, a proxy is created using the Service Contract (IWCFCalculatorService). To use this interface, copy it over from the ‘WCFCalculator’ project to the ‘Client’ project. Don’t forget to change the namespace to ‘Client’ in this file (In short the same interface now exists in both the ‘WCFCalculator’ and ‘Client’ project).
6. Compile the ‘Client’ project and make it the Startup Project (Right click on ‘Client’ project and select ‘Set as Startup Project’). Press Ctrl+F5 and you should see the output as shown in figure 7


Fig 7

Wow, you just create a WCF service from scratch and got it working. Though it may not be simple, I am sure it’s worth a try.


How it Works

Let me explain some of the concepts discussed in the above sections. If you have read my previous post, many of the details should be self explanatory. In listing 1, the IWCFCalculatorService interface is the Service Contract since it is decorated with the [ServiceContract] attribute. The single method within this interface - AddNumbers – is a WCF method as its decorated with the [OperationContract] attribute. Since IWCFCalculatorService is a service contract, any class implementing this interface becomes a WCF Service. This is also true for the WCFCalculatorService class as shown in listing 2.

In listing 3, an instance of ServiceHost class is created. This class provides a host for a WCF Service. It accepts two parameters, Type and params respectively. The Type parameter specifies the type (WCFCalculator.WCFCalculatorService) of the service while params specifies a collection of addresses (http://localhost:8000/WCFCalculator) where the service can be hosted. Next the ServiceHost defines a new Endpoint by calling the AddServiceEndPoint (). This method accepts two parameters including a contract (WCFCalculator.IWCFCalculatorService) and the type of binding (basicHttp) used by the Endpoint. Once an endpoint is defined, the service is open and available to accept requests from the client.

For a client to communicate with the service, a proxy is required. In listing 4, the generic ChannelFactory service model type generates the proxy and the related channel stack. This factory uses an instance of the EndpointAddress class which provides a unique network address (which points to the service endpoint) used by the client to communicate with the service. The factory creates a service of type IWCFCalculatorService. Later the generated proxy is used to invoke the required funcationlity.


Summary

In this post, I walked you through creating your first WCF Service. You may find it a bit difficult in the beginning but as you gain experience, WCF is a great tool to work with. In future post, I will talk more about WCF. So stay tuned for more…

Tuesday, June 30, 2009

Fundamentals of Windows Communication Foundation



In this post, we will look at the fundamental concepts behind Windows Communication Foundation or WCF (formally known as Indigo). This is not a walkthrough post rather it emphasis on the concepts which make up WCF. Creating and working with WCF Services will be a topic of future post.


What is Windows Communication Foundation

WCF is Microsoft’s flagship technology for developing Distributed application. It is a development platform which targets Service-Oriented Architecture. WCF provides a loosely coupled and interoperable platform for developing service-oriented applications.

Before the introduction of WCF, technologies such as .NET Remoting, COM, DCOM+ and MSMQ have existed for developing distributed applications. The downfall of these technologies has been coupling to a specific technology. Only a .NET Remoting client can talk to a .NET Remoting server. This means that’s its almost impossible for a Java-based client to talk to a .NET Remoting Server. Although Web Services have addressed the issue of interoperability to a greater extent, the introduction of Enhancement have started yet another race between different vendors.

To overcome the problem of interoperability and tight coupling, Microsoft introduced Windows Communication Foundation with .NET Framework 3.0. The System.ServiceModel assembly provides the core functionality for WCF. WCF provides a single programming model for developing distributed applications. It supports different protocols, behaviors and policies. This means the same WCF Service can be exposed to clients using different protocols. This way the service encompassing the business functionality remains the same but has different interfaces to interact with.




How does a WCF Service Work

Before I proceed to explain the different concepts behind WCF, I want to give you a faint idea of how a WCF application is organized. Basically a WCF application consists of three parts:

Service: The service exposes the business functionality to the rest of the world
Host: Before a service is available, it must be hosted in an environment.
Client: The client is an application or yet another service which accesses the service

Let us now look at the different concepts which make up a WCF application in the following sections.



Service and Contract

A service is a set of business functionality. From a .NET point-of-view, a service represents a CLR type. This type exposes different methods which can be invoked by client. For a type to be WCF Service, it must have a service contract. A service contract is defined by applying the [ServiceContract] attribute on a class or an interface. Any class implementing an interface with associated service contract is also a WCF service. Following listing shows a simple service contract:


[ServiceContract (Namespace="http://myuniquenamespace/")]
public interface IMaths
{
[OperationContract]
int AddTwoNumbers (int x, int y);
}

It is quite obvious that a class/interface define methods to be invoked. All methods exposed by a WCF Service must be decorated with the [OperationContract] attribute. A method without this attribute is not a part of the WCF Service. You must keep in mind that the OperationContract can only be applied to methods and not to a property or event. Why, because WCF is about exposing business functionality and business functionality resides in methods. For this reason, the OperationContract is only specific to methods.


Hosting

As I mentioned above, before a service can be accessed, it must be hosted in a host process. A host process can be any Windows Process. We can host multiple services under one host process or vice versa. There are three kinds of hosting available including:

Self Hosting: In self-hosting, the programmer is responsible for providing a hosting environment for the service which can include a Console application, Windows Form, WPF application or Windows NT Service.

IIS Hosting: A service can be hosted like a regular asp.net application. This requires a .svc file to be hosted in IIS

WAS Hosting: The Windows Activation Service (WAS) is only available for Windows Vista. Like IIS Hosting, WAS also requires a .svc file and is available for different protocols.

Under the hood of every host, the WCF Service Model is responsible for handling the communication. The ServiceHost class (a part of the service model) initiates the communication channel. A ServiceHost has an associated service type, address, service contract and communication protocol.



Addresses

Each WCF service has a unique address which a URI (Universal Resource Identifier). The URI has the following syntax:

[scheme]://[domain|machine-name][:port]/[optional [path]

A scheme defines the transport protocol used for communication. These protocols can include HTTP, TCP, name-pipes, MSMQ etc. Each of these protocols has an associated scheme such as http, net.tcp etc. The domain is the name of the machine or domain hosting the service. The port identifies the communication port associated with a specific protocol. A path can be used to avoid ambiguity. For example, we may have two services hosted on the same address. In this case, the optional path will give a separate address for each hosted service. The following shows a few examples of addresses:

http://www.mydomain.com
net.tcp://localhost/servicename
net.pipe://localhost:5500/myservice



Binding

Binding represents the options of choosing from different transport protocols, message encoding formats, security and reliability options for communication. When it comes to using a combination of these features, the options are countless - almost. For example, one may decide to use Http, Https, TCP, MSMQ, Named Pipes etc. as a transport protocol. Message encoding can be based on Binary Serialization or XML formatting. Security is yet another broad area to select from. If we plot a matrix of available options, we will end up with a very long list.

WCF Binding simplifies the above process by grouping together different options. For example HttpBasicBinding supports Http/Https protocols, Text/MTOM encoding format and is interoperable between existing and new web services format. Similarly, NetTcpBinding supports TCP protocol, Binary formatting and is not interoperable with other protocols. Details of different binding options can be found here.



Endpoint

To initiate communication with a service, the service model (ServiceHost) must provide an Endpoint. An endpoint is basically the trilogy of Address, Binding and Contract (commonly known as the ABC of a service). A service must have at least one endpoint, although it can have multiple endpoints. The ServiceHost must be initialized with one or more endpoints before communication commences.

Since a service can expose more than one endpoint, the same service is available with different communication options. For example, Service-A may be available over Http for web services but is also is available over TCP behind a firewall. It all comes down to the user requirements but the options are numerous. Endpoints can be configured using config files or programmatically.



Metadata

A service is attached to an endpoint where each endpoint has associated address, binding and contract. The client communicates with this endpoint to invoke business functionality. But the client needs to know about the endpoint before interacting with the service. Metadata provides information about an endpoint to the clients. Metadata can be generated by the help of a ServiceHost. The ServiceHost can either expose a metadata endpoint (this is different from the service endpoint) or can generate a WSDL file representing the metadata.


Proxy

A client can only communicate with a service using a proxy. A proxy acts on behalf of the service and exposes methods to the client. It also handles the underlying plumbing associated with the communication i.e. it handles message serialization, encoding format etc. A proxy communicates with one endpoint so it’s a one-to-one relationship. Proxies are generated by the help of metadata of a service.

With this we come to the end of this post. Future posts will talk about creating WCF Services. So stay tuned for more…