Proxy > Gmail Facebook Yahoo!

WCF Training Step-By-Step



I am going to start a WCF tutorial session. Anyone who knows how to program in C# and is looking for step by step guide to learning WCF, this could be the tuturial for them.    Followings are the Contents I am going to go through each day. 
1.  Different distributed computing APIs
2. WCF Assemblies
3. Visual Studio and WCF
4. Building a WCF Service and Client
5. WCF Service and Data Contracts
6. Different ways of hosting the WCF Service
7. Communication protocols
8. ASP.NET Web Service and WCF
9. Invoking WCF asynchronously
10. Exception handling
 
I will be updating the tutorial every day until the tutorial finishes.
1. Different distributed computing APIs
I am only going to describe different distributed computing APIs in brief. We would actually start coding from the next step. This is just an introduction of how WCF evolved.
1.1 DCOM – DCOM used COM objects distributed across network locations stored in Registry. The external storage of the location parameter is somewhat flexible but not an ultimate solution as it has disadvantages as well. DCOM does not support multiple operating systems and programming platforms. Due to the limited flexibility and platform issues, new solutions were sought and DCOM became a deprecated technology.  1.2 COM+ – COM+ is also known as Microsoft Transaction Server (MTS). COM+ is a windows based solutions and does not support other operating systems.  It is normally used for in-house software development. COM objects hide the complex implementations behind the interface which wraps around the object.  With the arrival of .NET technologies, COM+ is slowly disappering and becoming less popular. Click Here to dig into COM+ libraries further.
1.3 MSMQ – It is a queue based message delivery system used to build distributed systems. Other variations of MSMQ are System.Messaging in .NET and Queued Components.
1.4 .NET Remoting, Web Services and Windows Services – These are the main topics of study in WCF. .NET remoting is platform dependent and to overcome this web services and windows services come into play. TCP and HTTP are the main protocols we are going to study in this tutorial.
2. WCF Assemblies
In this section I will describe in brief about some of the core assemblies required to create and host services. If anyone wants to make further research on the assemblies, online MSDN library should have documentation of everything. But, as a beginner it is not a good idea to get confused with in depth details.
2.1 System.ServiceModel – This is required to create service and data contracts. We will talk about service and data contracts in later sections. This reference includes classes, types and interfaces required to build Services.
2.2 System.ServiceProcess – This assembly is required to host windows services. This assembly also allows us to install services.
2.3 System.Web.Services – This is similar to System.ServiceModel and System.ServiceProcess except that it is for Web Services. It provides all the types, functionalities and attributes required to create Web Servies.
System.Runtime.Serialization could also be one of the core assemblies, but one can build a simple WCF service and consume it without the use of Serialization.
3. Visual Studio and WCF
A good reference to find out about Visual Studio WCF templates is http://msdn.microsoft.com/en-us/library/bb552362.aspx
We will be using only a few among the templates specified in the above link in this tutorial.
  • ASP.NET Web Service Application
  • WCF Service Library
  • Windows Service
These templates are ordinary web application, class library and console application projects except that they already have reference to the required assemblies. They also contain default pages for the particular project type.
4. Building a WCF Service and Client (Download Code)
This is where we start the actual coding. We use Visual Studio as the development tool.
First of all we will start by creating a Class Library. We have to add reference to WCF assemblies as the class library is not WCF template. Follow the following steps to create a WCF Service.
4.1 Open Visual Studio. From the file menu File>New>Project. Select Class Library under Visual C# installed templates.
4.2 Right click the project in the solution explorer and add reference to System.ServiceModel.
4.3 Add new Interface called IServiceMultiply.cs and using System.ServiceModel on top. Add code to make your interface look like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace WCFTutorial
{
[ServiceContract (Namespace="http://www.localhost/IserviceMultiply")]
interface IServiceMultiply
{
[OperationContract]
double Multiply(double number1, double number2);
}
}
I will be describing about the contracts at the end of this section.
4.4 Rename the default Class1.cs to ServiceMultiply.cs. Derive the class from IServiceMultiply.cs
4.5 Create a Public function with the following code in ServiceMultiply
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;


namespace WCFTutorial
{
public class ServiceMultiply:IServiceMultiply
{
public double Multiply(double number1, double number2)
{
return number1 * number2;
}
}
}


