Pages

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

Tuesday, February 8, 2011

Creating a WCF Web Service with VS2010 Express

Last night while I was reading up on OPC-XML the interwebs took me on a merry trail of SOAP, XML-RPC and the like that ended with WCF Web Services. I found a very good tutorial on WCF Services at http://www.xvpj.net/2008/03/08/wcf-step-by-step-tutorial/ but this was for Visual Studio 2005. I only have express versions of Visual Studio 2010 so there were some things that needed to be done differently. In the interests of posterity here is how I wrote a very simple WCF web service and a WPF client that accesses it using only Visual Web Developer 2010 Express and Visual C# 2010 Express.

Configure the Development Environment

  1. Install Microsoft Visual C# 2010 Express
  2. Install Microsoft Visual Web Developer 2010 Express installed (you can download all Express editions on one iso image at http://www.microsoft.com/express/Downloads/#2010-All)
  3. Enable Windows features:
    1. IIS Metabase and IIS 6 configuration compatibility
    2. IIS Management Console
    3. ASP.NET
        iis_features
  4. In IIS Manager, under Application Pools right click DefaultAppPool, select Basic Settings then change .NET framework version to v4.0.x
    iis_manager
  5. Install Windows SDK. This can be downloaded from http://www.microsoft.com/downloads/details.aspx?FamilyID=c17ba869-9671-4330-a63e-1fd44e0e2505&displaylang=en 

Create the Web Service

  1. First we will create the web service. To do this we need to run Visual Web Developer 2010 Express with administrator privileges so hit the start button type in “web dev” or similar and when Web Developer is highlighted press ctrl+shift+enter. This will start it as an administrator and show the UAC prompt. Alternatively locate Web Developer in the start menu then right click and select run as administrator.
  2. Select File –> New web site and choose WCF Service and name it MultiplyService
    new_web_site
  3. Add code App_Code / IService.cs  
    IService
  4. Add code to App_Code / Service.cs
    Service
  5. Run the service by pressing ctrl F5 and click the Service.svc link in the page that opens. Nothing much to see here yet, you need a client to view this data. As indicated on the page you need to run the svcutil.exe utility to generate code that will be used by the client application
    svcutil1

    The svcutil.exe utility is installed with the Windows SDK and can be found at c:\Program Files\Microsoft SDKs\Windows\v6.0a\bin

    To create the Service.cs file on the desktop try the following in a cmd prompt:
    svcutil2 
  6. That ends the WCF service. Leave all of this running, including the internet explorer window that Web Developer opened and open Visual C# Express to start on the client application.

 

Create the Client Application

  1. Start up Visual C# 2010 Express and select File –> New Project. Select WPF Application and name it MultiplyClient.
  2. Add a Service Reference
    service_ref

    In the Service Reference dialog paste in the address from the internet explorer window that web developer opened. Select the service and select OK
    Service_ref2
  3. Copy the Service.cs file on the desktop that was generated by svcutil into the root folder of the project
    add_cs
  4. Add two entry textboxes, a multiply button and a result textbox to the MainWindow.xaml
    mainwindow
  5. Add code to MainWindow.xaml.cs to call the service when the multiply button is clicked
    mainwindow2
  6. Modify the app.config file. Simply change the contract value from “ServiceReference1.IService” to “IService”
    appconfig
  7. Press ctrl+F5 to run the WPF application. Enter two values to multiply and hit the Multiply button, you should see the answer in the result textbox!
    clientapp

 

References

  1. The basic gist of WCF services:
    http://www.xvpj.net/2008/03/08/wcf-step-by-step-tutorial/
  2. Adding IIS features:
    http://www.howtogeek.com/howto/windows-vista/how-to-install-iis-on-windows-vista/
  3. Where to find the svcutil.exe utility:
    http://www.dotnetspider.com/forum/239950-Where-find-svcutil-exe.aspx

Tuesday, November 16, 2010

Introduction to Windows Presentation Foundation

Introduction to Windows Presentation Foundation

Overview

The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.
WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.
The followinig illustration gives you an overview of the main new features of WPF

Separation of Appearance and Behavior

WPF separates the appearance of an user interface from its behavior. The appearance is generally specified in the Extensible Application Markup Language (XAML), the behavior is implemented in a managed programming language like C# or Visual Basic. The two parts are tied together by databinding, events and commands. The separation of appearance and behavior brings the following benefits:
  • Appearance and behaviour are loosely coupled
  • Designers and developers can work on separate models.
  • Graphical design tools can work on simple XML documents instead of parsing code.

Rich composition

Controls in WPF are extremely composable. You can define almost any type of controls as content of another. Although these flexibility sounds horrible to designers, its a very powerful feature if you use it appropriate. Put an image into a button to create an image button, or put a list of videos into a combobox to choose a video file.
 
>
 
 

Highly customizable

Because of the strict separation of appearance and behavior you can easily change the look of a control. The concept of styles let you skin controls almost like CSS in HTML. Templates let you replace the entire appearance of a control.
The following example shows an default WPF button and a customized button.

Resolution independence

All measures in WPF are logical units - not pixels. A logical unit is a 1/96 of an inch. If you increase the resolution of your screen, the user interface stays the same size - if just gets crispier. Since WPF builds on a vector based rendering engine it's incredibly easy to build scaleable user interfaces.

What is the WPF architecture?

1. What is the WPF architecture?

The WPF (WorkSpace-Project-Files) architecture is just a way to organize your work in a pyramidal hierarchy starting from the base with grammar files and ending at the top with the workspace. Between them you will find projects and folders. The complete hierarchy is as follows: Only one workspace can be opened at the same time. The workspace contains projects. Each workspace can have as many projects as you want. Each project has three folders: Source Files, Description Files and Setting Files. Each folder contains as many files as you want.
Organize your work with the WPF (WorkSpace-Project-Files) architecture, may seem useless at the beginning, but it turns extremely powerful when you get used to it.

The Architecture of WPF( Windows Presentation Foundation )

The Architecture of WPF( Windows Presentation Foundation )


The above diagram explains the WPF architecture.
Presentation Framework, including large number of standard controls i.e. Button, Label, Menu, panels, and other types of controls. The vast majority of Windows Presentation Foundation developers will work exclusively with this layer.
PresentationCore.dll includes base types, such as UIElement and Visual, from which all shapes and controls derive.
WindowsBase.dll includes even more basic things that have the potential to be reused outside of WPF, such as DispatcherObject and DependencyObject,
Milcore.dll is the core of the WPF rendering system and the foundation of the Media Integration Layer (MIL). Its composition engine translates visual elements into the triangle and textures that Direct3D expects. Though milcore.dll is considered a part of WPF, it’s also an essential system component for Windows Vista. The Desktop Window Manager (DWM) in Windows Vista uses milcore.dll to render the desktop.
WindowsCodecs.dll is a low-level API that provides imaging support (e.g., processing, displaying, and scaling bitmaps and JPEGs).
Direct3D is the low-level API through which all the graphics in a WPF are rendered.
User32 is used to determine what program gets what real estate. As a result, it’s still involved in WPF, but it plays no part in rendering common controls. 
At the lower most level you have the Kernel, your graphics drivers etc.

Introduction to XAML in WPF

Introduction to XAML

XAML stands for Extensible Application Markup Language. Its a simple language based on XML to create and initialize .NET objects with hierarchical relations. Altough it was originally invented for WPF it can by used to create any kind of object trees.
Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF and for electronic paper in the XPS standard.
All classes in WPF have parameterless constructors and make excessive usage of properties. That is done to make it perfectly fit for XML languages like XAML.

Advantages of XAML

All you can do in XAML can also be done in code. XAML ist just another way to create and initialize objects. You can use WPF without using XAML. It's up to you if you want to declare it in XAML or write it in code. Declare your UI in XAML has some advantages:
  • XAML code is short and clear to read
  • Separation of designer code and logic
  • Graphical design tools like Expression Blend require XAML as source.
  • The separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.

XAML vs. Code

As an example we build a simple StackPanel with a textblock and a button in XAML and compare it to the same code in C#.
 
>
     Margin="20">Welcome to the World of XAML>
    >
>
 
 
The same expressed in C# will look like this:
 
// Create the StackPanel
StackPanel stackPanel = new StackPanel();
this.Content = stackPanel;
 
// Create the TextBlock
TextBlock textBlock = new TextBlock();
textBlock.Margin = new Thickness(10);
textBlock.Text = "Welcome to the World of XAML";
stackPanel.Children.Add(textBlock);
 
// Create the Button
Button button = new Button();
button.Margin= new Thickness(20);
button.Content = "OK";
stackPanel.Children.Add(button);
 
 
As you can see is the XAML version much shorter and clearer to read. And that's the power of XAMLs expressiveness.

Properties as Elements

Properties are normally written inline as known from XML
 
.Content>
>
 
 

Implicit Type conversion

A very powerful construct of WPF are implicit type converters. They do their work silently in the background. When you declare a BorderBrush, the word "Blue" is only a string. The implicit BrushConverter makes a System.Windows.Media.Brushes.Blue out of it. The same regards to the border thickness that is beeing converted implicit into a Thickness object. WPF includes a lot of type converters for built-in classes, but you can also write type converters for your own classses.
 
 BorderBrush="Blue" BorderThickness="0,10">
>
 
 

Markup Extensions

Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime. Markup extensions are surrouded by curly braces (Example: Background="{StaticResource NormalBackgroundBrush}"). WPF has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension. These are the built-in markup extensions:
  • Binding
    To bind the values of two properties together.
  • StaticResource
    One time lookup of a resource entry
  • DynamicResource
    Auto updating lookup of a resource entry
  • TemplateBinding
    To bind a property of a control template to a dependency property of the control
  • x:Static
    Resolve the value of a static property.
  • x:Null
    Return null
The first identifier within a pair of curly braces is the name of the extension. All preciding identifiers are named parameters in the form of Property=Value. The following example shows a label whose Content is bound to the Text of the textbox. When you type a text into the text box, the text property changes and the binding markup extension automatically updates the content of the label.
 
 x:Name="textBox"/>

Namespaces

At the beginning of every XAML file you need to include two namespaces.
The first is http://schemas.microsoft.com/winfx/2006/xaml/presentation. It is mapped to all wpf controls in System.Windows.Controls.
The second is http://schemas.microsoft.com/winfx/2006/xaml it is mapped to System.Windows.Markup that defines the XAML keywords.
The mapping between an XML namespace and a CLR namespace is done by the XmlnsDefinition attribute at assembly level. You can also directly include a CLR namespace in XAML by using the clr-namespace: prefix.
 
 xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”>
>
 
 

WCF Basics

WCF
  • Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows.
  • Windows Communication Foundation (WCF) is a platform, a framework if you will, for creating and distributing connected applications.
  • Building services is significantly easier with WCF
  • WCF provides interoperability between services.
  • Most all of the WCF functionality is included in a single assembly called System.ServiceModel.dll in the System.ServiceModel namespace.
  • WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it:
    • Windows Vista (client and server),
    • Windows XP SP2, and
    • Windows Server 2003 SP1
    • Windows Server 2008

Layered architecture of Windows Communication Foundation:

Understanding The Basics Of WCF services

Click Here

The aim of this article is to explain the basics of WCF in a manner as simple as possible.
It is assumed that the reader doesn’t know anything about WCF or .NET 3.0, however he/she is expected to know .NET 2.0 and/or simple facts like what is a web service.
While writing this article (or any other) I always try to avoid difficult technical words, which may confuse the reader. I have tried to put it in as simple words as possible.
At the end of this article, I would hope you understand at least some of the key WCF areas and possibly be inspired enough to try out a project on your own.


Buy proven .NET Trainings on www.ITFunda.Com (Adv)
1.Introduction


The aim of this article is to explain the basics of WCF in a manner as simple as possible.It is assumed that the reader doesn’t know anything about WCF or .NET 3.0, however he/she is expected to know .NET 2.0 and/or simple facts like what is a web service.While writing this article (or for any other) I always try to avoid difficult technical words, which may confuse the reader. I have tried to put it in as simple words as possible.At the end of this article, I would hope you understand at least some of the key WCF areas and possibly be inspired enough to try out a project on your own.
2.Contents
1. Introduction
2. The most suitable reader for this article.
3. Prerequisites
4. A brief overview of demo service
5. Explanations of fundamentals involved
6. The demo Service with code
7. Conclusion


The Most suitable reader for this article
Any .NET Developer who wants to start with WCF can be most benefitted from  this article.
3. Prerequisites
 To run the code supplied with this article you need to install .NET 3.0 API   available with Visual Studio 2008.

4. A brief overview of demo service


In this demo WCF service we are trying to carry out the following functionality:
a)     Create a service
b)    Host the service
c)     Create a client for the service
d)    Let the client interact with the service.
To achieve the above functionality we will create three inter related assemblies as mentioned below:
     a)   SampleService.dll – this is the actual WCF service that allows clients to connect
