Search This Blog

Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Tuesday, July 23, 2013

WCF SOAP and WCF REST (WCF SOAP Vs REST )

Major difference between WCF SOAP and WCF REST is flexibility.
  • WCF SOAP services supports a wide range of transport protocols, including HTTP.
  • WCF REST services only support HTTP.
One point to remember about the SOAP services is that the size of its messages adds a significant overhead. The message size is related to the fact that SOAP is intended to interoperate with different platforms, such as Java. This overhead may be a matter of concern, in terms of performance and scalability, if your application has many transactions, complex data structures, and handles large volumes of data. On the other hand, WCF REST services use the standard HTTP protocol.

The second difference between the two types of services is that
WCF SOAP services are an operations-based service. A SOAP client application calls a method that is published as a web service operation on a remote server. The client receives a SOAP response in return. Web services expose an organization's capabilities, such as automated ordering and pricing services that customers can use. WCF REST services are resource-based. A client sends an HTTP request, much the way an Internet browser does, and receives a resource in return, such as data, video, or images.

The third difference is security. Traditional WCF SOAP services support more advanced security measures, such as message-based or federated security. SOAP also offers reliable messaging and transactional services, due to its support of WS-Security specifications, which have evolved over several years.

Additional Resources : 
REST in Windows Communication Foundation on MSDN at

WCF Data Services on MSDN at
Previous article: Operation-based SOAP vs. Resource-based REST

Wednesday, November 16, 2011

Exposing 2 endpoints for same WCF service using different Bindings



I just created a simple which exposes a service through 2 different endpoints which uses different bindings.One is basicHttpBinding and another using wsHttpBinding.

Specifying 2 EndPoints 

If you have a basic idea about WCF you can easily understand the below configuration in web.config which exposes  Uploader service through 2 different end points.

<services>
 
<service behaviorConfiguration="DemoMTOM.Web.UploaderBehavior"  name="DemoMTOM.Web.Uploader">
   
<endpoint address="bh" binding="basicHttpBinding" contract="DemoMTOM.Web.IUploader">
     
<identity>
       
<dns value="localhost"/>
     
</identity>
   
</endpoint>
   
<endpoint address="wh" binding="wsHttpBinding" contract="DemoMTOM.Web.IUploader">
     
<identity>
       
<dns value="localhost"/>
     
</identity>
   
</endpoint>
   
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
 
</service>
</services>

In the sample the url to the basicHttpBinding endpoint is http://localhost:64738/Uploader.svc/bh and the url to the wsHttpBinding endpoint is http://localhost:64738/Uploader.svc/wh. You can check this by adding a service reference in to a WPF application. 

Creating ServiceClient to call the service in WPF
When we create service reference in the WPF application, the app.config in the WPF application will get 2 entries.One for basicHttpBinding and another for wsHttpBinding.See the sample app.config below.


<client>
   
<endpoint address="http://localhost:64738/Uploader.svc/bh" binding="basicHttpBinding"
       
bindingConfiguration="BasicHttpBinding_IUploader" contract="UploadServiceReference.IUploader"
       
name="BasicHttpBinding_IUploader" />
   
<endpoint address="http://localhost:64738/Uploader.svc/wh" binding="wsHttpBinding"
       
bindingConfiguration="WSHttpBinding_IUploader" contract="UploadServiceReference.IUploader"
       
name="WSHttpBinding_IUploader">
       
<identity>
           
<dns value="localhost" />
       
</identity>
   
</endpoint>
</client>


So at the calling side there will be confusion of course in selecting the end point.So to resolve that confusion we have to specify the endPointConfigurationName at the time of creating client. See code below which uses the basicHttpBinding.


UploadServiceReference.UploaderClient cli = new UploadServiceReference.UploaderClient("BasicHttpBinding_IUploader");
string res = cli.DoWork("Joy");



UploadServiceReference.UploaderClient cli = new UploadServiceReference.UploaderClient("WSHttpBinding_IUploader");
string res = cli.DoWork("Joy");

The second code snippet uses wsHttpBinding to call the service.

Hosting service using 2 endpoints in a Console Application