4.6 Now that we have created a service contract, we need to host it so that a client can call it. Add a new Console Application Project called WCFConsoleHost.
4.7 Add reference to System.ServiceModel and project WCFTutorial.
Add Reference to System.ServiceModel
Add Reference to System.ServiceModel
4.8 Open Program.cs and add the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using WCFTutorial;
namespace WCFConsoleHost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Starting WCF Console Host”);
using (ServiceHost serviceHost = new ServiceHost(typeof(ServiceMultiply)))
{
serviceHost.Open();
Console.WriteLine(“The service is ready to be accessed.”);
Console.WriteLine(“Press any key to end the Service”);
Console.ReadLine();
}
}
}
}
4.9 The console application is not yet ready to host the service. We have to add an app.config file to set the endpoint address for the service. Copy and paste the following configuration to your app.config file and compile the program. If your console application does not contain app.config file, add one. We can also hard code the values withou using the app.config file which I’ll show at the end of this section.
<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<system.serviceModel>
<services>
<service name=”WCFTutorial.ServiceMultiply”
behaviorConfiguration = “ServiceMEXBehavior”>
<endpoint address =”"
binding=”basicHttpBinding”
contract=”WCFTutorial.IServiceMultiply”/>
<endpoint address=”mex”
binding=”mexHttpBinding”
contract=”IMetadataExchange” />
<host>
<baseAddresses>
<add baseAddress =”http://localhost:8080/ServiceMultiply”/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name=”ServiceMEXBehavior” >
<serviceMetadata httpGetEnabled=”true” />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration> I will describe about the configuration variables at the end of this section.
4.10 With your WCFConsoleHost set as Start up project debug the application. You should see the following message:
WCF Console Host - Multiply
WCF Console Host - Multiply
4.11 Now that we have successfully created the WCFConsoleHost, it’s time to create a console client to consume the service. Add a new Console Application called WCFConsoleClient to your solution file.
4.12 Add service reference to WCFConsoleHost. WCFConsoleHost needs to be running when adding the service reference. You can run it from within the debug folder of WCFConsoleHost.
Add Service Reference to WCF Console Host
Add Service Reference to WCF Console Host
4.13 After adding the reference open Program.cs and copy and paste the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFConsoleClient.ServiceReference1;
namespace WCFConsoleClient
{
class Program
{
static void Main(string[] args)
{
ServiceMultiplyClient svMultiply = new ServiceMultiplyClient();
Console.WriteLine(svMultiply.Multiply(10,2));
Console.Write("Press Enter to exit the application");
Console.ReadLine();
}
}
}
4.14 To test the WCFConsoleClient run the WCFConsoleHost.exe from bin\debug folder of WCFConsoleHost.
4.15 Set WCFConsoleClient as start up program and debug the program. You should see the following output. The first line displays 20 in the output which is the correct answer.
WCF Console Client Results
WCF Console Client Results
In the above example, instead of class library and Console application, we can use WCF Service library and Windows Service templates.
Now let me describe about what we did in the above example. The ServiceContract and OperationContract are the attributes which enable us to expose the operations and classes as Services. DataContract is another type of contract which we did not use. DataContract is used with custom data.
We can implement the service and the host in the same application and even without using the interface class. It depends on what programming style and standards you want to follow. In the config file, we specified the endpoint address which is required as WCF Clients will be using that url to access the service. We also enabled MEX endpoint in our config file. MEX stands for metadata exchange. Enabling MEX generates proxy code in the client when adding service reference.
If you browse the service endpoint address in your browser you will see the following sample code
http://localhost:8080/ServiceMultiply
WCF
WCF
We can also use other protocols like tcp and msmq to host a WCF Service.
Download Code for the abve sample.
5 WCF Service and Data Contracts
Creating Data Contract is also as simple as creating Service Contracts. You need to add reference to System.ServiceModel and System.Runtime.Serialization. After adding reference and using statements to your data class, just try to make your data class code similar to the following code:

    [DataContract]
    public class TestDataContract
    {
      
        [DataMember]
        public String TestData{get;set;}
    }

DataContract exposes the data class to the WCF Clients. Without [DataContract] attribute, the client would not know about the data type and would error if the data class is returned from any [OperationContract].
If sample code is required, please comment in the comments section.
6. Different ways of hosting WCF service
WCF Services can be hosted using windows services, web services and console application. In the previous examples, we already discussed about console application hosting. In this section I am going to demonstrate how we can host WCF using Windows and Web Services.
6.1 Windows Service – Follow the steps
6.1.1 Open the previously created project. If you downloaded the code from this website, unzip and open the solution file using Visual Studio.
6.1.2 Locate the project called ‘WCFConsoleHost’.
6.1.3 Right Click the project and click Add> New Item from the context menu. From the installed Visual C# Items select Windows Service. Rename Service1.cs to ServiceMultiplyInstaller.cs.
Windows Service in installed C# templates
Windows Service in installed C# templates
6.1.4 Open ServiceMultiplyInstaller.cs. Right Click anywhere within the designer window and click Add Installer. This adds ProjectInstaller.cs to the project.
Add Project Installer
Add Installer
6.1.5 In the ProjectInstaller.cs designer window, you will see two installer icons on the left top corner. Click on ServiceProcessInstaller1 and in the properties window change Account to LocalSystem.
Installer icons after adding installer
Installer icons after adding installer
Service Process Installer properties
Service Process Installer properties
6.1.6 Now Click the ServiceInstaller1 and in the properties window change the ServiceName property to ‘Multiply Service’. This name will appeaer in the windows service list when you install it. Also change StartType property to ‘Automatic’.
Multiply Service
Multiply Service
6.1.7 Now open the ServiceMultiplyInstaller code window. The OnStart and OnStop procedures are used to start and kill the service processes. Use the following code for ServiceMultiplyInstaller.cs.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using WCFTutorial;

