Friday, 30 August 2013

DOTNET WCF BEGINNERS - MANOHAR GOUD TRAINER FACULTY GURU DEVELOPER

WCF - WINDOWS COMMUNICATION FOUNDATION

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using  CF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.

 A few sample scenarios include:
  • A secure service to process business transactions. 

  • A service that supplies current data to others, such as a traffic report or other monitoring service.

  • A chat service that allows two people to communicate or exchange data in real time.

  • A dashboard application that polls one or more services for data and presents it in a logical presentation. 

  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.

  • A Silverlight application to poll a service for the latest data feeds.

While creating such applications was possible prior to the existence of WCF, WCF makes the development of endpoints easier than ever. In summary, WCF is designed to offer a manageable approach to creating Web services and Web service clients.

Features of WCF


  • Service Orientation

    One consequence of using WS standards is that WCF enables you to create service oriented applications. Service-oriented architecture (SOA) is the reliance on Web services to send and receive data. The services have the general advantage of being loosely-coupled instead of hard-coded from one application to another. A loosely-coupled relationship implies that any client created on any platform can connect to any service as long as the essential contracts are met.

  • Interoperability

    WCF implements modern industry standards for Web service interoperability.
  • Multiple Message Patterns

    Messages are exchanged in one of several patterns. The most common pattern is the request/reply pattern, where one endpoint requests data from a second endpoint. The second endpoint replies. There are other patterns such as a one-way message in which a single endpoint sends a message without any expectation of a reply. A more complex pattern is the duplex exchange pattern where two endpoints establish a connection and send data back and forth, similar to an instant messaging program.
  • Service Metadata

    WCF supports publishing service metadata using formats specified in industry standards such as WSDL, XML Schema and WS-Policy. This metadata can be used to automatically generate and configure clients for accessing WCF services. Metadata can be published over HTTP and HTTPS or using the Web Service Metadata Exchange standard.
  • Data Contracts

    Because WCF is built using the .NET Framework, it also includes code-friendly methods of supplying the contracts you want to enforce. One of the universal types of contracts is the data contract. In essence, as you code your service using Visual C# or Visual Basic, the easiest way to handle data is by creating classes that represent a data entity with properties that belong to the data entity. WCF includes a comprehensive system for working with data in this easy manner. Once you have created the classes that represent data, your service automatically generates the metadata that allows clients to comply with the data types you have designed.
  • Security

    Messages can be encrypted to protect privacy and you can require users to authenticate themselves before being allowed to receive messages. Security can be implemented using well-known standards such as SSL or WS-SecureConversation.
  • Multiple Transports and Encodings

    Messages can be sent on any of several built-in transport protocols and encodings. The most common protocol and encoding is to send text encoded SOAP messages using is the HyperText Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively, WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages can be encoded as text or using an optimized binary format. Binary data can be sent efficiently using the MTOM standard. If none of the provided transports or encodings suit your needs you can create your own custom transport or encoding.
  • Reliable and Queued Messages

    WCF supports reliable message exchange using reliable sessions implemented over WS-Reliable Messaging and using MSMQ.
  • Durable Messages

    A durable message is one that is never lost due to a disruption in the communication. The messages in a durable message pattern are always saved to a database. If a disruption occurs, the database allows you to resume the message exchange when the connection is restored. You can also create a durable message using the Windows Workflow Foundation (WF).
  • Transactions

    WCF also supports transactions using one of three transaction models: WS-AtomicTtransactions, the APIs in the System.Transactions namespace, and Microsoft Distributed Transaction Coordinator. 
  • AJAX and REST Support

    REST is an example of an evolving Web 2.0 technology. WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON).
  • Extensibility

    The WCF architecture has a number of extensibility points. If extra capability is required, there are a number of entry points that allow you to customize the behavior of a service.
















Sunday, 25 August 2013

DOTNET WCF BEGGINERS - MANOHAR GOUD TRAINER FACULTY GURU DEVELOPER


WCF FOR BEGGINERS

WCF stands for Windows Communication Foundation, it was first shipped with .NET 3.0 framework along with WPF, Windows CardSpace and WorkFlow Foundation.
From a beginner's perspective, what does actually WCF mean? Let's break the abbreviation into single entities and try to debug. It consists of 3 words, a)Windows b)Communication c)Foundation.
A beginner would glance at the words and would think, well it is something which deals with Windows platform, which is used to communicate and connect applications. Hmm, well he/she ain't wrong on the first strike...
A definition which comes to mind may be summed up as: WCF is a kind of technology, which is used to develop and deploy services on Windows platform. Different books have different set of words to describe WCF, but the gist is almost the same which points to development and deployment of services on Windows Platform.
MSDN says, WCF is a framework to build service-oriented applications. So basically WCF revolves around developing applications which are greatly dependent upon services.

Need For WCF

Next question wobbling the mind would be why WCF, what's the need for it? Well yeah it's the most probable query after a little initial understanding. Prior to WCF, there were a handful of technologies doing tasks of communication between a client and a server, they had their pros and cons. For instance:
  • .ASMX Web Services allowed stuffs to be accessed from any platform.
  • MSMQ allowed queuing of messages, so that communication between a client and server is possible even when the server was disconnected.
  • .NET Remoting service allowed transfer of data between a client and server on Windows OS.
So if a developer had to develop an architecture having all the above functionalities, he had to learn the above technologies, which was a cumbersome task. Hence WCF was introduced by Microsoft to overcome these shortcomings. Basically WCF unified the above technologies into a single programming model for the ease of developing service oriented architecture.
I hope that the readers have got an initial understanding of WCF by now, let's move on.

WCF Architecture

Below is the image of WCF Architecture (courtesy: Google Images) :
WCF has a multi-layered architecture namely Contracts layer, Service Runtime Layer, Messaging Layerand Activation and Hosting Layer. I'll try to explain major architectural stuffs in a simple language.

Contracts Layer

In a layman's terms, a contract may be seen as a kind of agreement between 2 or more parties, over some goods or services. The contract will define what kind of services need to be offered, how they need to be offered, details about the place etc. Similar is the case with WCF Contracts Layer. It's an agreement between 2 machines defining the terms and conditions for the messages to be exchanged. Let's have a look at the individual items of the Contracts Layer.
  • Data Contract: Agreement between a service and a client on the data that has to be exchanged. Also defines what data structures and parameters to be used by services in order to interact with the client.
  • Message Contract: Provides control over the SOAP messages that are produced and consumed by WCF. It also provides direct access to message header & body to alter the SOAP message as per the requirement.Usually developers don't pay much heed to message contracts in normal scenarios, but there arises a need for message contracts and their use when interoperability is important or security needs to be maintained at the message level.
  • Service Contract: Defines the kind of operations supported by the service. It also exposes certain information to the client such as:
  1. Data Types in the message.
  2. Locations of the operations, or where the methods are defined
  3. Protocol information and serialization format
  4. Message exchange patterns(whether the behavior of the message is either one-way, duplex or request/reply type)
  • Policy and Binding: Specify important information such as security, protocol.
Let's switch over to the Service Runtime layer:
Service Runtime layer specifies and manages different behaviors of the service that occur during the service operation. Behaviors of the service or Service Behaviors as they can be fondly called, are basically objects that modify and control the run time characteristics of WCF. Below is a list of Service Behaviors managed by the Service Runtime layer:
  • Throttling Behavior: Determines the number of processed messages, which varies according to the demand of the service.
  • Error Behavior: Specifies what kind of action to be taken when any of the messages give error during runtime.
  • Metadata Behavior: Specifies whether metadata is available across the network.
  • Instance Behavior: Specifies the number of service instances that are available to process a message.
  • Message Inspection: Inspects a message totally or partly during runtime.
  • Transaction Behavior: Enables the transaction operation, which rollbacks the transaction if any process fails during runtime.
  • Dispatch Behavior: Determines the handling and processing of a message.
  • Concurrency Behavior: Specifies whether the messages are processed sequentially or concurrently.
  • Parameter Filtering: Filters the message headers & executes preset actions based on the filter of the message headers.