static void Main(string[] args)
{
   
try
    {
        ServiceHost serviceHost =
new ServiceHost(typeof(Uploader),
           
new Uri("http://localhost:64738/Uploader.svc"));

        serviceHost.AddServiceEndpoint(
typeof(IUploader), new BasicHttpBinding(), "bh");
        serviceHost.AddServiceEndpoint(
typeof(IUploader), new WSHttpBinding(), "wh");

        ServiceMetadataBehavior smb =
new ServiceMetadataBehavior();
        smb.HttpGetEnabled =
true;
        serviceHost.Description.Behaviors.Add(smb);

        ServiceDebugBehavior sdb =  serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
        sdb.IncludeExceptionDetailInFaults =
true;

        serviceHost.Open();

        Console.WriteLine(
"Service running below are the Endpoints :");
       
foreach (ServiceEndpoint se in serviceHost.Description.Endpoints)
        {
            Console.WriteLine(se.Address.ToString());
        }
        Console.WriteLine(
"Press any key to quit...");
        Console.ReadLine();

        serviceHost.Close();
    }
   
catch (Exception ex)
    {
        Console.WriteLine(
string.Format("Error :{0}", ex.Message));
        Console.ReadLine();
    }
}

In the sample when you try to run the console application it will throw an error because the asp.net application also runs and uses the same port. So run the console application from command line or explorer.

There is no need to change the reference in the WPF application since both these console application and asp.net service host is using same url.


Tuesday, November 15, 2011

How to test WCF services

The typical way of testing WCF services is to create a test project, add a service reference to the project, and then write a test against the client object that is automatically created for you:
  • Create a test project
  • Right-click References and select Add Service Reference
  • In the Address box, type in the URL to the SVC file that is hosted on a web server. You can use the Discover button to find WCF services in the same solution.
  • Select a namespace to use for the service client that will be created, and press OK
This will create a class called <Namespace>.<ServiceName>Client for you, which will act as a client proxy to the WCF service. You can then write unit tests against that class just as you would write unit tests against a regular class. You could have a helper method that would convert some input parameters to the Byte array the WCF service takes, and returns the result. Then, each unit test would just call the helper method with the appropriate input parameters, and do validation on the output. The amount of code needed in each unit test can be minimized, but depends on how much validation needs to be done.

It looks like what you have is a web page that acts as a client to the WCF service. It is possible to have the web page take input parameters as query-string parameters in the URL, and have it write the result to the response, as it is already doing. With this, it would be possible to create web tests to test the WCF service through the web page. However, this requires that the web page be hosted on a web server, and separates related parts of test code.

To answer your questions specifically:
  1. The first approach I mentioned above is probably the best way to test a WCF service. It allows you to test methods/properties exposed in the service contract in the same way as any other client application would use the service.
  2. The amount of code that is necessary really depends on how much validation needs to be done on what is being tested. You can use a web page client as an alternative, in which case the amount of code that is needed may be slightly reduced, but you still need the same inputs to the service and the same validation on the outputs, so if it is not through code, it will be through searching the response from the web page. Using a web page client may even unnecessarily complicate your test code, in things such as parsing the query strings to convert the input parameters to the right types, and then parsing the response text to do validation.
  3. Using WcfTestClient.exe (for more info: http://msdn.microsoft.com/en-us/library/bb552364.aspx)
  4. VSTS 2008 Test Edition is definitely the right tool for testing WCF services. With the service client that is automatically created for you, testing a WCF service becomes a task as simple as testing a regular class. 

Monday, October 17, 2011

WCF architecture



WCF offers immensely valuable support for reliability, transactions, concurrency management, security, and instance activation, all of which rely on the WCF interception-based architecture. Having the client interact with a proxy means that WCF is always present between the service and the client, intercepting the call and performing pre-call and post-call processing.The interception starts when the proxy serializes the call stack frame to a message and sends the message down a chain of channels. The channel is merely an interceptor whose purpose is to perform a specific task. Each client-side channel does pre-call processing of the message. The exact structure and composition of the chain depend mostly on the binding. For example, one of the channels may be responsible for encoding the message (binary, text, or MTOM), another for passing the security call context, another for propagating the client transaction, another for managing the reliable session, another for encrypting the message body (if so configured), and so on. The last channel on the client side is the transport channel, which sends the message over the configured transport to the host.

On the host side, the message goes through another chain of channels that perform host-side pre-call processing of the message. The first channel on the host side is the transport channel, which receives the message from the transport. Subsequent channels perform various tasks, such as decryption of the message body, decoding of the message, joining the propagated transaction, setting the security principal, managing the session, and activating the service instance. The last channel on the host side passes the message to the dispatcher. The dispatcher converts the message to a stack frame and calls the service instance.
 This sequence is depicted in Figure 1


                                             

  Figure 1. The WCF architecture

The service has no way of knowing that it was not called by a local client. In fact, it was called by a local client—the dispatcher. The interception both on the client and the service sides ensures that the client and the service get the runtime environments they require to operate properly.

The service instance executes the call and returns control to the dispatcher, which then converts the returned values and error information (if any) into a return message. The process is then reversed: the dispatcher passes the message through the host-side channels to perform post-call processing, such as managing the transaction, deactivating the instance, encoding the reply, encrypting it, and so on. The returned message then goes to the transport channel, which sends it to the client-side channels for clientside post-call processing. This process in turn consists of tasks such as decryption, decoding, committing or aborting the transaction, and so on. The last channel passes the message to the proxy, which converts the returned message to a stack frame and returns control to the client.

Wednesday, September 21, 2011

Host WCF service with multiple host environment using multiple protocol

Introduction

In the world of distributed application, many technologies has been introduced, implemented and used like DCOM, CORBA,…etc.
And after that, a new concept has been adapted,it was the web services. Web service is simple to develop and implement without paying attention to firewall issues and as a result, communication between systems has been simplified.
The problem while developing a web service is you need to host it inside a web server like IIS or Apache using http or wshttp protocols, and this is the only option you have.
WCF has solved this issue, by providing the possibility to host your service in a different application process using also various protocols.
In this article I’ll show how you can achieve this.
The sample code includes a simple WCF service, console windows host, windows service host, IIS6 host, II7 host and client console windows application built in VS 2008 Standard edition and .NET 3.0.

Background

As we know if you adopt web services architecture for your system, you need the flowing:
- create a service like a component library using [WebService] and [WebMethod] attributes
- host it inside a web server like IIS
- generate a proxy (interface or contract) from the WSDL
- distribute this proxy to clients application who needs to call and use this web service.

Multiple Host and Protocol Support with WCF

Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.

Hosting Environment Supported protocol
Windows console and form application HTTP,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services) HTTP,net.tcp,net.pipe,net.msmq
Web server IIS6 http, wshttp
Web server IIS7 - Windows Process Activation Service (WAS) http, wshttp, net.tcp, net.pipe, net.msmq
Architect_Article.PNG

