AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1154&pId=-1
Start Development with Windows Communication Foundation
page
by Keyvan Nayyeri
Feedback
Average Rating: 
Views (Total / Last 10 Days): 33882/ 38

Introduction

In first and second parts of my tutorials entitled Introduction to Windows Communication Foundation and Fundamentals of Windows Communication Foundation I talked about principles of WCF and introduced this new technology in .NET 3.0.

In these parts I did not give any code, sample application or anything about development. After understanding all these principles, it is time to talk about programming model and start giving some examples.  We will discover basic concepts about development in this article and will follow our tutorials in the next parts by talking about each of fundamental concepts in more details (described in previous part).

However, this article is about programming model and development process in Windows Communication Foundation.  Before getting in, go back and read my previous articles about WCF to have a background about some concepts that we will use in this article.  If you have read them before or you are aware of these concepts then ignore them.

Development Process

Developing a WCF service (regarding its distributed service oriented nature) consists of three general steps that you will see in a moment. Each step may have some smaller steps for its own.  Based on the approach you follow and your needs for your application, it is possible to exclude one of these small steps.  However, main steps are constant.

·         Developing the Service

·         Developing the Client (or Clients)

·         Deployment

Let us see more details about these three steps.

Developing the Service

Here is where we provide all means to give necessary services to clients.  Usually we deploy one instance of a service to be used by as many clients that need this service.  Developing a good service depends on our understanding about some principles that I talked about before.  Choosing the best configurations to set up our channels, endpoints and providing our services is the main job that we need to do here.

A service can be hosted in Internet Information Services (IIS) or can have its own logic for hosting.  In the first case we do not need to care about starting or stopping a service and IIS does this automatically for us (so needs less code), but things are not as easy as this forever and sometimes we need to write self-hosted services.  Thankfully, this is possible and needs some extra code.

In addition to having a good Service Oriented Architecture for our application to build our service on its top, we need to choose the best choice for messaging pattern, contracts, schemas, security, etc. and this is not possible without practicing and writing different services.

There are three approaches in WCF development process:

·         Code First: In this approach you implement the service code logic then generate metadata information for your service.

·         Contract First: In the second approach you write your metadata information then begin writing service or client code because here their order does not matter and both of them follow this metadata information.

·         Contractless: In this third approach (which is less common) you get down to a lower level and work directly with messages and ignore contracts.

In the first and second approaches (Code First and Contract First) you can speed up your process by using a handy code generator tool that comes with .NET Framework 3.0 and is named SvcUtil.  SvcUtil helps you to work with metadata information easier.  You know working with XSD and WSDL is not easy and SvcUtil comes to help you in this way.  SvcUtil does three jobs for developers:

·         Generates WSDL and XSD metadata from the service assembly.

·         Generates proxy code for the client from service metadata from MEX endpoint.

·         Generates proxy code for the client from service metadata from WSDL and XSD.

Note that some services are self describing.  It means that you can provide MEX endpoints for a service and in this case you do not need to generate any code using SvcUtil.  Metadata information will be generated for service automatically.

You can run "SvcUtil /?" command from command line for more information about SvcUtil.

After choosing your approach to write service logic and contract, you can go to the next step to host your service on IIS or write your own code for self-hosting and configure your service based on your needs.

After configuration you can move to the client side and start writing your client using the proxy code that you have gotten from SvcUtil and your own configurations (created manually) or configurations that are generated by SvcUtil.  After this your application will be ready.

Do not worry!  We will see an example to demonstrate these theories.

Programming Model

In WCF programming we frequently deal with some concepts such as Service Contract, Data Contract, Message Contract and Service Operation on the service side.

Each of these concepts has a corresponding concept in object oriented programming and we will use them to implement our WCF concepts.  Usually we use an Object Oriented concept and mark it with an attribute to build our WCF concept.

These are some examples: Service Contract, Data Contract and Message Contract are implemented as interface.  For Service Contract we use ServiceContract, for Data Contract we use DataContract and for Message Contract we use MessageContract attributes.

In previous articles I mentioned that there are three approaches in WCF programming:

·         Declarative

·         Imperative