Let's discuss stuffs about the Messaging Layer:
Messaging Layer is responsible for the pattern of exchanges and its format. It's composed of the following components and channels:
  • WS-Security Channel: Enables message security by implementing the WS-Security specifications. Extensive coverage on WS Security can be found out here: http://msdn.microsoft.com/en-us/library/ms977327.aspx
  • WS Reliable Messaging Channel: Guarantees delivery of messages.
  • Encoders: Provides the number of encoders for messages, such as Binary, XML, Text, MTOM.
  • HTTP Channel: States that HTTP is used to deliver messages.
  • TCP Channel: States that TCP is used to deliver messages.
  • Transaction Flow Channel: Governs transacted message patterns.
  • Named Pipe Channel: Enables Inter Process Communication.
  • MSMQ Channel: Enables services to operate with MSMQ.
Let's move on to Hosting and Application Layer:
This layer provides a number of options in which a service can be activated and hosted. Hosting can be of 2 types: self hosting, hosting on external agents, such as IIS. Various options provided by this layer are as follows:
  • Windows Activation Services: Enables WCF applications to automatically activate, when deployed on a system running WAS.
  • .EXE: WCF services can also be run as executable files.
  • Windows Services: WCF services can also be run as Windows services.
  • COM+: WCF services can also be run as COM+ app.
After a discussion about the architecture, let's move on to the features of WCF, which is an important domain as well.

Features of WCF

Features of WCF can be described as follows:
  • Endpoint Support
  • Improved Transport Layer
  • Queuing Support
  • Improved Transactional process
  • Improved Security
  • Hosting Support on various environments
  • AJAX Integration and JSON Support
Let's start with a brief discussion about each of them
Endpoint Support: An endpoint is basically a resource or an entity in the network to which messages can be sent. Endpoints are responsible for the communication between a client and the service. Elements of endpoints are:
  • Addresses to locate the service
  • Bindings to communicate with the service
  • Contracts to specify the functionalities to be performed while communicating with the service.
  • Endpoint behaviors to specify the runtime behavior of the service endpoint.
These Addresses, Bindings and Contracts are normally referred to as ABC's of WCF.
Let's discuss a bit about these ABC's. 

Addresses: In order to send a message to a service, you would need its address. An address in WCF would consist of the following items:
  • Scheme: Basically the transport protocol used.
  • Machine: Full Domain Name of the machine.
  • Port: Defines the port number where the service is running.
  • Path: Path of the service.
Example can be written as:
  • scheme://domain_name:port/path
  • http://localhost:8080/services/MyFirstService
In the above example, a service is locally hosted with HTTP being the transport protocol and 8080 being the port used, path being services/MyFirstService.
Bindings: Facilitate the communication between the client and the service. Specify the communication protocol used to access the service. Below is the list of pre-defined binding elements: 
  • basicHttpBinding
  • wsHttpBinding
  • wsDualHttpBinding
  • wsFederationHttpBinding
  • netTcpBinding
  • netNamedPipeBinding
  • netMsmqBinding
  • msmqIntegrationBinding
  • netPeerTcpBinding
Well I would discuss a little about one of the bindings and details on the use and implementation of others can be searched easily on MSDN and even on CP...
basicHttpBinding: This type of binding is used by the WCF services to configure and expose those end points that are able to communicate with .ASMX Web Services and clients. Transport protocol used is HTTP, while message encoder used is Text/XML. Security is disabled by default in this, to enable the securityBasicHttpSecurityMode needs to be configured. Have a look at the below code on how to configure the host of the basicHttpBinding.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="MyFirstService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/MyFirstservice"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="MyFirstService">
        </endpoint>
      </service>
    </services>
  </system.serviceModel>