b)   SampleHost.dll – this is the dll that hosts WCF service, SampleService.dll
c)   SampleClient.dll – this is the client assembly which communicates with SampleService.dll.

          Note that the programming language used here is C#.

5. Explanations of fundamentals involved

Assuming that the reader has no Background in WCF, there are a number of key concepts that needs to be explained in order for the full application to be understood.
So I will just explain each of these a little bit at a time, so that the final application will be a little easier to understand.

Key Concepts:
a) What is WCF?
WCF stands for Windows Communication Foundation.
WCF is advanced API (Application Programming Interface) for creating distributed applications using .NET framework.
It is introduced in .NET 3.0.
Distributed system in its simplest form is two executable running and exchanging data.
WCF API is found in System.ServiceModel namespace.
WCF is based on basic concepts of Service oriented architecture (SOA)

b) What is a WCF Service?
         A WCF service is a program that exposes a collection of Endpoints (connections) for communicating with either client applications or other service applications.       
c) What are the components of WCF application?
                          There are three main components of a WCF application
i)      a WCF service
ii)     a WCF service host
iii)     a WCF service client
         d) What is the “ABC” of a WCF Service?
“ABC” of WCF stands for addresses Bindings and contracts respectively.
                i) Addresses:   This is location of the service in the form of an
                URI (Uniform resource Identifier) generally mentioned
                In the config file.

                ii) Bindings: This includes the type of network protocol  used by the
                Service. For Example HTTP, TCP/IP or others.
               
                iii) Contracts:  This is in fact the methods exposed by the WCF service.

e) What is a Service Contract in WCF application?
Service contract is the name of the attribute which is applied to an interface in   a WCF service.


f) What is an Operation Contract in WCF application?
Operation contract is the name of the attribute which is applied to a   method inside the interface of a WCF service


6. The demo Service with code

Before I start, I would like to remind you again that this is the simplest of WCF service only for understanding purpose. In real world you might have to build/face much more complicated WCF service.

I have divided this part in five sub-parts as below.
a) Building the WCF service
b) Building the WCF host
c) Building the Proxy to be used by client
d) Building WCF client
e) Testing the working of the whole application. 


a) Building the WCF service 

To understand the service better we will build the service as a c# class library project. Follow the following steps:

In my case it created the class1.cs with content as below.
         i)   Open Visual Studio 2008
ii)  Select Create ProjectàC# class library name it “Sample Service”
iii)  It will crate a .cs file in the project. Open that file.

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

namespace SampleService
{
    public class Class1
    {

    }

}

Change the namespace SampleService to SampleServiceLib,
Rename the Class1 to SampleService.
Rename the Class1.cs file in the solutionExplorer to SampleService.cs
Add the namesapce using System.ServiceModel at the top.

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


namespace SampleServiceLib
{
    public class SampleService
    {
    }
}
The SampleService.cs file should now look like below.

