WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 144 users


WorldofASP.NET >> .NET 3.5 >> Unedited .NET 3

Implement a simple windows communication foundation

Create the Derivatives Calculator Service which implement WCF
Published Date : 06 Jul 2008
Author : Hans Candra
Language : C#
Platform : .NET
Technology : WCF
Views : 968
Rating : (1 votes so far)



Introduction

Windows Communication Foundation, or just WCF, is a programming framework used to build applications that inter-communicate. WCF is the part of the .NET Framework dedicated to communications.

Originally tagged with the code name "Indigo", WCF is one of the four new application programming interfaces introduced with .NET Framework 3.0, which was released in December 2006. The .NET Framework is Microsoft technology that ships in Windows operating systems (client, server and mobile platforms). The .NET Framework v3.0 is included in Windows Vista and Windows Server 2008; It is available as a free download for Windows XP and Windows Server 2003, and a similar but separate version is also available for .NET Compact Framework version 3.5.

Because WCF is part of the .NET Framework, applications that use WCF can be developed in any programming language that can target the .NET runtime.

The WCF programming model unifies the various communications programming models supported in .NET 2.0, into a single model. Released in November 2005, .NET 2.0 provided separate APIs for SOAP-based communications for maximum interoperability (Web Services), binary-optimized communications between applications running on Windows machines (.NET Remoting), transactional communications (Distributed Transactions), and asynchronous communications (Message Queues). WCF unifies the capabilities from these mechanisms into a single, common, general Service-oriented programming model for communications.

Main

Here we will try to define implement a simple WCF to a project called DerivativesCalculator

First step create a visual studio solution then create a c# class project.



Next step is to add a reference for Windows Communication Foundation to the DerivativesCalculatorService Project. It is in add reference -> .NET tab -> System.ServiceModel. Next define the Contract that the Derivatives Calculator Service will Expose. Rename the class file, Class1.cs, in the DerivativesCalculatorService project to IDerivativesCalculator.cs, and modify the content thereof to read as follows:

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;

namespace DerivativesCalculatorService
{
    [ServiceContract]
    public interface IDerivativesCalculator
    {
        [OperationContract]
        Decimal CalculateDerivative(int days, string[] symbols, 
string[] functions);
    }
}

Next is to Implement the Contract that the Derivatives Calculator Service will Expose. Add a class named, Calculator.cs, to the project, and modify its contents to look like this and build the project:

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;

namespace DerivativesCalculatorService
{
    public class Calculator : IDerivativesCalculator
    {
        #region IDerivativesCalculator Members

        decimal IDerivativesCalculator.CalculateDerivative(int days,
 string[] symbols, string[] functions)
        {
            return (decimal)(System.DateTime.Now.Millisecond);
        }

        #endregion
    }
}

You will need to host the Derivatives Calculator Service that you defined and implemented in the first exercise to the .NET executeable. Specifically, you will host the service within a .NET console application.

Add a new console application project called, Host, to the DerivativesCalculator solution. There are 3 reference you must add to this new host project. From .NET tab is System.ServiceModel, System.Configuration, and a reference to the DerivatesCalculatorService project.


Next step is to write the Windows Communication Foundation code needed to provide a host for the Derivatives Calculator service. Modify the Program.cs class in the Host project to read as follows:

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;
using System.Configuration;
using DerivativesCalculatorService;

namespace Host
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Type serviceType = typeof(Calculator);


            using (ServiceHost host = new ServiceHost(serviceType))
            {
                host.Open();

                Console.WriteLine(
                    "The derivatives calculator service is available."
                );
                Console.ReadKey();
            }

        }
    }
}

Configure this service by add an application configuration file named, app.config, to the Host project in your solution.

<configuration>
  <system.servicemodel>

    <services>
      <service name="DerivativesCalculatorService.Calculator" 
behaviorconfiguration="metadataBehavior">
        <endpoint address="CalculatorService" binding="basicHttpBinding" 
contract="DerivativesCalculatorService.IDerivativesCalculator">
        <endpoint address="mex" binding="mexHttpBinding" 
contract="IMetadataExchange">
        <host>
          <baseaddresses>
            <add baseaddress="http://localhost:8000/Derivatives/">
            <add baseaddress="net.tcp://localhost:8010/Derivatives/">
          </add>
        </add>
      </baseaddresses>
    </host>
    <behaviors>
      <servicebehaviors>
        <behavior name="metadataBehavior">
          <servicemetadata httpgetenabled="true">
        </servicemetadata>
      </behavior>
    </servicebehaviors>
  </behaviors>
</endpoint>
</endpoint></service></services></system.servicemodel>
</configuration>

Test the Service
1. Build the DerivativesCalculator solution.
2. Start a new instance of the Host project.
3. Choose Run from the Windows Start menu, and enter.

http://localhost:8000/Derivatives/
Internet Explorer should open, and display a page like the one in figure below.


You can try to click on the link to http://localhost:8000/Derivatives/?wsdl near the top of the page and examine the page of WSDL that appears. Close Internet Explorer and then you can enter a keystroke into the console application window of the Host executable to terminate the Derivatives Calculator Service.

Next step is to consume the service we have created above. you will build a client that will use the Derivatives Calculator Service above. Add a second new C# Console Application project called, Client, to your solution. Generate a Typed Proxy and Configuration File for the Client Application.