</configuration>
Let's discuss about Contracts as in C of ABC's of WCF:
Contracts: Agreements between the client and services. 3 basic contracts are:
  • Service Contracts: Defines the methods of the service.
  • Data Contract: Defines the data types used by the service methods.
  • Message Contract: Ability to control the message headers during the creation of the message.
The second feature of WCF is Improved Transport Layer: Unlike .ASMX web services, WCF services use a numerous protocols for communication between a client and the service. It uses HTTP, TCP, HTTPS, Named pipes. Hence, improved transport facility.
Queuing Support: WCF supports queuing, which allows messages to be stored in a queue and then sent in a timely manner, thus giving a consistent state of communication.
Improved Transactional Support: WCF incorporates improved transactional support, which says if any process fails during service runtime, the transaction doesn't commit, it rollbacks.
Improved Security: Authentication plays a big role in WCF, also WCF ensures that during transit, order of the messages ain't altered.
Hosting support on various environments: WCF allows hosting of services in a number of environments, such as Windows NT Services, Windows Forms, Console Apps, IIS, Windows Activation Services(WAS). IIS provides added advantages such as automatic start and stopping of the service.
AJAX Integration and JSON Support: WCF supports ASP.NET AJAX and JSON data format, which allows WCF services to expose operations to AJAX clients. JSON is a data format used to carry data exchange between AJAX enabled services and their clients. Let's start with the coding part now.

Background

There ain't any pre-requisites as such, just the presence of Visual Studio 2008 client is enough.

Using the Code

We will first code a simple WCF service and test it via inbuilt WCF test client.
  1. Open Visual Studio 2008 and click on File> New> Project.
  2. Create a new Blank Solution to start with.We will add projects later in the next step.

    Give the name of the solution as MyFirstServiceSolution and the location where you want to store the codes.
  3. A solution will be created by VS, then right-click the solution explorer Add> New project.
  4. After clicking on Add>New project, a dialog box will open with few options. Select WCF service library, provide the name as MyServiceLibrary, location as desired and click on OK.
  5. A new WCF service library will be added to the solution, which will have 2 default class files namely,Service1.cs and IService1.cs, providing default implementation of the WCF Service library. Since we will configure the library on our own, so delete both these class files.
  6. Now, right click the WCF service library and add a new class file, name it as MyService.cs
  7. Open MyService.cs, initially it will just have a class called MyService. We need to define what kind of data the service needs to expose. Primitive datatypes such as int, string, float don't need to be exposed as data contract, they are pretty much understood by the .NET engine, whereas user defined data types such as class, enumerations need to be exposed as data contracts. Hence define a class called as Maths and define 2 properties over there.Individual members of the Data contract class need to be exposed as data members. The namespaceSystem.Runtime.Serialization needs to be added for data contract to come alive.Then, we will have to define our service contract, which ensures what operations are exposed by the service. Add an interface, call it as IMaths and add individual methods inside it which will accept the Data contract class as argument to work upon. Service contract will come alive via inclusion of System.ServiceModelnamespace. Next comes the actual implementation of the service, extend the MyService class to implement the interface and its operations. Define the functionalities of the operations as you desire. In the below code, normal arithmetic operations are defined in the MyService class. Build the solution, it should compile without any error.
using System;
<pre>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace MyServiceLibrary
{
    [DataContract]
    public class Maths
    {
       
        [DataMember]
        public int Number1 { get; set; }
        [DataMember]
        public int Number2 { get; set; }
    }
    [ServiceContract]
    public interface IMaths
    {
        [OperationContract]
         int Addition(Maths obj1);
        [OperationContract]
         int Subtraction(Maths obj2);
        [OperationContract]
         int Multiplication(Maths obj3);
        [OperationContract]
         int Division(Maths obj4);
    }
    class MyService:IMaths
    {
        #region IMaths Members
        public int Addition(Maths obj1)
        {
            return (obj1.Number1 + obj1.Number2);
        }
        public int Subtraction(Maths obj2)
        {
            return (obj2.Number1 - obj2.Number2);
        }
        public int Multiplication(Maths obj3)
        {
            return (obj3.Number1 * obj3.Number2);
        }
        public int Division(Maths obj4)
        {
            return (obj4.Number1 / obj4.Number2);
        }
        #endregion
    }
}
  1. Next, we need to configure the App.Config file. First of all, we need to change the service name to point to MyServiceLibrary.MyService, intially it would have pointed to MyServiceLibrary.Service1, but since we have deleted Service1.cs and have included MyService.cs, we need to alter the service node in the config file.
  2. Next we need to configure the endpoints. Change the contract name to point toMyServiceLibrary.IMaths. Here, I have configured 2 different endpoints to make the service talk via 2 means. Have used wsHttpbinding and basicHttpBinding. Have changed the base address to a simpler path.
  3. Well, when you try to debug the WCF service after making all the changes, it might give you an Access Denied exception as below, saying the base address can not be reached. Debug your WCF service in Administrator mode, then it will work.
  4. Let's now debug the service and see how it works. press F5, then a WCF test client will be launched as below. The .NET engine looks for the base address and pings it to get the metadata of the service and eventually gives us all the operations which were exposed by the service.
  5. It shows the same operations twice, coz we have added 2 different bindings to use. Double click any of the operations and then you can give the values of the parameters and invoke the service. The service in turn will return the response. Let's invoke the Addition operation as below:
  6. Give some random values and click on Invoke button, the service will return a response based upon the functionality of the operation as below:
In the above example, we saw the creation of a WCF service library from scratch, which involves creating just a single class and implementing everything in that, though it's not actually mandatory to implement everything in the same class.It was just for demonstration.
Next we will see how to call and consume a WCF service from a client. Let's start.
  1. Open your Visual Studio once again and click on New>WebSite as below.
  2. A dialog box will open, select WCF service, give the location where you want to store it.
  3. The template will add up a WCF service project in the solution, having 2 class files IService.cs, Service.cs and a Service.svc file.
  4. Service.svc file is helpful when we want to host the service within the IIS. Service.cs and IService.csclasses will provide some default implementation of the service. For the time being, leave them as it is. Build the solution, set the Service.svc file as Start Page and debug it. You will see that the ASP.NET Development server browses over to a URL and sends back a Service implementation something like below. It implies that the service has been created and is up and running.
  5. On clicking the URL inside the page, you'll be redirected to the Web Services Description Language(WSDL) page:
  6. Let's view the skeleton of the Service.svc file:
    <%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>
    The element Service shown as bold in the above piece of code refers to the Service class present intheService.cs file, which is further stored under App_Code folder.
    Above was just an intro to the WCF service and its features, let's start to code a WCF service and try to consume it in a console application.
  7. Rename the IService.cs, Service.cs files to something appropriate like IMathService.cs andMathService.cs. Accordingly you'll have to alter the names within the Service.svc and web.config file. Have a look at the below code for IMathService.cs:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.

[ServiceContract]

public interface IMathService

{

[OperationContract]

int Addition(Math obj1);

[OperationContract]

int Subtraction(Math obj2);

// TODO: Add your service operations here

}

// Use a data contract as illustrated in the sample below to add composite types to service operations.

[DataContract]

public class Math

{

int number1, number2;

[DataMember]

public int Number1

{

get { return number1; }

set { number1 = value; }

}

[DataMember]

public int Number2

{

get { return number2; }

set { number2 = value; }

}

}
Here in the code, we have a class as Math which is a DataContract since it acts as a user-defined data type. It has 2 members and 2 properties defining the numbers. Then we have a ServiceContract called asIMathInterface which exposes 2 operations to the client.
  1. Have a look at the MathService.cs file:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.