iv) At this point the project will not build, so please add a reference to System.Service Model.
For this, Go to solution Explorer ,Right click on the reference Add Reference .NET Tab Select System.ServiceModel  OK.

  Now you can successfully build the Project.

v) Create an interface named IAnswer in this file inside  SampleServiceLib namespace.Create a method inside the interface IAnswer, named ObtainAnswer The attributes for the interface and the method should be ServiceContract and OperationContract respectively

         vi) Implement the IAnswer  interface in SampleService class as

Shown in the code sample below.
 namespace SampleServiceLib
{
    public class SampleService : IAnswer
    {
       public string ObtainAnswer(string Question)
        {
return "My Profession is Software Development";

        }
    }

    [ServiceContract]
    public interface IAnswer
    {

        [OperationContract]
        string ObtainAnswer(string Question);

    }

}

vii)   Now ad a constructor to the class SampleService and the final code should look like this.Build this project. 


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

 

namespace SampleServiceLib
{

    public class SampleService : IAnswer
    {

        public SampleService()
        {
Console.WriteLine("Ask question to SampleService....");

       }

        public string ObtainAnswer(string Question)
        {

            return "Your Profession is Software Developer";

        }

    }

 

    [ServiceContract]
    public interface IAnswer
    {

        [OperationContract]
        string ObtainAnswer(string Question);
    }

}


 viii) Save the sample service Project by File Save All. Then build it so that you will get a SampleSevice.dll in its bin\release directory.


 b) Building the WCF host