Create a test service

Here I have created a very simple service called “FirstWcfService.Service” as in the following listing -1 :
FirstWcfService.PNG
// Listing -1 IService.cs file
using System;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace FirstWcfService
{
    [ServiceContract]
    public interface IService
    {
   
        [OperationContract]
        string Hello(); 
    }
}
// Service.cs file
using System;
namespace FirstWcfService
{
    public class Service : IService
    {
        public string Hello()
        {
            return ("Hello WCF");
        }
    }
}
As we can see, this service contains only on operation contract (Hello), this operation will return simple string “Hello WCF”.


Hosting our service

As I have mentioned in the begging of my article, with the arrival of WCF, now we have multiple options to host this service.
In each hosting environment, we need to provide an endpoint for this service and also we need to reference it, in order the client application can reach this service.
What does that mean practically, it means we have to create a configuration file for our hosted service.

Option 1 – windows console host application

1 - I created here a classic console application (picture 1) and then I hosted my service as in the following listing – 2:
FirstWcfServiceHostConsoleApp.PNG
//Listing – 2 Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace FirstWcfServiceHostConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
          
using (ServiceHost host = new ServiceHost(typeof(FirstWcfService.Service)))
            {
                host.Open();
                Console.WriteLine("Press <Enter> to terminate the Host application.");
                Console.ReadLine();
            }
           
        }
    }
}
 
In order to host a WCF service inside a console application we need a minimum of work. Let us examine the code in the above listing:
This code ServiceHost host = new ServiceHost(typeof(FirstWcfService.Service)
creates an instane of our service.
This line host.Open() makes the service ready for access inside the hosting enviroemnt.
2- Secondly I have created a configuration file with a minimum configuration options as in the following listing - 3:

//Listing – 3 App.config
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="FirstWcfService.Service" behaviorConfiguration="ServiceBehavior">
        <!-- Service Endpoints -->
        <endpoint address="FirstWcfService" binding="netTcpBinding" 
            contract="FirstWcfService.IService"/>
        <!-- This Endpoint is used for genertaing the proxy for the client -->
 <!-- To avoid disclosing metadata information, set the value below to false and
       remove the metadata endpoint above before deployment -->
        <endpoint address="mex" contract="IMetadataExchange" binding="mexTcpBinding" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9100/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Option 2 – windows service host application

1 - I created here a classic windows service application and then I hosted my service as in the following listing – 4:
FirstWcfServiceWindowsServiceHost.PNG
//Listing - 4, Program.cs
using System;
using System.ServiceProcess;
namespace Windows_Service
{
    static class Program
    {
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { new WCFWindowsService() };
            ServiceBase.Run(ServicesToRun);
        }
    }
}
//Listing - 4, WCFWindowsService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.ServiceModel;
namespace Windows_Service
{
    public partial class WCFWindowsService : ServiceBase
    {
       ServiceHost m_serviceHost;
        
protected override void OnStart(string[] args)
        {
            m_serviceHost = new ServiceHost(typeof(FirstWcfService.Service));
            m_serviceHost.Open();
        }
        