public class MathService : IMathService

{

#region IMathService Members

public int Addition(Math obj1)

{

return (obj1.Number1 + obj1.Number2);

}

public int Subtraction(Math obj2)

{

return (obj2.Number1 - obj2.Number2);

}

#endregion

}
The MathService class inherits the IMathService interface and provides the implementation of the operations exposed by the service.
  1. Build the solution, set Service.svc as Start Page and debug. It should work without any errors and you'll see the Service page in the browser as below:
    It shows as to how we can use this WCF service in a client application. Let's now try to code a console application to consume this service. Stay Tuned..
  2. Right click on the solution and click on Add>New Project as shown below:
  3. A dialog box will be opened, select Console Application from the list of templates, store this application inside the same solution in which the above service is kept and give a name for the application as DemoClient.
  4. A Console Application project will be added to the solution, now we need to refer the WCF service in this application. Right click on References>Add Service Reference.
  5. This will open a Add Service Reference window. We need to search the WCF service to add, give its URL in the Address textbox and hit Go. The service will be evident and its services and operations will be listed.
    Give the namespace as localhost, since it is the domain name(providing domain name is the convention) and hit OK. The service reference will be added to the Console Application project.
    Now open the program.cs file of the Console app and start coding as shown below:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace DemoClient

{

class Program

{

static void Main(string[] args)

{

localhost.MathServiceClient obj = new DemoClient.localhost.MathServiceClient();

localhost.Math mathobj = new DemoClient.localhost.Math();

mathobj.Number1 = 10;

mathobj.Number2 = 5;

Console.WriteLine("Addition continues..");

Console.WriteLine(obj.Addition(mathobj));

Console.WriteLine("Subtraction continues..");

Console.WriteLine(obj.Subtraction(mathobj));

Console.ReadLine();

}

}

}
I will explain the above code. We haven't done anything special, we have just created an object of the MathService client as obj and have tried to access the operations which were exposed in the WCF service. Since the operations of the WCF service accept an argument of type Math class, we have to make an object of the Math class, shown above as mathobj. This mathobj will be able to access the properties of the Mathclass. Then we have given some values to the properties and have just called the individual operationsAddition() and Subtraction() as exposed by the WCF service.
  1. Now, we need to debug our console application to see whether the implementation is successful or not. Well, right-click on the console app name in the solution and set as 'Startup Project'.
  2. Now debug the application and if everything's correct, then the console app would work without any errors, shown as below:
    Hence, we have been pretty successful in creating a WCF service and consuming it via a client, a console application in this case.I want to emphasize as to what happens when a service reference is added to an application, what's the internal mechanism and stuffs. Let's see.
  3. Click on localhost service under service references and click on 'Show All Files'.
  4. A list of files will be evident as shown below:
  5. Click on Reference.cs under Reference.svcmap classification, which will contain the mappings, serialization and proxy class stuffs. For ex: In the below image we can see that a partial class named as Math has been created, in which the DataMembers are serialized, it implies that the user-defined data type, Math class in our WCF service is serialized when the service is consumed by a client and then it's referenced.
  6. Have a glance at the below image too, implementation of the operations has been created, which means that we will have to code the same way if we have to consume these operations in our client application. Also, we can see that a proxy class named as MathServiceClient has been created, we just need to instantiate the proxy class in our main method and then we're good enough to use the operations which have been exposed by the WCF service.
Gist is that, when we add a service reference to a client application, Visual Studio looks at the WSDL file of the service, downloads it and prepares similar methods and functions inside Reference.cs file. Post that we just need to refer these methods and functions in our main application.
I guess I have reached the end of the article for now. I have discussed: 
  • What is WCF, its architecture, its features, uses.
  • How to create a WCF Service Library and test it via WCF Test Client, from scratch.
  • How to create a WCF Service and consume it in a client application.


