Dec 08

WCF Beginners – Step by step WCF approach

WCF stands for Windows Communication Foundation. It is a framework for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments. WCF used to send messages between client and service, these messages can be sent over intranet or the internet using common transport protocols such as TCP or HTTP.

This post is intended to give you quick exposure to Windows Communication Foundation programming experience. This post helps you to understand the steps involved to create WCF service and client application.

A service exposes one or more endpoints which contains one or more service operations. The endpoint of service specifies and address where service can be found, binding contains the information that describes how a client must communicate with the service and contract defines the functionality provided by the service to its clients.

 To create any WCF service we need to do following things,

  1. Create visual studio project structure
  2. Add WCF Service
  3. Define Data Contract 
  4. Create Business Layer
  5. Define Service Contract
  6. Implement Service Contract
  7. Creating and consuming Service from Console based Client application
  8. Test it

So let’s start with step by step approach to create WCF service. I hope you must have Visual Studio installed on your machine, Here I have used Visual Studio 2017 Community Edition to build WCF service and its console based client.

Step 1: Open Visual Studio and create project structure 

Create visual studio solution WcfBasics.sol

Create Solution

Create Wcf Service Application i.e. CsharpDocs.WcfApp and remove default services created i.e. Service1.svc

create wcf service application

Add .Net Framework based Console application within above solution i.e. CsharpDocs.Wcf.Client

create client

 

Create sub folders Contracts, Interface and Utils for better understanding (this is not mandatory but good practice)

Step 2: Add WCF Service(.svc) file

Create service file (WeatherForcastService.svc) by right clicking on CsharpDocs.WcfApp project -> select Add New Item -> Web -> WCF Service

add service

Move IWeatherForcastService.cs file to Interface folder and rename it to IWeatherForcast to keep proper naming conventions

That’s it !! your folder structure will look like below

Step 3: Define Data Contract

Create WeatherInfo.cs file inside Contracts folder and add below code. Here the class name is decorated with DataContract attribute and properties are decorated with DataMember attribute. These DataContract (message) is used to pass between client and service.

using System.Runtime.Serialization;

namespace CsharpDocs.WcfApp.Contracts
{
    [DataContract]
    public class WeatherInfo
    {
        [DataMember]
        public string City { get; set; }

        [DataMember]
        public string Tempreture { get; set; }
    }
}
Step 4: Create Business Layer

Create WeatherHelper.cs file inside Utils folder and add below code. I have created two functions to explain concepts. In practical scenario this would be business layer calling data access layer. Do the appropriate changes(separate .dll for Business Layer and Data Access Layer (using EF or ADO.NET)) while accessing SQL/Oracle data access.

using CsharpDocs.WcfApp.Contracts;
using System.Collections.Generic;
using System.Linq;

namespace CsharpDocs.WcfApp.Utils
{
    public class WeatherHelper
    {
        public IEnumerable<WeatherInfo> GetAll()
        {
            return new List
            {
                    new WeatherInfo { City = "Delhi", Tempreture="09" },
                    new WeatherInfo { City = "Mumbai", Tempreture="26"},
                    new WeatherInfo { City = "Kolkata", Tempreture="16"},
                    new WeatherInfo { City = "Pune", Tempreture="17"},
                    new WeatherInfo { City = "Nagpur", Tempreture="13"},
                    new WeatherInfo { City = "Indore", Tempreture="15"},
                    new WeatherInfo { City = "Ahmadabad", Tempreture="20"},
                    new WeatherInfo { City = "Vadodara", Tempreture="20"},
                    new WeatherInfo { City = "Chandigrah", Tempreture="8"},
                    new WeatherInfo { City = "Leh", Tempreture="-13"},
                    new WeatherInfo { City = "Manali", Tempreture="-06"},
                    new WeatherInfo { City = "Jaipur", Tempreture="16"},
                    new WeatherInfo { City = "Hyderabad", Tempreture="18"},
                    new WeatherInfo { City = "Bangalore", Tempreture="18"},
                    new WeatherInfo { City = "Chennai", Tempreture="26"}
                };
        }