        protected override void OnStop()
        {
            if (m_serviceHost != null)
            {
                m_serviceHost.Close();
            }
            m_serviceHost = null;
        }
    }
}
 
In order to host a WCF service inside a windows service application, we need also a minimum of work by implementing the followings functions:
void OnStart(string[] args) and protected override void OnStop()
Let us examine the code in the above listing:
This code:

m_serviceHost = new ServiceHost(typeof(FirstWcfService.Service));
m_serviceHost.Open();

creates an instane of our service and then makes the service ready for access inside the hosting enviroment.
2 - To make this application working like a windows service, we should install it as in Listing – 5. This file is not related to WCF implementation, so I’m not going to explain what does this code does.

//Listing - 5, WCFWindowsServiceInstaller.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
// To install or uninstall this Windows service via cmd:
//
//C:\Program Files\Microsoft Visual Studio 9.0\VC>installutil.exe /u  yourpath/WCFWindowsService.exe
//C:\Program Files\Microsoft Visual Studio 9.0\VC>installutil.exe     yourpath/WCFWindowsService.exe
namespace Windows_Service
{
    [RunInstaller(true)]
    public partial class WCFWindowsServiceInstaller : Installer
    {
        public WCFWindowsServiceInstaller()
        {
            InitializeComponent();
            ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();
            processInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.DisplayName = "WCF_WindowsService";
            serviceInstaller.Description = "WCF_WindowsService.";
            serviceInstaller.ServiceName = "WCF_WindowsService";
            serviceInstaller.StartType = ServiceStartMode.Manual;
            Installers.Add(processInstaller);
            Installers.Add(serviceInstaller);
        }
    }
}
3 - I have created a configuration file with a minimum configuration options as in the following listing - 6:
 //Listing - 6, App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="FirstWcfService.Service" behaviorConfiguration="ServiceBehavior">
        <endpoint address="FirstWcfService" contract="FirstWcfService.IService"
             binding="netTcpBinding" />
        <!-- This Endpoint is used for genertaing the proxy for the client -->
        <endpoint address="mex" contract="IMetadataExchange" binding="mexTcpBinding" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9000"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Option 3 – IIS6 host application

1 - I created here a simple WCF Service web application and then I have referenced FirstWcfService in order to host it as in the following listing – 7:
FirstWcfIIS6Host.PNG
 //Listing - 7, file Service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="FirstWcfService.Service"%>
As see can see her, when we host a WCF service inside IIS, we do not need to create a host service and open it as we have done in the console and service windows application hosting, because IIS is responsible for creating the service and make it listening to clients calls, all we need just the above code inside a .svc file.
2- I have created a configuration file with a minimum configuration options as in the following listing -8:
 
//Listing - 8, Web.config
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="FirstWcfService.Service" behaviorConfiguration="ServiceBehavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="basicHttpBinding"
           contract="FirstWcfService.IService"/>
       <!-- This Endpoint is used for genertaing the proxy for the client --> 
<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>
</configuration>

Option 4 – IIS7 (WAS) host application

1 - I created here a simple WCF Service web application using windows server 2008 (IIS7) and then I have referenced FirstWcfService in order to host it as in the following listing – 9:
FirstWcfIIS7Host.PNG
//Listing - 9 file Service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="FirstWcfService.Service"%>
2- I have created a configuration file with a minimum configuration options as in the following listing -10:
 
//Listing - 10, Web.config
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="FirstWcfService.Service" behaviorConfiguration="ServiceBehavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="netTcpBinding" contract="FirstWcfService.IService"
            bindingConfiguration="tcpbinding"/>
        <endpoint address="mextcp" 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>
    <bindings>
      <netTcpBinding>
        <binding name="tcpbinding">
          <!--<security mode="None"></security>-->
          <security mode="Transport">
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
            <message clientCredentialType="Windows"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
 