DOTNET WCF UNDERSTANDING - MANOHAR GOUD FACULTY, TRAINER, GURU, DEVELOPER



Windows Communication Foundation (WCF) comes to the rescue when we find ourselves not able to achieve what we want to achieve using web services, i.e., other protocols support and even duplex communication. With WCF, we can define our service once and then configure it in such a way that it can be used via HTTP, TCP, IPC, and even Message Queues. We can consume Web Services using server side scripts (ASP.NET), JavaScript Object Notations (JSON), and even REST (Representational State Transfer).
The following table illustrates the differences between a web service and a WCF service:
Web ServiceWCF Service
Communication can happen over HTTP onlyCommunication can happen over HTTP, TCP, IPC, or even MSMQ.
Only simplex and request-response communication is possibleIt can be configured to have simplex, request-response, or even full duplex communication.
They work in an stateless fashion over HTTP and are hosted inside a web server like IISThese can be hosted in many ways inside IIS, inside a Windows service, or even self hosted.
Note: Apart from these differences, there are other differences related to instance management, sessions, and data representation and serialization.


A WCF service can be visualized as:
wcf artcile image

Understanding the basics

When we say that a WCF service can be used to communicate using different protocols and from different kinds of applications, we will need to understand how we can achieve this. If we want to use a WCF service from an application, then we have three major questions:
  1. Where is the WCF service located from a client's perspective?
  2. How can a client access the service, i.e., protocols and message formats?
  3. What is the functionality that a service is providing to the clients?
Once we have the answer to these three questions, then creating and consuming the WCF service will be a lot easier for us. The WCF service has the concept of endpoints. A WCF service provides endpoints which client applications can use to communicate with the WCF service. The answer to these above questions is what is known as the ABC of WCF services and in fact are the main components of a WCF service. So let's tackle each question one by one.
Address: Like a webservice, a WCF service also provides a URI which can be used by clients to get to the WCF service. This URI is called as the Address of the WCF service. This will solve the first problem of "where to locate the WCF service?" for us.
Binding: Once we are able to locate the WCF service, we should think about how to communicate with the service (protocol wise). The binding is what defines how the WCF service handles the communication. It could also define other communication parameters like message encoding, etc. This will solve the second problem of "how to communicate with the WCF service?" for us.
Contract: Now the only question we are left up with is about the functionalities that a WCF service provides. Contract is what defines the public data and interfaces that WCF service provides to the clients.

Using the code

As an ASP.NET developer, we will find ourselves in the need of using a WCF service or perhaps write a WCF service. What we will do next is to implement a small WCF service and see how the ABC of WCF is to be implemented. We will then write a small application to consume this WCF service.
The service that we will create will provide arithmetic operations on a Pair data type. This Pair type will also be exposed by our service to the applications. We will simply provide addition and subtraction functionality for the Pair data type.
Note: We will host this WCF service inside an ASP.NET website, i.e., IIS hosting, and will be consuming it from an ASP.NET website. So let us create an empty ASP.NET website and then add a WCF service to it.
wcf artcile image

Creating a WCF Service