1. Start a new instance of the Host project.
2. Open the Start->Programs->Microsoft Windows SDK->Cmd Shell command prompt.
3. Enter,
cd c:\Windows Communication Foundation\Labs\DerivativesCalculator at the command prompt.
4. Next, enter,
svcutil http://localhost:8000/Derivatives/ /out:Client.cs /config:app.config
5. Choose Debug and Stop Debugging from the Visual Studio menus.

Next Add a reference to the System.ServiceModel .NET assembly, to the Client project. Next is to Code and Configure the Client to Consume this DerivativesCalculator Service. Modift the app.config in Client project like the one below:

<configuration>
    <system.servicemodel>
        <bindings>
            <basichttpbinding>
                <binding name="BasicHttpBinding_IDerivativesCalculator" 
closetimeout="00:01:00" opentimeout="00:01:00" receivetimeout="00:10:00" 
sendtimeout="00:01:00" allowcookies="false" bypassproxyonlocal="false" 
hostnamecomparisonmode="StrongWildcard" maxbuffersize="65536" maxbufferpoolsize="524288" 
maxreceivedmessagesize="65536" messageencoding="Text" textencoding="utf-8" 
transfermode="Buffered" usedefaultwebproxy="true">
                    <readerquotas maxdepth="32" maxstringcontentlength="8192" 
maxarraylength="16384" maxbytesperread="4096" maxnametablecharcount="16384">
                    <security mode="None">
                        <transport clientcredentialtype="None" 
proxycredentialtype="None" realm="">
                        <message clientcredentialtype="UserName" 
algorithmsuite="Default">
                    </message>
                </transport>
            </security>
        </readerquotas>
        <client>
            <endpoint address="http://localhost/DerivativesCalculator/Service.svc" binding="wsHttpBinding" 
contract="IDerivativesCalculator" name="DerivativesCalculatorConfiguration">
        </endpoint>
    </client>
</binding>
</basichttpbinding>
</bindings>
</system.servicemodel></configuration>

Write the code in the Program.cs file of the Client project like the one below:

using System;
using System.Collections.Generic;
using System.Text;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key when the service is ready.");
            Console.ReadKey();

            DerivativesCalculatorClient proxy = new 
DerivativesCalculatorClient("DerivativesCalculatorConfiguration");
            decimal result = proxy.CalculateDerivative(3, new 
string[] { "MSFT" }, new string[] { });
            Console.WriteLine("Result: {0}", result);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

        }
    }
}

The last step is to have the client consume the DerivativesCalculator Service. Set client project as startup project and run/debug your solution. When you see activity in the console for the Host application, enter a keystroke into the console for the Client application. You should see the client obtain an estimate of the value of a derivative from the Derivatives Calculator service, as shown in below. Note that the value shown in your console may vary from the value shown below, due to variations in prevailing market conditions over time.


Conclusion

You used the Windows Communication Foundation to provide and use a simple service. You saw the flexibility of the options for hosting services, by which services can be hosted in any .NET executable. You also saw how the address and bindings of a service can be altered independently of the code in the service or in its clients, to change the location of a service, and also how it communicates.

References

Include all the useful links or references that can help users learn about this tutorial

  1. MSDN Windows Communication Foundation
  2. Introduction to Building Windows Communication Foundation Services

Download Source Code


Tag Cloud
  asp.net cookies encryption   httpwebrequest   upload file progress bar asp.net   httpwebrequest in asp.net 2.0   form view in asp.net   asp.net encryption   formview displaying inserted data   cannot start service from the command line or a debugger. a windows service must   httpwebresponse   asp httpwebrequest   feedback form in asp.net   edit update insert in a gridview c#   asp.net listbox control   httpwebrequest vb.net   httpwebrequest .net   httpwebrequest httpwebresponse   checkboxlist datasource   asp.net httpwebrequest   asp.net cookie shopping cart   asp.net random number   "javascript in asp.net"   xhtml-mp asp.net   asp.net url parameters   encrypt querystring in asp.net   asp.net file upload progress bar   httpwebrequest create   asp.net delegate   tooltip asp.net   create httpwebrequest   cannot start service from the command line or a debugger   httpmodule httphandler   frames image gallery thumbnails asp.net   asp.net upload ajax progress   ajax updatepanel button   asp.net activate user   datalist control   asp.net file upload progress   asp.net pass data from one page to another   asp.net tooltip   formview asp.net   httpwebrequest asp.net c#   contact us asp.net   generate random number asp.net   smart device application





Other Related and Popular Articles :

Basic Silverlight programming in VS 2008
This article teach you how to code Silverlight by using Visual Studio 2008

Basic introduction of LINQ
This article covers basic introduction of LINQ

Visions in Online Crystal Ball: Is Silverlight 2.0 THE NEXT BIG THING
General article about Silverlight 2.0

Introduction to Language Integrated Query (LINQ)
Building the Data Access Layers Using LINQ to SQL in ASP.NET 3.5

Enhancing Web Experience with Siverlight
Developing a sample application to integrate silverlight with ASP.NET


Author Profile : Hans Candra

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

Leave New Comments


Article Content copyright by Hans Candra
Everything else Copyright © by WorldofASP.NET 2008

Category
.NET 3.5
AJAX and ATLAS
ASP.NET
C# Programming
Classic ASP
Enterprise Systems
General .NET
VB.NET Programming
Announcements
Earn Cash by writing an article or review
For more info Click here







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | Windows Web Hosting | ASP.NET Hosting | Phone Card | PHP Directory | Bangkok Hotels |Calling Card