NOTE:As you can see here, I have done the same implementation as I did for option 3 while hosting my SCF service inside II6, the only difference is, I have configured my service to be callable using “net.Tcp” protocol inside IIS7 (WAS) instead of classic “basicHttp” protocol. I’m not going to explain the new architecture of IIS7, because this topic is out of scope in this article.
3- When you create a WCF service inside IIS7, by default this service has only http and wshttp enabled. I have configured my service to be callable using net.Tcp protocol as in the following steps:
A - in order to enable a new protocol like net.Tcp, we need to add it to our default web site tree via IIS Manager by clinking on “Edit Bindings”
IIS7Manager1.PNG

B - Add the new protocol with the desired port also, I added 9200

IIS7Manager3.PNG
IIS7Manager2.PNG

C – Always from IIS Manager, add the net.Tcp to your WCf service by clicking on advanced settings:
IIS7Manager4.PNG

D – write your desired protocol through Enabled protocols settings :
IIS7Manager5.PNG

Create the client application

I created a simple client console application in order to show you how we can call our WCF service using multiple hosting options.
My client application looks like this:
FirstWcfServiceClientConsoleApp.PNG
Let’s examine this application:
1 – We need co create a proxy, to create a proxy we have tow possibilities:
Either from Visual studio by adding a service reference as below :
ServiceRef.PNG
Or by using the SvcUtil.exe utility, as we have multiple hosting options, we can observe here that we need just to use one of the following created proxy :
• If you create the proxy from a service hosted inside a console application you make: SvcUtil.exe net.tcp://localhost:9100/mex /out:path\proxy.cs /n:*,localhost
• If you create the proxy from a service hosted inside a windows service application you make SvcUtil.exe net.tcp://localhost:9000/mex /out:path\proxy.cs /n:*,localhost
• If you create the proxy from a service hosted inside an IIS 6 you make SvcUtil.exe http://localhost/FirstWcfIISHost/Service.svc /out:path\proxy.cs /n:*,localhost
• If you create the proxy from a service hosted inside an IIS7 using tcp protocol you make SvcUtil.exe net.tcp://winserver2008:9200/FirstWcfHost/Service.svc/ out:path\proxy.cs /n:*,localhost
When you create your proxy for the first time, you can use the same proxy to call the same service inside different hosting environments.
Finally our proxy will be as the following listing – 11
// Listing - 11 proxy.cs file
namespace localhost
{
    
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="localhost.IService")]
    public interface IService
    {
        
        [System.ServiceModel.OperationContractAttribute(Action =
            "%22http://tempuri.org/IService/Hello%22">http://tempuri.org/IService/Hello",
            ReplyAction = "%22http://tempuri.org/IService/HelloResponse%22">http://tempuri.org/IService/HelloResponse")]
        string Hello();
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public interface IServiceChannel : localhost.IService,
        System.ServiceModel.IClientChannel
    {
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public partial class ServiceClient :
        System.ServiceModel.ClientBase<localhost.IService>, localhost.IService
    {
        
        public ServiceClient()
        {
        }
        
        public ServiceClient(string endpointConfigurationName) : 
                base(endpointConfigurationName)
        {
        }
        
        public ServiceClient(string endpointConfigurationName, string remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
        
        public ServiceClient(string endpointConfigurationName,
            System.ServiceModel.EndpointAddress remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
        
        public ServiceClient(System.ServiceModel.Channels.Binding binding,
            System.ServiceModel.EndpointAddress remoteAddress) : 
                base(binding, remoteAddress)
        {
        }
        
        public string Hello()
        {
            return base.Channel.Hello();
        }
    }
}
2- I have created a configuration file with a minimum configuration options as in the following listing -12:
//Listing - 12, App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <client>
      <!-- calling the WCF service which is hosted inside windows console application -->
      <endpoint address="net.tcp://localhost:9100/FirstWcfService" binding="netTcpBinding"
          contract="localhost.IService" name="Windows_Console_Host_TcpBinding">
      </endpoint>
      <!-- calling the WCF service which is hosted inside IIS6 -->
      <endpoint address="%22http://localhost/FirstWcfIISHost/Service.svc%22">http://localhost/FirstWcfIISHost/Service.svc"
          binding="basicHttpBinding"
          contract="localhost.IService" name="IIS_Host_HttpBinding">
      </endpoint>
      <!-- calling the WCF service which is hosted inside windows service  -->
      <endpoint address="net.tcp://localhost:9000/FirstWcfService"
          binding="netTcpBinding"
          contract="localhost.IService" name="Windows_Services_Host_TcpBinding">
      </endpoint>
      <!-- calling the WCF service which is hosted inside IIS7 (WAS)  -->
      <endpoint address="net.tcp://winserver2008:9200/FirstWcfHost/Service.svc"
          binding="netTcpBinding"
          contract="localhost.IService" name="II7_WAS_Host_TcpBinding"
          bindingConfiguration="II7NetTcpBinding">
      </endpoint>
    </client>
    <bindings>
      <netTcpBinding>
        <binding name="II7NetTcpBinding">
          <!--<security mode="None"></security>-->
          <security mode="Transport">
                    <transport clientCredentialType="Windows"
                         protectionLevel="EncryptAndSign"/>
                    <message clientCredentialType="Windows"/>
                  </security>
        </binding>
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
In this file I have configured my client in order to show you how we can call the same WCF service hosted in different environments. In realty you do not need all these endpoints, you need only one of these endpoints for your client, so your “app.config” would be as in following listing - 13:
<?x ml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <client>
      <!-- calling the WCF service which is hosted inside windows console application -->
      <endpoint address="net.tcp://localhost:9100/FirstWcfService" binding="netTcpBinding"
          contract="localhost.IService" name="Windows_Console_Host_TcpBinding">
      </endpoint>
    </client>
   </system.serviceModel>
</configuration>
3- I have implemented my client as in the following listing -14:
//Listing - 14, Program.cs
using System;
namespace FirstWcfServiceClientConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                #region Call the hosted service inside IIS6
                localhost.ServiceClient iis6proxy = new localhost.ServiceClient(
                    "IIS_Host_HttpBinding");
                Console.WriteLine("=====================");
                Console.WriteLine("Call the hosted service inside IIS6");
                Console.WriteLine(iis6proxy.Hello());
                Console.WriteLine("=====================");
                Console.WriteLine();
                #endregion
                #region Call the hosted service inside IIS7 (WAS)
                localhost.ServiceClient iis7proxy = new localhost.ServiceClient(
                    "II7_WAS_Host_TcpBinding");
                Console.WriteLine("=====================");
                Console.WriteLine("Call the hosted service inside IIS7 (WAS)");
                Console.WriteLine(iis7proxy.Hello());
                Console.WriteLine("=====================");
                Console.WriteLine();
                #endregion
                #region Call the hosted service inside Windows service application
                localhost.ServiceClient tcpWindowsSrviceproxy =
                    new localhost.ServiceClient("Windows_Services_Host_TcpBinding");
                Console.WriteLine("=====================");
                Console.WriteLine(
                    "Call the hosted service inside Windows service application");
                Console.WriteLine(tcpWindowsSrviceproxy.Hello());
                Console.WriteLine("=====================");
                Console.WriteLine();
                #endregion
                #region Call the hosted service inside Windows Console application
                localhost.ServiceClient tcpproxy = new localhost.ServiceClient(
                     "Windows_Console_Host_TcpBinding");
                Console.WriteLine("=====================");
                Console.WriteLine(
                    "Call the hosted service inside Windows Console application");
                Console.WriteLine(tcpproxy.Hello());
                Console.WriteLine("=====================");
                Console.WriteLine();
                Console.WriteLine("Press <Enter> to terminate the client application.");
                Console.ReadLine();
                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
    }
}
In the above code, we notice that in order to call a WCF service, we need to instantiate the proxy class like this :
localhost.ServiceClient iis6proxy = new localhost.ServiceClient("IIS_Host_HttpBinding");
and then we can call a function or method we are interested like this:
iis6proxy.Hello());

Putting all together and get the result

My final solution will be something like that:
FirstWcfServiceSolution.PNG
Finally when we run the client application (FirstWcfServiceClientConsoleApp.exe) after verifying that all four hosting environments (IIS6, IIS7, windows service, windows console application) are running and listening, we get the following wonderful result:
ClientResult.PNG
As you can notice here, we have created a WCF service, hosted it in four different environments as below using different protocols :
- Windows a console application using tcp protocol
- Windows service process using tcp protocol
- IIS6 using http protocol
- IIS7 using tcp protocol
By changing only the endpoint on the client we have been able to access our WCF service and calling functions.
What I do like to precise here, different client applications (Windows, Intranet, Internet, Extranet, ..etc) can call the service in different hosting environments.

Popular Posts