A WCF host may be IIS (Internet Information Server) , Windows Service, A console application etc.The simplest of them is a console application host. So we will demonstrate that here.
Follow the following steps: 
i) Open Visual Studio 2008
ii) Select Create ProjectàC#  Console Application name it “Sample Host”
iii) From Solution Explorer,Add the reference of System.ServiceModel to this project as before and
iv) also add the reference of SampleServiceLib.dll from SmpleService Class library project you created before by addreference Browse Tab Browse to the    SampleServiceLib.dll in the project SampleService’s Bin/release folder.
v) Open its Program.cs file and add the following two namespace to the

Using Section.
Using System.ServiceModel
Using SampleServiceLib

vi)               Build the project successfully.
vii)             Add the following console.Writeline codes to program.cs so that the final Program.cs Should look Like as below.

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

namespace SampleHost
{
   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Sample Host of Sample Service is running....");
            using (ServiceHost servicehost = new ServiceHost(typeof(SampleService)))
            {
                servicehost.Open();
                Console.WriteLine("The SampleService is ready now...");
                Console.WriteLine("Press enter to terminate the SampleService...");

            }
            Console.ReadLine();
        }
    }
}


viii) Adding the config File to the Host :
                Go to the Solution Explorer of the Sample Host
          Right Click Add New Item Application Configuration File
          A file named app.config will be added to the solution.
          Initial content of the file is given below


          

        

     

ix)               Add the code inside the configuration tag of app.cofig so that the final app.cofig should look like as below 

 



  

 

 

    

      

        

      

        

        

          

            

 

          

 

 

        

 

      

 

    

 

 

    

      

        

         

          

        

      

    

 

 

  

x)                 Build the Service host application and run it. You should get a console Window while host is running.


c)     Building the Proxy to be used by client

Before building a client you need to build a proxy of the service which the client will use to interact with the service.
A proxy is nothing but a .cs file and a .config file generated by a tool called svcutil.exe using your service Sampleservice.dll
Steps to create the Proxy:
i) Create a Proxy folder in your c:\ drive.
ii) Search for the svcutil.exe file on your computer and copy it to the Proxy folder.
iii) Copy the dll of the service you created (sampleservice.dll) to this Proxy folder.
iv) Go to Start Run cmd
v)  On the command prompt change the directory to Proxy folder.
vi)  Run the following command
C:\ Proxy  svcutil.exe SampleService.dll
This will create a few files in the current directory like
.wsdl, .xsd etc
vii)  The run the following command
C:\ Proxy svcutil.exe *.wsdl *.xsd  /language:C# 
      /out:SampleProxy.cs /config:app.config
       It will create two files in the Proxy folder
SampleProxy.cs and app.config.
These are your proxy files to be used in the Client.
viii)  Open the SampleProxy.cs file, it has the AnswerClient class which has the ObtainAnswer Method from SampleService.
d)    Building WCF client

i)    Open Visual Studio 2008
ii)   Select Create ProjectàC# Console Application name it “SampleClient”
iii)  From Solution Explorer,Add the reference of System.ServiceModel to  the project as before. 
iv)  Add the two proxy file SampleProxy.cs and app.config to the solution.
v)   Open the app.config File .You will find that inside of client Tag,the endpoint tag does not have “address” attribute.
vi) add the attribute address="
http://localhost:8080/SampleService" to the endpoint tag of the app.config file.
vii) Now add code to Program.cs so that final Program.cs should look like as below
    

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

 

namespace SampleClient
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Ask question");
            //the name AnswerClient is generated autometically by svcutil.exe tool which creates
           //chat proxy and app.cofig
            //by browsing the service url after reference.

            using (AnswerClient client = new AnswerClient())
            {
                Console.WriteLine("Your Question:  ");
                string question = Console.ReadLine();
                string answer = client.ObtainAnswer(question);
                Console.WriteLine(answer);
                Console.ReadLine();
            }

 

        }

    }

}

 viii) Build the application. Now the client is ready. 

e)     Testing the working of the whole application

To Test the service follow the steps below.
i)  Run the Sample Host  Application
ii)  Run the client application
iii)  Write the following question on client console “What is my Profession”
iv)  The reply fro service will come as “Your Profession is Software Developer.”
Conclusion

