MyITBlog.com - IT Professionals Online Journal
 
  Home  |   Site News  |   About Us  |   Privacy  |   FAQ  |   Contact   Add Blog Entry  |  Login  |  Register   
 My Account
Username
Password
Remember me
Lost Password?


 Categories


  HOME  >  ProgrammingPrint


0
Votes
Programming your First WCF service in Programming   
by sundararajan on 18 Feb 2006, 07:22     Read sundararajan's Blog
Total Hits: 44086    Comments: 0   

Windows communication foundation previously code named ‘Indigo’ is the Microsofts next generation programming platform for building Distributed systems.In this article we will deal with the basics of Windows communicaiton foundation service and a simple walkthrough of creating a simple WCF service with VS2005..

 

Windows Communiction Foundation Service(Indigo):

 

Indigo combines and extends the capabilities of existing Microsoft distributed systems technologies, including Enterprise Services, System.Messaging, .NET Remoting, ASMX, and WSE to deliver a unified development experience.

          Windows communication foundation service  is primarily based on the System.ServiceModel namespace. This is the Programming interface to the developers. The System.ServiceModel namespace is very rich in its design so that it allows much easier programming interface.

 

Before getting into first programming sample of a WCF service, lets look into the programming model of the WCF service.

Programming Model:

 

The Programming model mainly constitutes of the End points.

 

The endpoint is the basic unit of communication in Windows Communication Foundation (WCF). Each endpoint is made up of three elements: an address, a binding, and a contract,

 

  1. Address
  2. Binding
  3. Contracts

 

Address: Address specifies the info about where can I find my service.

Binding: Binding specifies the info  that how can I interact with my service.

Contracts: contracts specifies the info that how my service is implemented and what it can offer me.

 

Three methods of programming are supported in the Indigo programming model:

  1. Declarative programming: the usage of attributes for the types
  2. Imperative programming: OO based programming in code.
  3. Configuration based programming: specifying the information required in the .config files(web.config/App.config)

 

Now lets look into the various components that constitutes the WCF service.

 

Address:

     Every WCF enpoint must have an address so that other end points can initialise the communication.

 

Each Address consists of an Uri and Address properties.

The address properties consists of an Identity and optional Headers.

 

The endpoints can be added programmatically or in configuration files. The configuration files provide the flexibility of changing the endpoints in the future without a need to recompile the application and deploying it.

 

Addresses will be of the format http://localhost:8000/HelloWorld.

 

Binding:

Bindings describe how the endpoints communicate with the external world.

The bindings specify the following.

  1. The protocol stack.
  2. The transport protocol
  3. Encoding.

 There are a set of predefined bindings that ships with WCF.

The following is the comprehensive list of predefined bindings available and their descriptions

 

S.No

Binding

Description

1

BasicHttpBinding

For communication with ASMX based clients

2

wsHttpBinding

Secure WS interoperable binding for non duplex contracts

3

wsDualHttpBinding

Secure WS interoperable binding for duplex contracts

4

netTcpBinding

Secure reliable binding for Cross machine communication

5

NetNamedPipeBinding

For on machine communication

6

NetMsmqBinding

Queued binding for cross machine communication.

7

MsmqIntegrationBinding

maps Microsoft Message Queuing Service (MSMQ) messages to Windows Communication Foundation (WCF) messages

 

Contracts:

 

A contract specifies what the endpoint communicates. What the service can offer.It is a collection of messages. Called message exchange.(MEX).

 

Now lets take a look into how we can configure an endpoint using the configuration based programming approach.

 

<endpoint address="http://localhost:8000/hello1"

                  binding="wsHttpBinding"

                  bindingConfiguration="Binding1"

                  contract="Indigo.Programming.IHello" />

 

In the endpoint definition the address,  binding and contract are specified. Here we have used wsHttpBinding.

 

With this information into our thoughts we can go straight into developing a sample service application .

 

 

Developing a WCF Service.

 

   With VS2005  the developer experience of the indigo service is great. U have ready made templates available like WinFxService when you create a new project.

 