        public WeatherInfo GetWeatherInfo(string city)
        {
            var weatherInfos = GetAll();

            return weatherInfos.Where(x => x.City.ToLower() == city.ToLower()).Single();
        }
    }
}
Step 5:  Define Service Contract

Here IWeatherForecast service defines two functionalities i.e. weather information of all major cities and for perticular city exposed by service. Here interface decorated with ServiceContract attribute and the functions exposed by service are decorated with OperationContract attribute.

using CsharpDocs.WcfApp.Contracts;
using System.Collections.Generic;
using System.ServiceModel;

namespace CsharpDocs.WcfApp.Interface
{
    [ServiceContract]
    public interface IWeatherForcast
    {
        [OperationContract]
        IEnumerable<WeatherInfo> GetAll();

        [OperationContract]
        WeatherInfo GetWeatherInfo(string city);
    }
}
Step 6: Implement Service Contract

Here WatherForecastService describes the implementation of service contract. Here I have created instance of business layer (WeatherHelper) and called appropriate function. 

using CsharpDocs.WcfApp.Contracts;
using CsharpDocs.WcfApp.Interface;
using CsharpDocs.WcfApp.Utils;
using System.Collections.Generic;

namespace CsharpDocs.WcfApp
{
    public class WeatherForcastService : IWeatherForcast
    {
        public IEnumerable<WeatherInfo> GetAll()
        {
            var weatherHelper = new WeatherHelper();
            return weatherHelper.GetAll();
        }

        public WeatherInfo GetWeatherInfo(string city)
        {
            var weatherHelper = new WeatherHelper();
            return weatherHelper.GetWeatherInfo(city);
        }
    }
}

Here is the web.config file code of my WCF service




  
    
  
  
    
    
  
  
    
      
        
          
          
          
          
        
      
    
    
        
        
    
  
  
    
    
    
  

Step 7: Creating and consuming Service from Console based Client application

We have already created CsharpDocs.Wcf.Client project. So, first Add Service Reference of WCF service. This web reference will acts as a proxy of service on which we invoke method call.

Right click on Connected Services in CsharpDocs.Wcf.Client project and select Add Service Reference… option

Now click on Discover button which will show you services available. Give the namespace and click Ok button to add service reference

add service reference in client

Replace below code in Program.cs file Here i have added CsharpDocs.Wcf.Client.WeatherForcastService as using statement where WeatherForcastClient resides. This is our proxy class. Create the instance of proxy class and call the appropriate function on it.

using CsharpDocs.Wcf.Client.WeatherForcastService;
using System;

namespace CsharpDocs.Wcf.Client
{
    public class Program
    {
        static void Main(string[] args)
        {
            GetAll();
            Console.Write("\n\n\n----------------------------------------------------\n\n\n");
            GetWeatherInfo();
            Console.ReadKey();
        }

        private static void GetAll()
        {
            var weatherForcastClient = new WeatherForcastClient();
            var cityWathers = weatherForcastClient.GetAll();

            Console.Write("Weather of major cities in india on 3rd Dec 2017 \n\n");
            Console.Write(string.Format("City                 Tempreture(in degree celcius)\n"));
            foreach (var weather in cityWathers)
            {
                Console.Write(string.Format("{0}                 {1}\n", weather.City, weather.Tempreture));
            }
        }

        private static void GetWeatherInfo()
        {
            var weatherForcastClient = new WeatherForcastClient();
            var cityWather = weatherForcastClient.GetWeatherInfo("Pune");

            Console.Write("Weather of Pune on 3rd Dec 2017 \n");
            Console.Write(string.Format("{0} degree celcius", cityWather.Tempreture));
        }
    }
}

Once you add the service reference in client application it aromatically creates endpoint and address in app.config file as below


Step 8: Lets test it

I hope you enjoyed this article. Please don’t forget to like, comment, share and subscribe to this post. 

Leave a Reply