Let us start by looking at the Contract part of the WCF service. We need to expose a Pair data type from our service so this class will have to be decorated with the DataContract attribute. This attribute specifies that this data type can be used by consumers of this WCF service. Also, the public properties of this class will have to be decorated with the DataMember attribute to specify that clients can use these properties and to indicate that they will be needing serialization and deserialization.
[DataContract]
public class Pair
{
int m_first;
int m_second;
public Pair()
{
m_first = 0;
m_second = 0;
}
public Pair(int first, int second)
{
m_first = first;
m_second = second; }
[DataMember]
public int First
{
get { return m_first; }
set { m_first = value; }
}
aMember]
[Da
tpublic int Second
{
get { return m_second; }
set { m_second = value; }
}
}
Now we have specified the Data contract that our service is exposing. The next thing is to specify the service contracts and major operations of this service. Let us create an interface that will list the major functionalities provided by this service. We will then have to decorate this interface with the ServiceContract attribute to specify that this interface is being exposed by this service and can be used by the clients.
We will then have to write methods for all major operations provided by this service and decorate them with the OperationContract attribute to specify that these operations of this interface can be used by the clients.
public interface IPairArihmeticService
{
[OperationContract]
Pair Add(Pair p1, Pair p2);
[OperationContract]
, Pair p2); }
Pair Subtract(Pair p
1
Now we have specified all the DataContract, ServiceContract, and the OperationContract of our small service. Now the major thing left in this service is to implement the functionalities. To do that, let's have a small class that will implement the interface we just created.
public class PairArihmeticService : IPairArihmeticService
{
Pair IPairArihmeticService.Add(Pair p1, Pair p2)
{
Pair result = new Pair();
result.First = p1.First + p2.First;
result.Second = p1.Second + p2.Second;
return result;
}
IPairArihmeticService.Subtract(Pair p1, Pair p2) {
Pai
r Pair result = new Pair();
result.First = p1.First - p2.First;
result.Second = p1.Second - p2.Second;
return result;
}
}
Let us try to visualize what we have done so far. This class diagram will show the classes we created so far and decorated them with attributes to specify the data contract, service contract, and operation contracts.
wcf artcile image
We have our Contract part declared and defined. Now let us see how we can configure the other things. We need to make this service visible to the client applications and let the client applications extract the meta data information out of this service. To do this we need to specify the service behavior in the web.config.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
The important thing to notice here is the httpGetEnabled="true" which enables this service to provide its meta data when a client requests for it. Now let us build this website to build our WCF service. Let us set the.SVC file as the start page and run the website to see what happens.
wcf artcile image

Consuming a WCF Service

We have seen how to create a WCF service. Let us now see how we can consume a WCF service. Let us start by adding a default ASP.NET website in the same solution. We then need to add a service reference to the WCF service we just created.
wcf artcile image
Adding this service reference will mainly do two things:
  1. Create the Address and Binding part to access this service in the web.config file.
  2. Create the proxy class for us to access the service.
So let us first look at the Address and Binding in the web.config to complete the ABC part of the WCF service.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IPairArihmeticService"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1062/WcfTestWebSite/PairArihmeticService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IPairArihmeticService"
contract="PairServiceReference.IPairArihmeticService"
name="BasicHttpBinding_IPairArihmeticService"/>
</client>
</system.serviceModel>
This web.config shows the address of the WCF service, the binding to use the webservice, and the contract that is being exposed by this web service. All this was generated by extracting the meta data from the service.
Now let us look at how to use the proxy class that was generated. We will use this proxy class to call the methods of the WCF service and then extract the results out of it.
PairServiceReference.Pair p1 = new PairServiceReference.Pair();
p1.First = Convert.ToInt32(txtP1First.Text);
p1.Second = Convert.ToInt32(txtp1Second.Text);
airServiceReference.Pair p2 = new PairServiceReference.Pair();
P
2.First = Convert.ToInt32(txtP2First.Text);
pp2.Second = Convert.ToInt32(txtp2Second.Text);
airServiceReference.PairArihmeticServiceClient pairServiceClient =
P new PairServiceReference.PairArihmeticServiceClient();
PairServiceReference.Pair addResult = pairServiceClient.Add(p1, p2);
airServiceReference.Pair minusResult = pairServiceClient.Subtract(p1, p2);
P
lsum.Text = addResult.First.ToString() + ", " + addResult.Second.ToString();
l b
blminus.Text = minusResult.First.ToString() + ", " + minusResult.Second.ToString();
l
Note: The above code snippet refers to control IDs. Please see the source code for that.
Now we have successfully consumed the WCF service from our ASP.NET website. Before we wrap up, let us now build this web site and see the results.
wcf artcile image

Note: While using the source code, the service reference will have to be updated to added again as the address of the service that was being used was specific to my system. It could differ on other systems.