·         Configuration Based

And also I mentioned that normally we use a combination of these three approaches to build our WCF applications.

The declarative part of WCF programming is where we mark our classes, methods and interfaces with attributes to build WCF concepts.  Imperative part is where we write programming code logic for our applications and Configuration is where we configure our applications, define service endpoints, behaviors, etc.

We have three levels of programming in WCF (from top to down):

·         Typed Services: We write services like our Object Oriented applications and use methods and functions to get parameters and return results in simple and complex data types.

·         Untyped Services: We write services to use messages as parameters and returns types rather than simple or complex types.

·         Messaging-Layer: In this level we come down to the lowest level and directly work with messages.  Here you need to code for many details of your application.  One common example of this level is writing intermediaries.

Well, I think theories are getting boring.  Let us discover our example to cover much of these theories.

An Example

In this section we discover a simple example to show all development steps for a WCF application.  No, I am not going to write another "Hello World!" application.  Instead, I write a service which gets the name of an author on ASP Alliance and returns integer value of his articles number.  I will not get into much detail, such as fetching my data from the database.  I just store some information about some authors in a collection and return them.

My service will be hosted in IIS and I will get access to it by writing a Windows Console Application.  The user enters a name and the client passes it to a service then gets the number of the articles and shows them to user in console.  In a nutshell I have to follow these steps to write my application:

·         Develop the service

·         Configure the service

·         Host the service in IIS and test it

·         Use SvcUtil command to generate proxy code and client configurations

·         Develop the client

·         Test the application

As you see, hosting my application in IIS and using SvcUtil saves me from some further steps such as writing code for starting and stopping the service, creating the proxy class manually and configuring the client manually.  So far in many cases I have used IIS hosting and SvcUtil; you should get the same experience, but do not forget that things are not as easy as you see here.  In next parts I will give an example of a self-hosted service to make you familiar with this type of service.

Develop the Service

I begin with creating a WCF Service Library project and name it AuthorsService (Figure 1).

Figure 1

I rename default Class1 to AuthorsInfo then remove all the code comments that are provided to give some tips and also code templates for developers for easier development.  I only keep references and the AuthorsService namespace without any code inside it.

Now I create an IAuthorsInfo interface for my service contract and use ServiceContract attribute to mark it as my service contract.

Listing 1

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
 
namespace AuthorsService
{
    [ServiceContract()]
    public interface IAuthorsInfo
    {
        
    }
}

My service provides one method which gets a string value (author's name) and returns an integer value (the number of author's articles).  If the author cannot be found, it returns -1 as result.

I add this method to my interface and mark it as operation contract by putting an OperationContract attribute.

Listing 2:

[ServiceContract()]
public interface IAuthorsInfo
{
    [OperationContract]
    int GetArticleCount(string authorName);
}

Now I create a class (AuthorsInfo) and implement this interface.

Listing 3:

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
 
namespace AuthorsService
{
    [ServiceContract()]
    public interface IAuthorsInfo
    {
        [OperationContract]
        int GetArticleCount(string authorName);
    }
 
    public class AuthorsInfo : IAuthorsInfo
    {
        public int GetArticleCount(string authorName)
        {
            Dictionary<stringint> authors = new Dictionary<stringint>();
            authors.Add("Keyvan Nayyeri", 10);
            authors.Add("Steven Smith", 29);
            authors.Add("Mohammad Azam", 40);
            authors.Add("Bilal Haidar", 15);
 
            if (authors.ContainsKey(authorName))
            {
                return authors[authorName];
            }
 
            return -1;
        }
    }
}

I do not need any data contract because I have not used simple types as parameters and return types for my service. So here my coding is finished for this service.

I compile this to an assembly to put it on IIS.  Note that I could use code file directly and put it on server without using an assembly, but here I want to write a neat service.

Configure the Service

Choosing the appropriate binding for the service is an important thing.  However, in this example we are not dealing with a complicated example because we do not need any special message formatting, encoding, transport or security mechanism. Therefore, I choose BasicHttpBinding as the simplest binding and this is sufficient for our example.