I have enjoyed writing this WCF Service article and I hope you will enjoy reading it. In real world you may have to face far more complicated WCF services than this sample.
You can contact me by clicking my blog link below.

WCF Binding

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.
Binding has several characteristics, including the following:
  • TransportDefines 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

WCF Hosting

In this part of the tutorial we are going to see the four different way of hosting the WCF service. WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process. As we discussed there are mainly four different way of hosting the WCF service.
Multiple hosting and protocols supported by 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,net.tcp,net.pipe,net.msmq
A summary of hosting options and supported features.
Feature Self-Hosting IIS Hosting WAS Hosting
Executable Process/ App Domain Yes Yes Yes
Configuration App.config Web.config Web.config
Activation Manual at startup Message-based Message-based
Idle-Time Management No Yes Yes
Health Monitoring No Yes Yes
Process Recycling No Yes Yes
Management Tools No Yes Yes

WCF-Architecture with Screen Shot

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).

Wednesday, November 3, 2010

WCF Basics

WCF (Window Communication Foundation) is a solution for developers to work in distributing environment. WCF mainly for make communication between applications. Before WCF, the technologies to make communication between applications were ASMX, .NET remoting, and COM+. WCF provides a common platform for all .NET communication.

WCF is a framework for developing, configuring, exposing, and hosting services. All service providers were agree on SOAP concept for making communication between application before WCF. The idea of WCF is a combination of SOAP and web service.

There are two categories of classes in WCF.

  • Service model classes handle configuration and validation.
  • Channel layer classes handle things such as communication and data transformation.

WCF services expose functionality through one or more endpoints. Clients communicate with the service's endpoint. In configuring an end points there are three components require.

  • Address
  • Binding
  • Contract

These three components are interrelated.

An address mean an URL.

Binding tells the WCF runtime how your endpoint communicates.

Contracts mean it gives the information of working endpoints.

With the help of XML-based config information we can configure an end point, programmatically using methods/properties, or with both XML config files and some coding. WCF includes multiple usability avenues. For example, we can use WCF out of the box with little or no coding or elect to build custom implementations for all aspects of your service.

In making communication channels plays an important role, the WCF runtime detects the binding for creating the channels. The main task of channel are receiving and transforming data. Data goes in one end of the channel, the channel operates on the data, and new data is dumped out the other end of the channel.

Basic WCF Concept and Terminologies

In the past when distributed computing started there has been many methodologies used for achieving this right from COM+, Remoting , Web Services and now its WCF which is a part of .net framework 3.0.



WCF(Windows Communication Foundation) is most recent evolution in this field. First question comes in mind is that why this WCF is introduced instead of promoting Web services and remoting? Simple answer is that drawbacks in these two are covered in WCF. In Remoting we must have both client and remoting component should be developed in dotnet and we can only use HTTP or TCP protocol. Web services are platform independent and protocol used for web services is SOAP over HTTP. In WCF we have support of almost all protocols , WCF service can be hosted on self hosting application,IIS and WAS(windows application service). WCF also supports transaction management . WCF is used to implement Service oriented architecture which is widely required in current trend as application required to communicate with other applications. Service oriented architecture means collection of services communicated with each other with the help of messages.

WCF services can have n number of end points. end points are the pointers with the help of which client knows where service is located(Address) and how to access that service(binding) and what operations are available for accessing this service(Service contract). This is ABC's of WCF(Address,Binding and Contract) . Client only knows end point and does not know about the service this is loosely coupled architecture in which if we change the service we need not have to change the client as client accesses the service only with the help of end point.

Building WCF application there are two steps



1) Build Service layer: In this we need to define various contracts

Service Contract : It will define which operation to be available for invoking when service receive request from client

Data Contract : define the structure of data to the transferred from Client to service

Message Contract : enable us to control the headers that
appear in the message and how the messages are structured.

2) Create Proxies : Proxy classes to be created from service metadata.There are various methods to create proxies e.g using svcutil command line utility, from Visual Studio, by defining manually and dynamical proxy creation

3) Create Client application : Client application need to be created in order to consume the services This step also include creating the configuration files.

 

Web Design Company karimnagar, Web Designing warangal, Logo Design Company nizamabad, Indian Website Design Company, maddysoft.co.in