Tuesday, September 23, 2008

Implementation of a Simple WCF Service

Implementation of a Simple WCF Service
In this section, we will see the steps involved in creating a simple WCF service. Since the focus of this section is to get familiar with the service development steps, We will keep the service implementation simple. The service is a simple MathService that implements a service contract named IMathService. This exercise has six development steps:
1. Create the service
2. Choose the service hosting mechanism
3. Create the service configuration file
4. Create the client
5. Create the proxy and configuration file for the client
6. Implement and run the client
We will see this steps one by one
1. Create the Service
To start with, create a new project named WCFBasics using Visual Studio 2005 as shown in the below screenshot.

Once the project is created, add a new WCF Service using the Website->Add New Item menu option and name the service MathService.
After the service is created, you should see a MathService.svc file in your project with the below line of code.

Note that the MathService.svc has a code-behind file (named MathService.cs) that is placed in the App_Code directory. Open up the MathService.cs and modify its code to look as follows:
using System;
using System.ServiceModel;
[ServiceContract]
public interface IMathService
{
[OperationContract]
int Add(int x, int y);
[OperationContract]
int Subtract(int x, int y);
[OperationContract]
int Divide(int x, int y);
}
public class MathService : IMathService
{
public int Add(int x, int y)
{ return x + y; }
public int Subtract(int x, int y)
{ return x - y; }
public int Divide(int x, int y)
{ return x / y; }
}
2. Choose the Service Hosting Mechanism
As mentioned before, WCF is flexible because its services can be hosted in different types of applications. For the purposes of this installment, let us use IIS for hosting the WCF services because of its simplified configuration.
3. Create the Service Configuration File
Configuration-based development permits part of an application's behavior to be specified in configuration files. You can make such things as addresses, bindings, security details, service behavior, and tracing changeable without having to modify and recompile the program code. By specifying addresses, bindings, and behaviors in a configuration file, you can make deploy-time decisions about services that don't require any modification to the service programs themselves.As mentioned before, by using IIS you can take advantage of IIS features such as service activation, process recycling and so on. To host the MathService in IIS, modify the Web.config in the Web service project to look as follows:


Through its attributes, the element under \ specifies the name of the service as well as the name of the behavior configuration that will be used to control the behavior of the service. The element also contains another child element named that enables you to specify the address, contract, and binding for the service. In this case, since IIS is the hosting mechanism, the address attribute is set to "". For an IIS-hosted application, the endpoint address should be defined by the physical *.svc file and the name of its hosting virtual directory and should have an empty value unless you would like to give it an extension and assign a different set of bindings to it. For example, in this case if the endpoint address="", then the actual communication endpoint is http://localhost/MyWCF/MathService.svc. Note that the contract attribute is set to the name of the interface, which is IMathService in this case. To expose the service through HTTP, the binding attribute is set to "wsHttpBinding".
4. Create the Client
To test the service, let us create an ASP.NET Web site named WCFServiceClient with Visual C# as the language of choice. Once the Web site is created, you now need to create a proxy for the WCF service that was created earlier. In addition, you also need to create a configuration file that contains the configuration settings required to connect to the service. You can accomplish both of these through a new utility called svcutil.exe.
5. Create the Proxy and Configuration file for the Client
The Service Model Metadata Utility (svcutil.exe) builds the proxy and the corresponding configuration file based on the published service's metadata (WSDL + Schema + Policy). Once the service is up, running and listening, you can run svcutil.exe against the service endpoint address. For example, if it were an IIS-hosted service, it would be something like the following:
To use the svcutil utility, open up the command prompt through Start->Programs->Microsoft Visual Studio 2005->Visual Studio Tools->Visual Studio 2005 Command Prompt.
6. Implement the Client
Now that you have created the proxy and the configuration file, you are ready to work with them from the client application. Before that, create a new ASP.NET Web site named WCFBasicsServiceClient using Visual C# as the programming language. Once the Web site is created, add the proxy file MathService.cs to the App_Code folder. Also rename the output.config file created through the svcutil to Web.config and add that to the root of the Web site. If you open up the output.config file, you will notice it contains a number of configuration entries for controlling the invocation behavior of the client. However it is also possible for you to manually generate the Web.config file using the below lines of code:

Note the use of as the root of the service client configuration section. Inside that you have an element named that specifies that you are dealing with client configuration sections here. Underneath the element, you have an element named that captures the address, binding, and the contract information about the service.
At this point, you are ready to consume the service by writing code against the proxy. To this end, add a new ASP.NET Web page named MathServiceClient.aspx and modify its code to look as follows:

The above implementation is very simple. It invokes the various methods of the MathService using the proxy class (generated through the svcutil utility) from the previous section and displays the results of the invocation through a label control. If you navigate to the page using the browser, you should see an output that is somewhat similar to the following:



Windows Communication Foundation [WCF]

Windows Communication Foundation

Prerequisites
* Visual Studio 2005 Professional Edition
* Microsoft Pre-Release Software Microsoft .NET Framework 3.0 - Release Candidate
* Microsoft Visual Studio Code Name "Orcas" Community Technology Preview - Development Tools for .NET
Famework 3.0
* Microsoft® Windows® Software Development Kit for RC 1
Introduction to WCF
WCF is a set of .NET Framework-based technologies for building and running services. WCF is the next step in the evolutionary path that started with COM, COM+, and MSMQ, and continues through .NET Remoting, ASMX, System. Messaging and .NET Enterprise Services. WCF combines these technologies and offers a unified programming model for developing services using any CLR-compliant language. The below screenshot provides a conceptual representation of the different components that make up the WCF architecture.




As you see from the above, the major subsystems of WCF are the Service model, the connector framework, hosting environments, and system and messaging services. The WCF service model makes service-oriented development explicit and simple from any CLR-targeted language. You use declarative attributes to mark up which aspects of their type should form the external contract of a service. The service model supports different types of contracts including service contracts, operation contracts and so on, which will be discussed later in this article. The service model also provides instance and context management for a service. WCF routes incoming messages to instances of user-defined service types. As a developer, you can leverage the declarative attributes to control how instances are associated with incoming messages as well as how the session management features of Indigo routes multiple messages to a common session object. Finally, the service model provides declarative behaviors that automate security and reliability. All of the above functionalities of service model are contained in the System.ServiceModel namespace.
Key Components of a WCF Service
A WCF service program contains four elements:
Contract definitions - A service must have at least one service contract, and it might contain multiple service contracts, data contracts, or message contracts
Endpoint definitions - One or more address-binding-contract endpoints must be declared
Hosting code - Some code is needed to create and start the service
Implementation code - The service contracts in a service need code to implement their service operations
Let us look at each of these components in detail.


Understanding Contracts
Contracts are one of the fundamental concepts in WCF. They allow clients and services to have a common understanding of available operations, data structures, and message structures while remaining loosely coupled and platform independent. WCF includes four kinds of contracts:
Service contract - Describes the operations a service can perform. A service contract is defined with the [ServiceContract] and [OperationContract] attributes. Binding requirements can be specified for the contract with a [BindingRequirements] attribute.
Data contract - Describes a data structure. A data contract is defined primarily with the [DataContract] and [DataMember] attributes.
Message contract - Defines what goes where in a message. A message contract is defined primarily with the [MessageContract], [MessageBodyMember], and [MessageHeader] attributes.
Fault contract - Allows you to document the errors that WCF code is likely to produce. A fault contract is specified along with the operation contract at the time of declaring the method. A fault contract is defined using the [FaultContract] attribute.
All four types of contracts translate between Microsoft .NET types used internally and the XML representations shared externally:
> A service contract converts between the CLR and Web Services Description Language (WSDL)
> A data contract converts between the CLR and XML Schema Definition (XSD)
> A message contract converts between the CLR and Simple Object Access Protocol (SOAP)
> A fault contract converts the CLR exceptions and to SOAP faults
You define contracts by using familiar object-oriented constructs: interfaces and classes. By decorating interfaces and classes with attributes, you create contracts.
Understanding Service Contracts
A service contract describes the operations a service can perform. A service must have at least one service contract, and it can have more than one. You can think of a service contract as follows:
* It describes the client-callable operations (functions) exposed by the service
* It maps the interface and methods of your service to a platform-independent description
* It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
* It is analogous to the element in WSDL
You define a service contract by annotating an interface (or class) with the [ServiceContract] attribute. You identify service operations by placing [OperationContract] attributes on the methods of the interface. The following service contract defines only one service operation.
[ServiceContract]

public interface IHelloWorldService