namespace WCFConsoleHost
{
    partial class ServiceMultiplyInstaller : ServiceBase
    {
        private ServiceHost myHost;
        public ServiceMultiplyInstaller()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            if (myHost != null)
            {
                myHost.Close();
                myHost = null;
            }
            myHost = new ServiceHost(typeof(ServiceMultiply));
            myHost.Open();
        }
        protected override void OnStop()
        {
            // Shut down the host.
            if (myHost != null)
                myHost.Close();
        }
    }
}
6.1.8 Now it is time to edit the Program.cs file to initiate the service to run. Open program.cs and make sure the code looks like the following.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
namespace WCFConsoleHost
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
   {
    new ServiceMultiplyInstaller()
   };
            ServiceBase.Run(ServicesToRun);
        }
    }
}
6.1.9 Build the project.
6.1.10 Open Visual Studio and navigate to the project folder and locate the WCFConsoleHost.exe. In the command prompt use the installutil command to install WCFConsoleHost.exe as windows service.
installutil WCFConsoleHost.exe
6.1.11 Open Windows services and check the name Multiply service exists and has status set to Started. If not open it and start the service.
Windows Service list
Windows Service list
6.1.12 Now you can call this windows service from WCF client applications using the service reference specified in the config file of the project.
7. Communication protocols
HTTP, TCP, named pipes and MSMQ are the protocols supported by Windows Communication Foundation. I am not going to describe about the protocols here. Some important references might be the followings:
http://www.devx.com/codemag/Article/33655/0/page/6
http://msdn.microsoft.com/en-us/magazine/cc163357.aspx
http://msdn.microsoft.com/en-us/library/ms733824.aspx
http://msdn.microsoft.com/en-us/library/aa347793.aspx
8. ASP.NET Web Service and WCF
 8.1 WCF uses uses Contract attributes to specify which classes, operations and data members to be serialized or changed to XML. Web Service uses XMLSerializer to transform data into XML.
8.2 Web Service uses [WebService] and [WebMethod] attributes to expose services. WCF uses [ServiceContract], [DataContract], [OperationContract] and [DataMember] attribues to implement a service.
8.3 Web Services can only be hosted in Web Servers whereas WCF can be hosted using Console Application, Windows Application, Windows Service and Web Application.
8.4 WCF has improved exception handling then traditional web servies.
5.5 More technical details at http://msdn.microsoft.com/en-us/library/aa738737.aspx
9. Invoking WCF asynchronously
When adding service reference using visual studio, there is an Advance button at the left bottom of the Add Service Reference screen. If you click this button, you will see Service Reference Settings window. The first CheckBox allows the service to be called asynchronously. There is no coding involved to generate asynchronous proxy code. Visual studio facilitates this process. The only code change required is when calling the Service from within the client.
10. Exception Handling
You can find an excellent article on exception handling in msdn website (http://msdn.microsoft.com/en-us/library/ff650547.aspx). But let me  describe in brief about WCF exception handling in this section anyway. Since WCF Service communicates with clients using XML, the exception needs to travel in xml format as well with defined types. Using datacontract we can define custom data type or class that will hold the exception message and return to the client as exception. FaultContract attribute facilitates this functionality in WCF.  The above given msdn link provides examples of how it works. For more examples please visit the following links:
http://www.c-sharpcorner.com/UploadFile/ankithakur/ExceptionHandlingWCF12282007072617AM/ExceptionHandlingWCF.aspx
http://blogs.microsoft.co.il/blogs/sasha/archive/2008/04/12/automatically-converting-exceptions-to-wcf-faults.aspx
http://blogs.microsoft.co.il/blogs/sasha/archive/2008/04/12/automatically-converting-exceptions-to-wcf-faults.aspx
End of WCF Course.


Responses

0 Respones to "WCF Training Step-By-Step"


Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar