Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WCF: Quick Tour

3.78/5 (22 votes)
20 Jul 2008CPOL3 min read 1   252  
Illustrating in brief how to make a small and complete application with WCF
BankSystem

Introduction

I'll talk today about new Technology called WCF, i.e. “Windows Communication Foundation”. Before going into detail, let’s define our problem. We have multiple programs (server and clients) which need communication in order to accomplish their target.

For example, if we need to make a chatting system, we can implement it in the client server way. The server will be responsible for taking requests from the chat clients (such as login request, send message request, logout request, … ) and clients will be considered a thin client because most of the operations are done in the server. This is a popular example in which we need a communication framework.

Another example is in making programs that need heavy processing. We recommend putting a server application on a powerful machine and any simple client application on a simple machine, e.g. a laptop. A small PC can connect to the server and make use of it.

This was just an introduction by illustrating in what situations we need this technology. Let’s see what the current possibilities are, i.e. the technologies we have to make it.

Background

The most popular technologies are: COM, COM+, CORBA and WCF. COM and COM+ are implemented using C++ language but it’s considered very difficult due to using pointers which are considered to be difficult for many developers. For CORBA, it’s implemented in Java, I used it and I think it’s easy and has an important feature which is cross platform. I'll try to post an article of how to use it later.

Using the Code

I'll take you through a small application (client and server) implemented by WCF and C#. The purpose of this application is to simulate a very small bank system as follows:

The server will have to provide these functionalities:

  • AddAccount 
  • RemoveAccount 
  • GetAccounts

The client will be responsible for calling the previous functionalities from the server. So here are our steps.

Server Side

  1. Create a new Console Application in C# language and add System.ServiceModel.dll to its references by navigating to this path “c:\windows\Microsoft.Net\Framework\v3.0\Windows Communication Foundation” and select system.servicemodel.dll.

  2. Create our contract: The contract is an interface that contains the functionalities that the server will implement some day :D. We can define it as follows: add a new class to your application and paste this code in it:

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    
    namespace BankServer
    {
        [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
        public interface IBank
        {
            [OperationContract]
            int AddAccount(string clientName, int clientAge);
            [OperationContract]
            bool RemoveAccount(int accountNumber);
            [OperationContract]
            List<String> GetAccounts();
        }
    }
  3. Create our data model i.e., Account class. Add a new class, call it Account and paste this code in it:

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace BankServer
    {
        class Account
        {
            private int _id = 0;
            private string _name = "";
            private int _age = 0;
            public Account(int id, string name, int age)
            {
                _id = id;
                _name = name;
                _age = age;
            }
            public string ClientName
            {
                get { return _name; }
                set { _name = value; }
            }
            public int ClientAge
            {
                get { return _age; }
                set { _age = value; }
            }
            public int ID
            {
                get { return _id; }
                set { _id = value; }
            }
            public override string ToString()
            {
                return String.Format("ID:{0} Name:{1} Age:{2}",
    			_id.ToString(), _name, _age.ToString());
            }
            public override bool Equals(object obj)
            {
                Account temp = (Account)obj;
                return this.ID.Equals(temp.ID);        
    	}  
        }
    }
  4. Implement the Contract: Create a new class called bank and put this code in it:

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace BankServer
    {
        class Bank :IBank
        {
            private List<Account> _accounts = new List<Account>();
            private int _idGenerator = 0;
    
            public int AddAccount(string clientName, int clientAge)
            {
                _idGenerator++;
                Account acc = new Account(_idGenerator, clientName, clientAge);
                _accounts.Add(acc);
                return _idGenerator;
            }
    
            public bool RemoveAccount(int accountNumber)
            {
                Account acc = new Account(accountNumber, "", 0);
                return _accounts.Remove(acc);
            }
    
            public List<string> GetAccounts()
            {
                List<string> accLst = new List<string>();
                foreach (Account acc in _accounts)
                {
                    accLst.Add(acc.ToString());
                }
                return accLst;
            }
        }
    }
  5. Configure the server: this will specify an address for our service and start it. Copy and paste this code in program.cs:

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    namespace BankServer
    {
        class Program
        {
            static void Main(string[] args)
            {
                Uri baseAddress = new Uri
    		("http://localhost:8000/ServiceModelSamples/Services");
    
                ServiceHost selfHost = new ServiceHost(typeof(Bank), baseAddress);
    
                try
                {
                    //configure the service.
                    selfHost.AddServiceEndpoint(typeof(IBank), 
    				new WSHttpBinding(), "BankService");
    
                    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    selfHost.Description.Behaviors.Add(smb);
    
                    //start the service.
                    selfHost.Open();
                    Console.WriteLine("Our Bank Service is Open now");
                    Console.WriteLine("Press <ENTER> to close it");
                    Console.WriteLine();
                    Console.ReadLine();
    
                    selfHost.Close();
                }
                catch (CommunicationException cs)
                {
                    Console.WriteLine("Exception:{0}", cs.Message);
                    selfHost.Abort();
                }
            }
        }
    }

Client Side

  1. Create your client: right click on your solution and create a new project. Call it MyBankClient and its type is console C# application and don't forget to add System.ServiceModel.dll. You can find it in the recent tab.

  2. Generate a proxy class in your client that you will use to deal with the bankservice:

    • Start your server.
    • Open Visual Studio 2008 Command prompt.
    • Navigate to your client folder.
    • Write this command:

      svcutil.exe /language:cs /out:generatedProxy.cs 
          /config:app.conig http://localhost:8000/ServiceModelSamples/services
    • This will generate two files: a proxy class and a configuration file.
    • Right click on your client project and add existing item, and choose generatedProxy.cs.
  3. Use our bank service. Paste this code in your program.cs:

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    
    namespace MyBankClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                EndpointAddress epAddress = new EndpointAddress
    	    ("http://localhost:8000/ServiceModelSamples/Services/BankService");
                BankClient client = new BankClient(new WSHttpBinding(), epAddress);
    
                Console.WriteLine("Adding John , 20 years");
                client.AddAccount("John", 20);
                Console.WriteLine("Adding Peter , 21 years");
                client.AddAccount("Peter", 21);
                Console.WriteLine("Adding Andrew , 25 years");
                client.AddAccount("Andrew", 25);
                
                DisplayAccounts(client.GetAccounts());            
    
                Console.WriteLine("Removing John");
                client.RemoveAccount(1);
                
                DisplayAccounts(client.GetAccounts());            
    
                client.Close();
    
                Console.WriteLine();
                Console.WriteLine("Press <Enter> to close");
                Console.ReadLine();
            }
    
            private static void DisplayAccounts(string[] accounts)
            {
                Console.WriteLine();
                Console.WriteLine("Current Accounts:");
                foreach (string acc in accounts)
                {
                    Console.WriteLine(acc);
                }
                Console.WriteLine();
            }        
        }
    }

Run the server, then the client, and check the result.

Congratulations, you've created a working WCF application.

Points of Interest

WCF gives you great facility in making communication between applications. You can use it in more complex applications. Use MSDN as it is a great help.

History

  • 20th July, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)