Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Thursday, August 16, 2012

Windows Activation Service

Windows Activation service is a system service available with Windows vista and windows server 2008. It is available with IIS 7.0 and it is more powerful compared to IIS 6.0 because it supports Http, TCP and named pipes were IIS 6.0 supports only Http. It can be installed and configured separately.
Hosting WCF in Activation service takes many advantages such as process recycling, isolation, idle time management and common configuration system. WAS hosted service can be created using following steps
  1. Enable WCF for non-http protocols
  2. Create WAS hosted service
  3. Enable different binding to the hosted service

Enable WCF for non-http protocols

Before Start creating the service we need to configure the system to support WAS. Following are the step to configure WAS.
  1. Click Start -> Control Panel -> programs and Features and click 'Turn Windows Components On or Off' in left pane.
  2. Expand 'Microsoft .Net Framework 3.0' and enable "Windows Communication Foundation HTTP Activation" and "Windows Communication Foundation Non- HTTP Activation".
  3. Next we need to add Binding to the Default Web site. As an example, we will bind the default web site to the TCP protocol. Go to the Start menu -> Programs ->Accessories. Right click on the "Command Prompt" item, and select "Run as administrator" from the context menu.
  4. Execute the following command
  5. C:\Windows\system32\inetsrv> appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.tcp',
  6. bindingInformation='808:*']




  • That command adds the net.tcp site binding to the default web site by modifying the applicationHost.config file located in the "C:\Windows\system32\inetsrv\config" directory. Similarly we can add different protocols to the Default Web site.
  • Create WAS hosted service

    Step 1: Next we are going to create the service, Open the Visual Studio 2008 and click New->WebSite and select WCF Service from the template and Location as HTTP as shown below.
    Step 2: Create the Contract by creating interface IMathService and add ServiceContract attribute to the interface and add OperationContract attribute to the method declaration.
    IMathService.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    
     [ServiceContract]
    public interface IMathService
    {
    
        [OperationContract]
        int Add(int num1, int num2);
    
        [OperationContract]
        int Subtract(int num1, int num2);
    
    }
    Step 3: Implementation of the IMathService interface is shown below.
    MathService.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    
    public class MathService : IMathService
    {
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }
    
        public int Subtract(int num1, int num2)
        {
            return num1 - num2;
        }
    }
    Step 4: Service file is shown below.
    MathService.svc
    <%@ ServiceHost Language="C#" Debug="true" Service="MathService" 
    CodeBehind="~/App_Code/MathService.cs" %>
    Step 5: In web.Config file, create end point with 'netTcpBinding' binding and service metadata will be published using Metadata Exchange point. So create the Metada Exchange end point with address as 'mex' and binding as 'mexTcpBinding'. Without publishing the service Metadata we cannot create the proxy using net.tcp address (e.g svcutil.exe net.tcp://localhost/WASHostedService/MathService.svc )
    Web.Config
    <system.serviceModel>
    <services>
     <service name="MathService" behaviorConfiguration="ServiceBehavior">
     <!-- Service Endpoints -->
     <endpoint binding="netTcpBinding" 
     contract="IMathService" >
     </endpoint>
      <endpoint address="mex" 
      binding="mexTcpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
    <serviceBehaviors>
    <behavior name="ServiceBehavior">
    <!-- To avoid disclosing metadata information, set the value below 
    to false and remove the metadata endpoint above before deployment -->
     <serviceMetadata httpGetEnabled="true"/>
     <!-- To receive exception details in
      faults for debugging purposes, set the value below to true. 
       Set to false before deployment to avoid disclosing 
       exception information -->
     <serviceDebug includeExceptionDetailInFaults="false"/>
     </behavior>
    </serviceBehaviors></behaviors>
    </system.serviceModel>

    Enable different binding to the hosted service

    1. Go to the Start menu -> Programs ->Accessories. Right click on the "Command Prompt" item, and select "Run as administrator" from the context menu.
    2. Execute the following command C:\Windows\system32\inetsrv>appcmd set app "Default Web Site/WASHostedServcie" /enabledProtocols:http,net.tcp
    Output will be shown below.
    Step 6: Now the service is ready to use. Next we can create the proxy class using service uttility and add the proxy class to the client application. Creat the proxy class using Visual Studio Command prompt and execute the command
    svcutil.exe net.tcp://localhost/WASHostedService/MathService.svc Proxy and configuration file are generated in the corresponding location.
    Step 6: Create the client application as shown below and add the reference 'System.ServiceModel', this is the core dll for WCF.
    Step 8: Add the proxy class and configuration file to the client application. Create the object for the MathServiceClient and call the method.
    Program.cs
     class Program
        {
            static void Main(string[] args)
            {
                MathServiceClient client = new MathServiceClient();
                Console.WriteLine("Sum of two number 5,6");
                Console.WriteLine(client.Add(5,6));
                Console.ReadLine();
    
            }
        }
    The output will be shown as below.
    So this tutorial clearly explains about the hosting the WCF in Windows Activation Service. So next we can see how to host the service using Windows Service

    Saturday, August 4, 2012

    Self Hosting

    In web service, we can host the service only in IIS, but WCF provides the user to host the service in any application (e.g. console application, Windows form etc.). Very interestingly developer is responsible for providing and managing the life cycle of the host process. Service can also be in-pro i.e. client and service in the same process. Now let's us create the WCF service which is hosted in Console application. We will also look in to creating proxy using 'ClientBase' abstract class.
    Note: Host process must be running before the client calls the service, which typically means you have to prelaunch it.

    Step 1: First let's start create the Service contract and it implementation. Create a console application and name it as MyCalculatorService. This is simple service which return addition of two numbers.
    Step 2: Add the System.ServiceModel reference to the project.
    Step 3: Create an ISimpleCalculator interface, Add ServiceContract and OperationContract attribute to the class and function as shown below. You will know more information about these contracts in later session. These contracts will expose method to outside world for using this service.
    IMyCalculatorService.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    
    namespace MyCalculatorService
    {
        [ServiceContract()]
        public interface ISimpleCalculator
        {
            [OperationContract()]
            int Add(int num1, int num2);
        }
    
    }
    Step 4: MyCalculatorService is the implementation class for IMyCalculatorService interface as shown below.
    MyCalculatorService.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace MyCalculatorService
    {
        class SimpleCalculator : ISimpleCalculator
        {
            public int Add(int num1, int num2)
            {
                return num1 + num2;
            }
    
        }
    }
    Step 5: Now we are ready with service. Let's go for implementing the hosting process. Create a new console application and name it as 'MyCalculatorServiceHost'
    Step 6: ServiceHost is the core class use to host the WCF service. It will accept implemented contract class and base address as contractor parameter. You can register multiple base addresses separated by commas, but address should not use same transport schema.
    Uri httpUrl 
    = new Uri("http://localhost:8090/MyService/SimpleCalculator");
    
    Uri tcpUrl 
    = new Uri("net.tcp://localhost:8090/MyService/SimpleCalculator");
    
    ServiceHost host 
    = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl, tcpUrl);
    Multiple end points can be added to the Service using AddServiceEndpoint() method. Host.Open() will run the service, so that it can be used by any client.
    Step 7: Below code show the implementation of the host process.
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    namespace MyCalculatorServiceHost
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a URI to serve as the base address
                Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
                //Create ServiceHost
                ServiceHost host 
                = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
                //Add a service endpoint
                host.AddServiceEndpoint(typeof(MyCalculatorService.ISimpleCalculator)
                , new WSHttpBinding(), "");
                //Enable metadata exchange
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(smb);
                //Start the Service
                host.Open();
    
                Console.WriteLine("Service is host at " + DateTime.Now.ToString());
                Console.WriteLine("Host is running... Press <Enter> key to stop");
                Console.ReadLine();
    
            }
        }
    }
    
    Step 8: Service is hosted, now we need to implement the proxy class for the client. There are different ways of creating the proxy
    • Using SvcUtil.exe, we can create the proxy class and configuration file with end points.
    • Adding Service reference to the client application.
    • Implementing ClientBase<T> class
    Of these three methods, Implementing ClientBase<T> is the best practice. If you are using rest two method, we need to create proxy class every time when we make changes in Service implementation. But this is not the case for ClientBase<T>. It will create the proxy only at runtime and so it will take care of everything.
    MyCalculatorServiceProxy.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using MyCalculatorService;
    namespace MyCalculatorServiceProxy
    {
        public class MyCalculatorServiceProxy : 
            //WCF create proxy for ISimpleCalculator using ClientBase
            ClientBase<ISimpleCalculator>,
            ISimpleCalculator
        {
            public int Add(int num1, int num2)
            {
                //Call base to do funtion
                return base.Channel.Add(num1, num2);
            }
        }
    }
    Step 9: In the client side, we can create the instance for the proxy class and call the method as shown below. Add proxy assembly as reference to the project.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    
    namespace MyCalculatorServiceClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy ;
                proxy= new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
                Console.WriteLine("Client is running at " + DateTime.Now.ToString());
                Console.WriteLine("Sum of two numbers... 5+5 ="+proxy.Add(5,5));
                Console.ReadLine();
            }
        }
    }
    Step 10 : End point (same as service) information should be added to the configuration file of the client application.
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
        <client>
          <endpoint address ="http://localhost:8090/MyService/SimpleCalculator" 
                    binding ="wsHttpBinding"
                    contract ="MyCalculatorService.ISimpleCalculator">
            
          </endpoint>
        </client>
      </system.serviceModel>
    </configuration>
    
    Step 11: Before running the client application, you need to run the service. Output of the client application is shown below.
    This self host shows advantage such as in-Pro hosting, programmatic access and it can be used when there need singleton service. I hope you have enjoyed the Self hosting session, now let go for hosting using Windows Activation service.

    IIS 5/6 Hosting

    The main advantage of hosting service in IIS is that, it will automatically launch the host process when it gets the first client request. It uses the features of IIS such as process recycling, idle shutdown, process health monitoring and message based activation. The main disadvantage of using IIS is that, it will support only HTTP protocol.
    Let as do some hands on, to create service and host in IIS
    Step 1:Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' and Location as http. This will directly host the service in IIS and click OK.
    Step 2: I have created sample HelloWorld service, which will accept name as input and return with 'Hello' and name. Interface and implementation of the Service is shown below.
    IMyService.cs
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        string HelloWorld(string name);    
    
    }
    MyService.cs
    public class MyService : IMyService
    {
    
        #region IMyService Members
    
        public string HelloWorld(string name)
        {
            return "Hello " + name;
        }
    
        #endregion
    }
    
    Step 3: Service file (.svc) contains name of the service and code behind file name. This file is used to know about the service.
    MyService.svc
    <%@ ServiceHost Language="C#" Debug="true" 
    Service="MyService" CodeBehind="~/App_Code/MyService.cs" %>
    Step 4: Server side configurations are mentioned in the config file. Here I have mention only one end point which is configured to 'wsHttpBinding', we can also have multiple end point with differnet binding. Since we are going to hosted in IIS. We have to use only http binding. We will come to know more on endpoints and its configuration in later tutorial. Web.Config
    <system.serviceModel>
      <services>
       <service behaviorConfiguration="ServiceBehavior" name="MyService">
     <endpoint address="http://localhost/IISHostedService/MyService.svc" 
     binding="wsHttpBinding" contract="IMyService">
     <identity>
     <dns value="localhost"/>
     </identity>
     </endpoint>
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       </service>
     </services>
     <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
     <!-- To avoid disclosing metadata information, 
     set the value below to false and remove the 
     metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
     <!-- To receive exception details in faults for 
     debugging purposes, set the value below to true.  
     Set to false before deployment to avoid disclosing exception information -->
     <serviceDebug includeExceptionDetailInFaults="false"/>
     </behavior>
       </serviceBehaviors>
      </behaviors>
    </system.serviceModel>
    
    Note: You need to mention the service file name, along with the Address mention in the config file. IIS Screen shot
    This screen will appear when we run the application.

    Step 5: Now we successfully hosted the service in IIS. Next we have to consume this service in client application. Before creating the client application, we need to create the proxy for the service. This proxy is used by the client application, to interact with service. To create the proxy, run the Visual Studio 2008 command prompt. Using service utility we can create the proxy class and its configuration information.
    svcutil  http://localhost/IISHostedService/MyService.svc
    After executing this command we will find two file generated in the default location.
    • MyService.cs - Proxy class for the WCF service
    • output.config - Configuration information about the service.
    Step 6: Now we will start creating the Console application using Visual Studio 2008(Client application).
    Step 7: Add the reference 'System.ServiceModel'; this is the core dll for WCF.
    Step 8: Create the object for the proxy class and call the HelloWorld method.
    static void Main(string[] args)
            {
                //Creating Proxy for the MyService 
                 MyServiceClient client = new MyServiceClient();
                 Console.WriteLine("Client calling the service...");
                 Console.WriteLine(client.HelloWorld("Ram"));
                 Console.Read();
    
            }
    Step 9: If we run the application we will find the output as shown below.
    I hope you have enjoyed the Service hosted in IIS. Now let start the look on the self hosted service.

    WCF Architecture

    The following figure illustrates the major components of WCF.
    Figure 1: WCF Architecture

    Contracts

    Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

    Service contracts

    - Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

    Data contract

    - It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

    Message Contract

    - Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

    Policies and Binding

    - Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

    Service Runtime

    - It contains the behaviors that occur during runtime of service.
    • Throttling Behavior- Controls how many messages are processed.
    • Error Behavior - Specifies what occurs, when internal error occurs on the service.
    • Metadata Behavior - Tells how and whether metadata is available to outside world.
    • Instance Behavior - Specifies how many instance of the service has to be created while running.
    • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
    • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

    Messaging

    - Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
    • Transport Channels Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
    • Protocol Channels Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

    Activation and Hosting

    - Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism
    • IIS Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
    • Windows Activation Service (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
    • Self-Hosting WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
    • Windows Service WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

    WCF Client and Metadata

    WCF Client

    WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services.
    A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps:
    1. Get the Proxy class and service end point information
    2. Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints.
      svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl
    3. Call operations.
    4. Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled.
      //Creating the proxy on client side
      MyCalculatorServiceProxy.MyServiceProxy proxy 
      = new MyCalculatorServiceProxy.MyServiceProxy();
       Console.WriteLine("Counter: " + proxy.MyMethod());
    5. Close the WCF client object.
    6. After using the object created in the above steps, we have to dispose the object. Channel will be closed with the service, when the object is cleared.

    Metadata

    Characteristics of the service are described by the metadata. This metadata can be exposed to the client to understand the communication with service. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file.
    <system.serviceModel>
        <services>
          <service name="MathService"
            behaviorConfiguration="MathServiceBehavior">
            <endpoint address="" contract="IMathService"
              binding="wsHttpBinding"/>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="MathServiceBehavior">
        <serviceMetadata httpGetEnabled="True"/>
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    
    This metadata can be viewed while creating WCF client application using SvcUtil.exe

    Message and Channel

    Message

    WCF Message is the unit of data exchange between client and service. It consists of several parts, including a body and headers.

    WCF Runtime

    WCF runtime is the set of object responsible for sending and receiving message. For example formatting the message, applying security and transmitting and receiving message using various protocol.

    Channels:

    Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

    Transport Channels - Handles sending and receiving message from network. Protocols like HTTP, TCP name pipes and MSMQ.

    Protocol Channels

    - Implements SOAP based protocol by processing and possibly modifying message. e.g. WS-Security and WS-Reliability.

    Contracts and Service Host

    Contracts

    In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF

    Service Contract

    Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.
    To know more on Service contract see Service contract tutorial.

    Data Contract

    Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.
    To know more on DataContract see DataContract tutorial.

    Message Contract

    Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
    To know more on Message Contract see Message contract tutorial.

    Fault Contract

    Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.
    To know more on Fault Contract see Fault Contract tutorial.

    Service Host

    Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHost namespace hold this object. This object is created while self hosting the WCF service.
    In the below example you can find that WCF service is self hosted using console application.
    //Creating uri for the hosting the service
    Uri uri = new Uri("http://localhost/CategoryService");
    //Creating the host object for MathService
      ServiceHost host = new ServiceHost(typeof(CategoryService), uri);
    //Adding endpoint to the Host object
      host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri);
      host.Open(); //Hosting the Service
      Console.WriteLine("Waiting for client invocations");
      Console.ReadLine();
      host.Close();

    Binding and Behavior

    Binding

    Simple definition for Binding describes how the client will communicate with service. We can understand with an example.
    Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.
    <system.serviceModel>
        <services>
          <service name="MathService"
            behaviorConfiguration="MathServiceBehavior">
          <endpoint address="http://localhost:8090/MyService/MathService.svc" 
            contract="IMathService"
              binding="wsHttpBinding"/>
    <endpoint address="net.tcp://localhost:8080/MyService/MathService.svc" 
    contract="IMathService"
              binding="netTcpBinding"/> 
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="MathServiceBehavior">
              <serviceMetadata httpGetEnabled="True"/>
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    
      
    See how simple it is in WCF. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.

    Example:

    In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the servieMetadata node with attribute httGetEnabled='true'. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.
    <system.serviceModel>
        <services>
          <service name="MathService"
            behaviorConfiguration="MathServiceBehavior">
            <endpoint address="" contract="IMathService"
              binding="wsHttpBinding"/>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="MathServiceBehavior">
              <serviceMetadata httpGetEnabled="True"/>
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    
    
      

    Note:

    Application can be controlled either through coding, configuring or through combination of both. Specification mention in the configuration can also be overwritten in code.

    EndPoint

    WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
    All the WCF communications are take place through end point. End point consists of three components.

    Address

    Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
    http://localhost:8090/MyService/SimpleCalculator.svc

    Binding

    Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
    A binding has several characteristics, including the following:
    • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
    • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
    • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
    The following table gives some list of protocols supported by WCF binding.
    Binding Description
    BasicHttpBinding Basic Web service communication. No security by default
    WSHttpBinding Web services with WS-* support. Supports transactions
    WSDualHttpBinding Web services with duplex contract and transaction support
    WSFederationHttpBinding Web services with federated security. Supports transactions
    MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions
    NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions
    NetNamedPipeBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions
    NetPeerTcpBinding Communication between computers across peer-to-peer services. Supports duplex contracts
    NetTcpBinding Communication between WCF applications across computers. Supports duplex contracts and transactions

    Contract

    Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.
    Below figure illustrate the functions of Endpoint

    Example:

    Endpoints will be mentioned in the web.config file on the created service.
    <system.serviceModel>
    <services>
          <service name="MathService"
            behaviorConfiguration="MathServiceBehavior">
           <endpoint
             address="http://localhost:8090/MyService/MathService.svc" contract="IMathService"
              binding="wsHttpBinding"/> 
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="MathServiceBehavior">
              <serviceMetadata httpGetEnabled="True"/>
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
      

    Difference between WCF and Web service

    Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
    Features Web Service WCF
    Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
    Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
    Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
    Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
    XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
    Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
    Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
    Protocols Security Security, Reliable messaging, Transactions

    Development Tools

    WCF application can be developed by the Microsoft Visual Studio. Visual studio is available at different edition. You can use Visual Studio 2008 Expression edition for the development.
    Visual Studio 2008 SDK 1.1

    Microsoft Visual Studio 2008

    Microsoft Visual studio 2008 provides new features for WCF compared to Visual Studio 2005. These are the new features added to VS 2008.
    1. Multi-targeting

      You can create application in different framework like Framework 2.0, 3.0 and 3.5
    2. Default template is available for WCF

    3. WCF - Test Client tools for testing the WCF service.

      Microsoft provides inbuilt application to test the WCF application. This can be done by opening the Visual Studio command prompt and type the wcfClient Serviceurl shows below. This will help the developer to test the service before creating the client application.
    4. WCF services can be debugged now in Visual Studio 2008. Wcfsvchost.exe will do it for you because service will be self hosted when you start debugging.

    Introduction to WCF

    Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
    Below figures shows the different technology combined to form WCF.

    Advantage

    1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
    2. WCF services provide better reliability and security in compared to ASMX web services.
    3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
    4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

    Disadvantage

    Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article.