{

[OperationContract]

string HelloWorld (string input);

}
Once you define a service contract using an interface, you can write a class to implement the interface. For example:
Public class HelloWorldService : IHelloWorldService

{

public string HelloWorld(string input) { return "Hello " + input; }

}
It is also possible for you to define the service contract directly against the implementation class and skip the interface altogether. The following class both defines and implements a service contract.
[ServiceContract]

public class HelloWorldService

{

[OperationContract]

public string HelloWorld(string input) { return "Hello " + input; }

}
Although this approach works, it is not a recommended way to create services as interfaces allow you to separate the implementation from the definition of a service.

Understanding Bindings
The bindings of a WCF service define how an endpoint will communicate with an external client. A binding has several characteristics, including the following:
* Transport protocols - Some of the choices include HTTP, Named Pipes, TCP, and MSMQ.
* Encoding - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
* Security - Includes wire security (SSL) or schema-defined security (WS-Security).
Bindings can also determine if you are using sessions or a transacted communications channel. You have the choice of creating custom channels or using prebuilt bindings. WCF comes shipped with nine built-in bindings. The following table lists the WCF build-in bindings and their associated features.



You can choose the right binding to use by mapping the features they support to your requirements.
Hosting WCF Services
As for where to put your code and what it compiles to, you have some choices. You can host your service in Internet Information Services (IIS), or you can write a small amount of extra code to host a service yourself. You can self-host a service from just about any environment that supports managed code, including a WinForms application, console application, library assembly (DLL), or Windows Service controlled through SCM (Service Control Manager). The following lists show the common hosting mechanisms for WCF services.
* IIS (Internet Information Services) - IIS provides a number of advantages if the service uses HTTP as its transport. The nice thing about using IIS is that you don't have to write any hosting code as part of the application since IIS automatically activates service code as required. Services also benefit from IIS features such as process lifetime management and automatic restart after configuration changes. To run services using IIS, you create the service code along with its configuration file and simply save them in an IIS virtual directory.

What's New to .NET 3.5

Visual Studio 2008 and .NET 3.5 contain a lots of new functionality and improvements
  • VS 2008 Multi-Targeting Support :VS 2008 enables you to build applications that target multiple versions of the .NET Framework. This means you can use VS 2008 to open, edit and build existing .NET 2.0 and ASP.NET 2.0 applications (including ASP.NET 2.0 applications using ASP.NET AJAX 1.0), and continue to deploy these application on .NET 2.0 machines.
  • ASP.NET AJAX and JavaScript Support :.NET 3.5 has ASP.NET AJAX built-in no separate download required. In addition to including all of the features in ASP.NET AJAX 1.0, ASP.NET 3.5 also now includes richer support for UpdatePanels integrating with WebParts, ASP.NET AJAX integration with controls like and , WCF support for JSON, and many other AJAX improvements.
  • VS 2008 Web Designer and CSS Support :VS 2008 and Visual Web Developer 2008 Express includes a significantly improved HTML web designer. This delivers support for split-view editing, nested master pages, and great CSS integration.
  • Language Improvements and LINQ : The new VB and C# compilers in VS 2008 deliver significant improvements to the languages. Both add functional programming concepts that enable you to write cleaner, terser, and more expressive code. These features also enable a new programming model we call LINQ (language integrated query) that makes querying and working with data a first-class programming concept with .NET.
  • Data Access Improvements with LINQ to SQL :LINQ to SQL is a built-in OR/M [object relational mapper] in .NET 3.5. It enables you to model relational databases using a .NET object model. You can then query the database using LINQ, as well as update/insert/delete data from it. LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy way to integrate business logic and validation rules into your data model.
  • Lots of other improvements :The list above is only a small set of the improvements. For client development VS 2008 includes WPF designer and project support. ClickOnce and WPF XBAPs now work with FireFox also. WinForms and WPF projects can also now use the ASP.NET Application Services (Membership, Roles, Profile) for roaming user data.
    Office development is also much richer - including support for integrating with the Office 2007 ribbon, and with Outlook. Visual Studio Tools for Office support is also now built-into Visual.
    New WCF and Workflow projects and designers are now included in VS 2008. Unit testing support is now much faster and included in VS Professional. Continuous Integration support is now built-in with TFS. AJAX web testing (unit and load) is now supported in the VS Test SKU. And there is much, much more...

Thanks