The service can be hosted in different means. Either in IIS or as a windows service or as a console application.

 

For this sample application we will develop the service as a console application.

 

Step 1: Creating a new service.

  1. IN VS2005 create a new C# console application project.
  2. Add System.service model as a reference from the .Net components tab.
  3. Add the statement using System.ServiceModel; in the class file.
  4. Copy the following code  in the EmployeeService.cs

 

using System;

using System.Collections.Generic;

using System.ServiceModel;

using System.Data;

using System.Data.SqlClient;

using System.Text;

 

namespace IndigoEmployeeService

{

    // Defining the contract.

 

    [ServiceContract]

    public interface IEmployeeService

    {      

        [OperationContract]

        DataSet GetInfo();

    }

 

    [ServiceBehavior]

    class EmployeeService:IEmployeeService

    {

        public DataSet GetInfo()

        {

            

            SqlConnection _conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;User Id=sa;Password=yukon;");

            _conn.Open();

            try

            {

                SqlDataAdapter _sqlAdapter = new SqlDataAdapter("select EmployeeID,LastName, FirstName, Address from employees", _conn);

                DataSet _employeeDs = new DataSet();

                _sqlAdapter.Fill(_employeeDs);

                return _employeeDs;

            }

            catch (Exception ex)

            {

                return null;

            }

            finally

            {

                _conn.Close();

                _conn.Dispose();

            }

           

 

        }

        public static void Main()

        {

            // Create a ServiceHost.

            Uri uri = new Uri("http://localhost:8000/EmployeeService1");

            using (ServiceHost serviceHost = new ServiceHost(typeof(EmployeeService), uri))

            {

                serviceHost.Open();

                Console.WriteLine();

                Console.WriteLine("The service is ready");

                Console.WriteLine();

                Console.WriteLine("Press ENTER to shut down service.");

                Console.WriteLine();

                Console.ReadLine();

                // Close the service.

                serviceHost.Close();

            }

        }

    }

}

 

 

The complete analysis of the code will be dealt with in the later part of the article.

 

Step 2: Add the configuration file to the service.

1.      rightclick on the service project and click add new item.

2.      add the Application configuration file.

3.      In the App.config, specify the ‘endpoint’ information and binding information.

4.      The end point can be configured as below:

 

<services>

      <service

          type="IndigoEmployeeService.EmployeeService"

          behaviorConfiguration="EmployeeServiceBehavior">

           <endpoint address="http://localhost:8000/EmployeeService1"

                  binding="wsHttpBinding"

                  bindingConfiguration="Binding1"

                  contract="IndigoEmployeeService.IEmployeeService" />

        </service>

    </services>

 

Lets deal with the elements in the config file above.

< service > tag:

 

  type: specifies the type of our service. This is the class name of the Service.<namespace.class>

behaviorConfiguration: specifies the behavior to be used to instantiate the service. This behavior is defined as below.

 

  <behaviors>

      <behavior

          name="EmployeeServiceBehavior"

          returnUnknownExceptionsAsFaults="True" >

      </behavior>

 </behaviors>

 

 

Now we have to define the properties of the end point. As we discussed earlier the endpoint has three elements address, binding and contract.

 

Address is the Uri object that we have specified in the EmployeeService.cs code . in this case it is    http://localhost:8000/EmployeeService1 if this is left as blank this will take the base address.

 

binding:- we use the predefined wsHttpBinding  that ships with WCF.

 

returnUnknownExceptionsAsFaults enables the unhandled exceptions to be returned as fault messages. This will be very much useful for debugging purposes.

 

 

Code Analysis- Employee service

 

First we define an interface IEmployeeService and mark it with [ServiceContract] Attribute in System.ServiceModel

 

Then we declare the operation to be performed by the service. In this case GetInfo() is a method that returns a data set. We mark it with [OperationContract] attribute.

 

Then comes the implementation of our servicecontract.

 

We implement the IEmployeeService contract i


 

Post Comment

Copyright © 2008 MyITBlog.com