Start Development with Windows Communication Foundation
page 4 of 6
by Keyvan Nayyeri
Feedback
Average Rating: 
Views (Total / Last 10 Days): 33883/ 39

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!


View Entire Article

User Comments

Title: Good Article for all   
Name: Balu
Date: 2010-12-14 7:31:21 AM
Comment:
Hi,

This article is very clear in concepts and implementations. This can be easily understandable for beginners also.

Very useful!

Thanks
Title: Thank You   
Name: Safiya P
Date: 2010-08-12 8:23:13 AM
Comment:
Keep posting arcles like this on new technologies. As a beginer, your articles really helped me to get the foundation. Thank You.
Title: Very useful for beginners   
Name: Elizabeth
Date: 2010-08-06 4:57:10 AM
Comment:
Thank you so much....
Title: Very useful   
Name: sudheer
Date: 2010-04-01 4:41:31 AM
Comment:
thnks a lot was very useful
Title: Very Useful article especially to the beginner   
Name: kurt
Date: 2009-11-09 2:01:20 AM
Comment:
Very Useful article especially to the beginner
Title: Very Very Good   
Name: Pankaj Lahoti
Date: 2008-08-07 5:02:54 AM
Comment:
Hai (all wcf),
Its very Clear and Understandable Steps.
hopefully find more Article near Future...10x in adv
Title: start WCF   
Name: Adrian
Date: 2008-03-27 3:19:10 PM
Comment:
very clear, thanks

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


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