On the other hand, I add MexHttpBinding and auto discovery behaviors for my service to generate my proxy with SvcUtil.  My final configuration file is simple and you can see it in Listing 4.

Listing 4

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="AuthorsService.AuthorsInfo"
               behaviorConfiguration="metadataSupport">
        <endpoint contract="AuthorsService.IAuthorsInfo"
                  binding="basicHttpBinding"/>
        <endpoint address="mex"
           binding="mexHttpBinding"
           contract="IMetadataExchange"/>
      </service>
    </services>
 
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataSupport">
          <serviceMetadata />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Host the Service

As I stated before, I want to host my service on IIS.  To do this, create a new virtual directory (named AuthorsService) and enable anonymous access for it. Then create a "bin" folder and copy my service assembly in it.  I also need to copy Web.Config file to its root.

For services hosted on IIS I must add a .svc file to define my service.  Later I will use the address of this file to generate my proxy with SvcUtil.

This file allows me to define my services on IIS.  I can copy my source code file and put it on the server then choose appropriate attributes to set my service up and also I can use some attributes to use my assembly.  You know that I preferred the second approach for this example so my code for Service.svc file looks like Listing 5.

Listing 5

<%@ServiceHost language="c#" Debug="true" Service="AuthorsService.AuthorsInfo" %>
<%@Assembly Name="AuthorsService" %>

ServiceHost is a directive that lets you declare my service class and Assembly lets you give an assembly name to look for your service class in this assembly.

Now if I copy my service address (http://localhost/authorsservice/service.svc) to my browser window then I should be able to view it without getting any error.  If you got an error, check all steps again and make sure your IIS configurations are correct.  If your error is a .NET error then it should have enough description about the reason for the error.

Generate Proxy Code

The easiest step is here when I use SvcUtil.exe from command line to generate a class file (as proxy) and a configuration file to use them in my client application (Listing 6).

Listing 6

svcutil http://localhost/authorsservice/service.svc /out:proxy.cs

If you do all the preceding steps correctly then this command should generate two files for you in destination path named proxy.cs and output.config (Figure 2).

Figure 2

Develop the Client

Alright, now we have a service, proxy code class and client configuration so it will not be so hard to develop our client.

I create a new Windows Console Application (named AuthorsClient), add a reference to System.ServiceModel and copy proxy code and client configuration files generated from the previous step (proxy.cs and output.config) to this solution.  Before writing my client code, I renamed output.config to App.config to make it my application's configuration file.

Listing 7 shows the code logic for the client.  The only point that I should mention here is about AuthorsInfoClient which does the job for us.  This class is available in proxy.cs and is generated by SvcUtil.  I use a using{} block to create and destroy an instance of this proxy class and get access to service methods.

Listing 7

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
 
namespace AuthorsClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "ASP Alliance Authors Info";
 
            Console.WriteLine("Enter an author's name:");
            string authorName = Console.ReadLine();
 
            using (AuthorsInfoClient client = new AuthorsInfoClient())
            {
                int articleCount = client.GetArticleCount(authorName);
 
                if (articleCount != -1)
                    Console.WriteLine(string.Format("{0} has {1} articles published.",
                        authorName, articleCount));
                else
                    Console.WriteLine("We don't have any author with this name!");
 
                client.Close();
            }
 
            Console.WriteLine("Press any key to continue ...");
            Console.ReadLine();
        }
    }
}

Test

Alright, now we can test out client to see if it works.  I give my name (Keyvan Nayyeri) as the input value to the application and get my articles count.

Figure 3

And it works as expected!

Download

[Download Sample]

Source code for service and client applications that I described as a case study in this article is available.  Other Service files are added to the service project as well.

Summary

In this article we finally started coding with Windows Communication Foundation.  The third part of my tutorial was about development process and programming model in WCF and gave a simple example at the end.  As you saw, writing a WCF application in its simplest form needs a multi-step and long process, but thankfully it is not a complicated process.  To understand it, I can say that this article took more time than all my previous articles on ASPAlliance, but it was straightforward.

Keep your eyes on ASPAlliance to see the next parts on detailed descriptions over each fundamental concept in WCF in near future.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 4:38:50 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search