4 Simple Steps to Consume WCF Service using Silverlight

4 Simple Steps to Consume WCF Service using Silverlight

Video demonstration One Way, Two Way and One Time Bindings using Silver light


This article will talk about 4 simple steps which will assist you to consume WCF service in a Silverlight application. It also has a simple sample source code which demonstrates all the 4 steps practically.

I have collected around 400 FAQ questions and answers in WCF, WPF, WWF, SharePoint, design patterns, UML, etc. Feel free to download these FAQ PDFs from my site http://www.questpond.com.

Step 1: Create Your WCF Service

The first step is to create your WCF service. When we create a WCF service, by default it creates ‘GetData’ function which takes in an integer value and returns back a string saying “You entered 10” , in case you passed ‘10’ as value to the function. We will try to consume this service in Silverlight in the coming steps:

public class Service1 : IService1
    public string GetData(int value)
        return string.Format("You entered: {0}", value);

Step 2: Enable Cross Domain for Your WCF Service

For this example, our WCF service and the Silverlight web application will be hosted in different IIS websites. In other words, they will be hosted in different domains. When we talk about different website, in other words they are hosted in different domains. For instance, it’s possible that your Silverlight web application is hosted in one domain like www.xyz.com  and your WCF service is hosted in different domain i.e. www.pqr.com.

The WCF service needs to enable cross domain facility so that other domains can consume the WCF service.

Figure: Cross domain

We need to create two XML files (clientaccesspolicy.xml and crossdomain.xml) in the root directory of the WCF service to enable cross domain functionality.
Below is the XML code snippet for clientaccesspolicy.xml:

<?xml version="1.0" encoding="utf-8" ?>
<allow-from http-request-headers="*">
<domain uri="*"/>
<resource include-subpaths="true" path="/"/>

Below is the XML code snippet for crossdomain.xml:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM 
<allow-http-request-headers-from domain="*" headers="*"/>

Step 3: Add the WCF Service Reference

Create a simple Silverlight application and add the service reference to your Silverlight project. In order to call the WCF service, we need to define event handlers.

To consume the WCF service is a three step procedure.

  • In the first step, refer to the name space.
  • In the second step, create the object of your WCF service.
  • In the final step, we need to create an event handler which will get the results sent by the WCF service.

One of the important points to note is that the function ‘GetData’ is called asynchronously.

Step 4: Call the Service

Finally compile the program and enjoy the output.

A Simple Sample: WCF Service


This article discusses the simplest way to write, configure and consume Windows Communication Foundation (WCF) service, using Visual Studio 2010. This would help gain a better understanding to WCF services which is slightly different from ASP.NET web services.


We would look into writing and consuming a simple service using VS2010. Scenario: Book store service that would fetch the book information. At the end of the article you would know:

  • How to build a WCF service
  • How to consume WCF service in Windows Forms
  • How to bind custom object with DataGridView
  • How to configure WCF Service while publishing
  • How to convert XElement to custom object using LINQ

Also you might be interested in Why use MessageContract when DataContract is there?; an article that I wrote some time back. Btw, we will use both in this example.

Steps to Follow

Lets create a WCF Service Library project. Visual Studio 2010 stubs-in a default service which it calls Service1.  Lets ignore this existing service for a while now. We would create a separate service that would return the list of books requested by the client end.

Note that to just to keep things simple, we would use XML file as our data store; taken from MSDN

The XML has columns: Author, Title, Genre, Price, Publish Date, Description, and Book ID.

The Book ID, which is a string shall be used as primary key to identify the book.

We would add an book interface that shall define what this service provides as book service. So, we want to provide a service that returns the list of books found based upon user criteria.

Add a new item as interface called IBookService under namespace Store. Add the directive, using System.ServiceModel;
Decorate the interface with service contract attribute as [ServiceContract].

We want the following functionality as a scope of this sample:

  • List of all books
  • Filter functionality; return a book or a list of books given its ID or Title or Genre or Author

Note that we will also look into the .NET default/optional arguments functionality that is provided in C# v4.0, as a part of this sample while we implement the above methods.

The interface shall contain the methods

Let’s define the operations for IBookService interface:

namespace Store
    interface IBookService
        List GetAllBooks();//Get all books; returns list of books

        List GetBookByID(string BookID);//Gets a(single) book by ID

        List Filter(string Author, string Genre, string Title); //Returns list of books by specified filter

Lets add a Book type and define the attributes of the book that we want for the client to have. For now its all those attributes that are there in the XML data.

Right click on the Book return type, and select Generate Class for Book. This shall generate the class of type Book. Note that you also write the attributes where it is to be used and VS shall add those attributes in the class automatically.


FIG1: Book service interface

If you select the generate new type it will show the following window and provide you with the options about class. Its Access specifier, Kind (class, struct, etc), and either to create a new file and stub the code in the current file. We would select a separate file.

FIG2: Add Book data type

Right click on the Book return type and select Goto Definition.

Add the directive using ServiceModel, and using System.Runtime.Serialization;. And DataContract attribute on Book class; it would look like following:


FIG3: List of book attributes, similar to XML element attributes.In figure 3, note that the ID is of type string, ideally ID’s should be of integer type, when using as primary keys, integers keys works faster than the string keys. The reason we are using the string type primary key, is that we have string data in the XML data store.

Lets decorate the Book class with DataContract attribute.

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts.

Lets add the types that are required ID, Title, Author, Description, Genre, Price, and Publish Date and tag all members with[DataMember] attribute.

Now we will add a class BookService that implements the IBookService interface;

The book service shall contain the definition


FIG4: Implement book service interface

Note, in case if you plan on using the database(and not the xml which is a part of this example), you can use Enterprise Library, Data Application Block for your data transactions; you will need to add a reference to the Data.dll file, generally available in the DRIVE:\Program Files\Microsoft Enterprise Library 4.1 – October 2008\Bin.

Now lets add the implementation of the methods. First, there this is a small GetDb() method, that loads the data from given XML and into the XDocument object.

Then, since we interested in the book nodes, therefore we select all the books.

The select new Book() creates a new object and copies the data from book attribute into our defined book object attribute. So by the end of the book structure “}” is complete we have our book object ready to be inserted into the List object.

Implementing both the methods using XDocument and LINQ, answers the question, how to convert XElement to custom object using LINQ.

public List GetAllBooks()
    XDocument db = GetDb();
    List lstBooks
        (from book in db.Descendants("book")
         select new Book()
             ID = book.Attribute("id").Value //Get attribute from XML and set into the Book object attribute.
             Author = book.Element("author").Value
             Genre = book.Element("genre").Value
             Price = Convert.ToDecimal(book.Element("price").Value)
             Description = book.Element("description").Value
             PublishDate = Convert.ToDateTime(book.Element("publish_date").Value)
             Title = book.Element("title").Value
         }).ToList(); //Cast it into the list

    return lstBooks;

The above is the method that gets all of the books in the datastore. Now, lets add the definition for GetBookByID(). The method is same as get all books, except for the where clause. Note that, this shall be only one book in this case, so the list shall contain only one item.

public List GetBookByID(string BookID)
    XDocument db = GetDb();

    //Howto: Convert XElements to Custom Object
    List lstBooks =
        (from book in db.Descendants("book")
         where book.Attribute("id").Value.Equals(BookID)
         select new Book() //Instantiate a new object 
             ID = book.Attribute("id").Value
             Author = book.Element("author").Value
             Genre = book.Element("genre").Value
             Price = Convert.ToDecimal(book.Element("price").Value)
             Description = book.Element("description").Value
             PublishDate = Convert.ToDateTime(book.Element("publish_date").Value)
             Title = book.Element("title").Value

    return lstBooks;

The above code gets a book given its ID using LINQ.

Configuration and Deployment

Add the service definition in app.config file under system.serviceModel/services tag.

The system.serviceModel/services tag contains the classes, enumerations, and interfaces necessary to build service and client applications that can be used to build widely distributed applications.

<service name="Store.BookService">
        <endpoint binding="basicHttpBinding" contract="Store.IBookService"></endpoint>

basicHttpBinding Represents a binding that a service can use to configure and expose endpoints that are able to communicate with ASMX-based Web services and clients and other services that conform to the WS-I Basic Profile 1.1 [^] . Contract is the name of the interface that we expose.

Note that a WCF service requires an application host, in order to run and be accessible to clients.

We have couple of options here, for instance:

  • Create a custom host application
  • Build a Windows service application
  • Using IIS

In our case we would use IIS to simply publish the service.

Right click on the project and select Publish, would generate following directory structure in IIS.

Fig5: Configure WCF Service in IIS

Just for your interest, if you are using a version prior to VS2010 to configure a WCF service, following is the manual process.

  • Ensure that you have the binary files being built inside the \bin folder, rather than \debug or \release folder.
  • Add a service definition file, a file having .svc extension.
  • Add a new item, select the Text File template; rename the file to BookService.Svc. This shall contain the service definitions.

Fortuntely Visual Studio 2010 does that for us.

We also need to tell the IIS that our service is going to use the .NET Framework version 4.0. So that it does not use its default .NET framwork.

Fig6 shows how to change the framework that IIS is going to use for our app.

Fig6: Change app’s framework in IIS

Publish in IIS

In order to be able to be accessible to the outside world, we need to allow access. You can open the url in IE and see it works. In my case, for instance, I have it under WCF folder http://localhost/WCF/Store.BookService.svc.


FIG7: Open service url in the browser

Note the highlighted text in the above image. This requires a service behavior to be added in the config file, which Visual Studio 2010 stubs in for us automatically.

You will need to set the httpGetEnabled attribute to true, in order to publish your service metadata. Its a Boolean value that specifies whether to publish service metadata for retrieval using an HTTP/Get request. The default is false.

To save and publish the service into IIS, click on


Now you can open the url again in IE, and you should be able to see your service’s meta.

Fig8: Book service in IE Quick way to see the wsdl, type ?wsdl in the address bar to see the wsdl, like:http://localhost/WCF/Store.BookService.svc?wsdl

Fig9: Book service WSDL listing

How to Consume WCF Service?

We would create a small forms based client app, that would show a couple of filter options, and provide a search button that requests the service for books based upon the filter provided by the user.

Add a Windows Forms project and design the form.

Fig10: Client user interface (UI) To be able to consume the service we will need to add a reference to that service. So when you try to add the service reference, the IDE discovers all the services on your system. Alternatively, you can provide the path that you have of the service.

Note that web services, by nature, are of public type. Though, WCF adds the Service, Message, and Data level contracts; but the service itself is public.

So Right click on the WCF Client project and add a service reference. In your client app, add the service reference.

Add following as the service reference uri: http://localhost/WCF/Store.BookService.svc?wsdl. I would rename the reference toSvcBookstore.

Fig11: Client user interface (UI)

Since, at this point, we have already added the service reference, therefore we can access it by adding the using directive in the forms class, and then declaring the object of the service; exactly similar to how we add/declare other .NET objects. Lets declare the service object in our form. And addusing directives.

One important thing: What if you are in the middle of developing real world WCF Services, and now you want to test it. And while testing using a demo client app, your service is throwing exception that you have hell no idea of. So in that case, a “natural” scenario a developer wants is that you should able to “step into (F11)” the service code and see if for yourself. Thats is going be to a great help. So, if this is the case you can always go back to your service configuration file and add the a serviceDebug within behavior element.


serviceDebug allows the client app receive exception details in faults for debugging purposes, when set to true. DONOT, forget to set to falsebefore deployment to avoid disclosing exception information.

So, if you want to get the service related exception here at the client ends, add a tag in service. Because, at this point you might want to step into it.

Client Code

So, lets add the final code that collects the filter specified by the user, and call the service. When the data is retrieved, you can simply just assign object array to .DataSource property to show on Grid. Following the output of the client.

private void button1_Click(object sender, EventArgs e)
    //Get the combo choice, if there is any.
    string strGenre = cbxGenre.SelectedIndex > -1 ? cbxGenre.SelectedItem.ToString() : string.Empty;

    //Declare the books array; though the actual return type is List, it actually gets casted into
    //Book[] array.
    Book[] lstBooks = null;

    //Discard other filters, if user has entered a book id
    if (!string.IsNullOrEmpty(txtID.Text))
        lstBooks = bookService.GetBookByID(txtID.Text);
        //Lets get books by filter.
        lstBooks = bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre);

    //Set datasource, custom object.
    dataGridView1.DataSource = lstBooks;


Did you notice bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre); line in the code above?

Thats what the named arguments are. Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. Named arguments can follow positional arguments.

As an example, if at some point, for this client app, user only provides the Author to look for, you can provide only the author to this method. Like:bookService.Filter(Author: "Paulo Coelho");

Note that you will have to update the Service’s .Filter() method and provide the default arguments; for instance, like following:

public List<book> Filter(string Author = "N/A", string Genre = "N/A", string Title = "N/A")

FIG12:Output of client user interface (UI)

Points of Interest

Couple of things that I noticed is that WCF service is way different than an ASP.NET service. The file extensions are different as well. .asmx for ASP.NET and .svc for WCF. Also, after all that you have done above, and deployed your application and now you are wondering, WHY your service is taking time on the first load. Well, Why my service is slow on first access? might just help you.

Simple Web Service using WCF (Windows Communication Framework)


This article shows you how easy it is to setup a web service using WCF (Windows Communication Framework). Using the source I’ve provided as a template, you can quickly create your own web services. This article does not deal with a client consuming the web service (you will have to wait until part 2).


I’ve been playing around with WCF for a while, since the early CTP’s. I found it difficult to find good samples/examples. Either they didn’t work or I was either too lazy or too stupid to get them working. All I wanted was something that worked with very little effort (or understanding) on my part. I just wanted something I could install and get running!!!

Of course at some point everyone will have to understand the ABC’s (but that can wait for another day). When you start to learn a new technology, especially a Beta or CPT – you just want it to work, figuring out how it works can wait for another day…..

So I put together a simple WCF Web service, that you can just download and get running in a few minutes (for lazy developers – like myself!)

Getting Started

You are going to need Visual Studio 2005 (it might work with other versions of Visual Studio, but I’ve not tested in and I’m not going to!!), and .NET 3.0 (I would get the entire package from here instead).

Then just download the source from above.

Using the code

Download the example code and open up the solution in Visual Studio 2005.

The are two projects, the Web service and the Implementation of the class. [Fig 1]

Fig 1 – showing the 2 projects

I have chosen to use the dev web server that is built into Visual Studio, it’s just easier, less setup and mucking around. But there is no reason not to use IIS (if you know how to). When your code goes into production you will be using IIS, but for now I’m going to leave it alone.

There are two parts to the web service, the .svc file and the web.config.





The Service from the ServiceHost attribute in the WCFService.svc file should match one of the service names in the web.config. The service name and endpoint contract should both match the implementation and contracts from the WCF Project Template.

The WCF Project Template is made up of 3 parts, the contract [data contract or message], the implementation and the interface [ServiceContract] (yes, the ABC’s had to come in somewhere).

The Service Contract

The WCFContract.cs contains the interface for this service.

interface IEchoContract
EchoMessage Echo(EchoMessage Message);
The Data Contract

The Message which gets sent around is contained in the WCFContract.cs

public class EchoMessage
private string _OutMessage;
private string _ReturnMessage;

public string OutMessage
get { return _OutMessage; }
set { _OutMessage = value; }

public string ReturnMessage
get { return _ReturnMessage; }
set { _ReturnMessage = value; }
The Implementation

The implementation of the web service is in WCFImplementation.cs

class EchoImplementation : IEchoContract
public EchoMessage Echo(EchoMessage Message)
EchoMessage _returningMessage = new EchoMessage();

_returningMessage.ReturnMessage = Message.OutMessage;

return _returningMessage;
For this example, I used the EchoMessage to pass the data between the client and the web service, but this could be any class that has [DataContract] as an attribute.

Basic concept of WCF

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.

3 ways to do WCF instance management (Per call, Per session and Single)


WCF service object instancing

Per Call instance mode

How to implement WCF per
call instancing?

Per session Instance mode

How to implement per session

Single Instance mode

How to implement Single
Instance mode?

When should
you use per call, per session and single mode?

Per call

Per session



Source code





Many times we would like to control the way WCF service objects are
instantiated on WCF server. You would like to control how long the WCF instances
should be residing on the server.


WCF framework has provided 3 ways by which we can control the WCF instance
creation. In this article we will first try to understand those 3 ways of WCF
service instance control with simple code samples of how to achieve them.
Finally we will compare when to use under what situations.


This is a small Ebook for all my .NET friends which covers topics like
WCF,WPF,WWF,Ajax,Core .NET,SQL etc you can download the same from 
or else
you can catch me on my daily free training @
from here


WCF service object instancing


In a normal WCF request and response communication following sequence of
actions takes place:-

• WCF client makes a request to WCF service object.

• WCF service object is instantiated.

• WCF service instance serves the request and sends the response to the WCF

Following is the pictorial representation of how WCF request and response work.




Following are different ways by which you would like to create WCF

• You would like to create new WCF service instance on every WCF client method

• Only one WCF service instance should be created for every WCF client session.

• Only one global WCF service instance should be created for all WCF clients.

To meet the above scenarios WCF has provided 3 ways by which you can control WCF
service instances:-

• Per Call

• Per session

• Single instance


Per Call instance mode


When we configure WCF service as per call, new service instances are created
for every method call you make via WCF proxy client. Below image shows the same
in a pictorial format:-

• WCF client makes first method call (method call 1).

• New WCF service instance is created on the server for this method call.

• WCF service serves the request and sends response and the WCF instance is
destroyed and given to garbage collector for clean up.

• Now let’s say WCF client makes a second method call, again a new instance is
created, request is served and the WCF instance is destroyed.

In other words for every WCF client method call one WCF service instance is
created and destroyed once the request is served.




How to implement WCF per
call instancing?


In order to specify instancing mode we need to provide ‘InstanceContextMode’
value in the ‘ServiceBehavior’ attribute as shown below. This attribute we need
to specify on the ‘Service’ class. In the below code snippet we have specified
‘intCounter’ as a class level variable as shown below and the class counter is
incremented by one when method ‘Increment’ is called.


[ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)] 
public class Service : IService
private int intCounter;

public int Increment()
return intCounter;




At the client we have consumed the WCF client and we have called ‘Increment’
method twice.


ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 




Even though we have called the ‘Increment’ method twice we get value ‘1’. In
other words the WCF service instance is created for every method call made to
the WCF service instance so the value will always be one.




Per session Instance mode


Many times we would like to maintain state between method calls or for a
particular session. For those kind of scenarios we will need to configure the
service as per session. In per session only one instance of WCF service object
is created for a session interaction. Below figure explains the same in a
pictorial format.

• Client creates the proxy of WCF service and makes method calls.

• One WCF service instance is created which serves the method response.

• Client makes one more method call in the same session.

• The same WCF service instance serves the method call.

• When client finishes his activity the WCF instance is destroyed and served to
garbage collector for clean up.




How to implement per
session Instancing?


To configure service as per session we need to configure ‘ServiceBehavior’
attribute with ‘PerSession’ value in the ‘InstanceContextMode’ object.


[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public class Service : IService
private int intCounter;
public int Increment()
return intCounter;




At the client side when we run the below client code. You should see the
value as ‘2’ after the final client code is executed. We have called the method
twice so the value will be seen as two.


ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 




Single Instance mode


Many times we would like to create one global WCF instance for all WCF
clients. To create one single instance of WCF service we need to configure the
WCF service as ‘Single’ instance mode. Below is a simple pictorial notation of
how single instance mode will operate:-

• WCF client 1 requests a method call on WCF service.

• WCF service instance is created and the request is served. WCF service
instance is not destroyed the service instance is persisted to server other

• Now let’s say some other WCF client i.e. client 2 requests a method call.

• The same WCF instance which was created by WCF client 1 is used to serve the
request of WCF client 2. In other words only one global WCF server service
instance is created to serve all client requests.




How to implement Single
Instance mode?


In order to create a single instance of WCF service we need to specify the
‘InstanceContextMode’ as ‘Single’.


[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
public class Service : IService


If you call the WCF from different client you will see the counter keep
incrementing. The counter has become a global variable.




should you use per call, per session and single mode?


Per call


• You want a stateless services

• Your service hold intensive resources like connection object and huge memory

• Scalability is a prime requirement. You would like to have scale out

• Your WCF functions are called in a single threaded model.


Per session


• You want to maintain states between WCF calls.

• You want ok with a Scale up architecture.

• Light resource references




• You want share global data through your WCF service.

• Scalability is not a concern.




MSDN link for WCF instances


Do not miss this post which covers end to end about WCF sessions


Great blog by Rick rain on WCF instancing




Interview Questions with answers

1. What is this? Can this be used within a static method?
— The “this” reference refers to the current object context. Static methods have no context, so it is not valid.

2. Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
— The first constructor invokes the base constructor in addition to its own functionality; this would be useful if your base initialized basic field values or had other code that all other constructors would utilize.

3. What is the difference between typeof(foo) and myFoo.GetType()?
— The first returns the object’s type at compile time; the second returns it at runtime.

4. What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
— Both statements will catch and throw exception, but the latter will preserve the original exception stack.

5. By what mechanism does NUnit know what methods to test?
— Reading attributes defined for classes and methods via reflection.

6. What benefit do you get from using a Primary Interop Assembly (PIA)?
— A PIA is a strongly-named assembly which defines COM interfaces for a component. Because it is strongly-named, it can be loaded into the GAC and verified against the COM component’s own signature to give the component collision-protection and authorship-verification benefits when interacing with .NET code.

7. Explain the differences between public, protected, private and internal.
— Public: accessible from any class. Private: accessible only from within the same class. Protected: like private, but derived classes may also access. Internal: like public, but accessible only by code within the same assembly.

8. Explain the importance and use of each component of this string: Foo.Bar, Version=, Culture=neutral, PublicKeyToken=593777ae2d274679d
— Assembly name — used for loading. Assembly version — also used for loading. Culture — defines culture settings used for string translation and other locale-specific settings. PublicKeyToken — used to uniquely identify this assembly and prevent collisions.

9. Explain the use of virtual, sealed, override, and abstract.
— Virtual marks a method as overridable. Sealed marks a class as uninheritable. Override redefines a method declared as virtual. Abstract defines a class which cannot be instantiated, or a method which must be overriden in any derived classes.



WCF Service Hosting Options

Here I am going to explain what are the ways you can host WCF service.
We were able to host webservices only in IIS, but for WCF we have many hosting options,

1. Internet Information Services (IIS)
IIS is suited for hosting HTTP-based WCF services because it is integrated with ASMX and ASP.NET. It helps you host unattended services that start and stop with the system. Services hosted using IIS 6 can only use an HTTP protocol, but IIS 7 can be implemented with WAS to use non-HTTP protocols.

2. Windows Process Activation Services (WAS)
WAS enables services to use non-HTTP protocols, such as such as TCP, MSMQ, and named pipes. So it is suited for services that use protocols other than HTTP.

3. Self-hosting in a managed Windows service
Using a managed service helps you create a customized hosting environment, which allows the SCM to choose features. However, it requires you to write some hosting code in the service application.
4. Desktop Application
Using a desktop application enables you to implement a service that requires user interaction.
5. Console Application
Console applications provide a simplified debugging process, so they are suited for testing services.

Refer below link if you wanted to know more details on how to host,

Implementing Session in WebService

As we all know that all web applications are stateless and webServices are no exceptions.There are various techniques of state management in web applications viz
Hidden Fields
Since web services don’t have any user interface we can’t use Hidden fields and ViewState for maintaining state. Here in we will discuss how to maintain session in web services.
In my previous post regarding web services attributes http://www.dotnetspider.com/resources/16088-Web-Services-Attributes.aspx. I have specified what all attributes a web service can have and what is the use of each attribute. Let’s talk in depth about EnableSession attribute:-

The EnableSession property is a Boolean property and allows us to enable sessions (this requires the use of the proxy object, which will be discussed in another article). Without the proxy object, this web property cannot be implemented as the property is discarded as soon as the value is assigned to it. Without a proxy object, only one request is allowed per session, and assigning a value to the property itself is a request and therefore the session is ended just after.
Now just have a look at the below code
public void SetSessionVariable(string str)
Session[“id”] = str;

public string GetSessionVariable()
if ( Session[“id”] != null )
return Session[“id”].ToString();
return “Nothing in Session”;
When you run this code for the first time It will give Object reference error in SetSessionVariable function since Session is not enables and thus Session object will be null.
To get around this issue you just need to tweak the WebMethod attribute a bit.Append the WebMethod attributes to the functions to enable sessions.

public void SetSessionVariable(string str)
Session[“id”] = str;

public string GetSessionVariable()
if ( Session[“id”] != null )
return Session[“id”].ToString();
return “Nothing in Session”;
Now try to run this sample by writing the following code
localhost.Service obj = new localhost.Service();
obj.SetSessionVariable(“Some Value”);
MessageBox.Show(obj. GetSessionVariable().ToString());
What Happened this time?Did we get the value this time round from session?What have we done wrong……………
Well the web service code is ok but since web Services are stateless where will they store the session information. System.Net.CookieContainer class comes to the rescue.Since web services are a complete framework you will find a lot of things when you have just created them by writing a simple function one og the things is a CookieContainer property.Yeah you have to set this property to get the session thing working for you.
So here goes the complete code

localhost.Service obj = new localhost.Service();
System.Net.CookieContainer container= new System.Net.CookieContainer();
obj.SetSessionVariable(“Some Value”);//Sets value in session
MessageBox.Show(obj. GetSessionVariable().ToString());//Retrieves value from Session

A Fast-Track Overview to WCF

Overview of WCF

– Windows Communication Foundation.
– It combines functionalities of Asp.Net Web services, remoting, MSMQ and Enterprise Services.
– It’s more reliable and secured then Web services.
– All the major changes can be done in the configuration file instead of code file.

Differences with Webservices

WCF can be hosted on IIS, WAS, of self-hosting.
WS can be hosted on IIS.

WCF has [ServiceContract] attribute attached with the class.
WS has [WebService] attribute attached with the class.
WCF has [OperationContract] attribute attached with methods.
WS has [WebMethod] attribute attached with methods.

WCF uses System.Runtime.Serialization namespace for serialization.
WS uses System.Xml.Serialization namespace for serialization.

WCF supports XML, MTOM (Messaging Transmission Optimization Mechanizm),Binary.
WS supports XML, MTOM, DIME (Direct Internet Message Encapsulation).

WCF supports Http, Tcp, Msmq, P2P transport protocols.
WS supports Http protocol.

WCF provides reliable security for messaging and transactions over net.
WS doesn’t provide method level security & message delivery is’t assured & can be lost without acknowledgement.

3 major Points in WCF

WCF service location that client can use to expose its features

Configuration for Transport protocol, security and encoding mechanism.

It defines type of data and type of oprtaions, a client application can use from WCF service.

Service Contract in WCF

It has 2 attributes: ServiceContract & OperationContract

Interface ITestContract 
	string MyMethod();

Class myService : ITestContract
	public  string myMethod()
		return "Hello World!!";

Data Contract in WCF

It has 2 attributes: DataContract & DataMember

class TestDataContract
	public string EmployeeName;

	public DateTime JoiningDate;

WCF configurations in config file

It declares information about endpoint name, address, binding and contract.

        <endpoint name = "MyEndpoint"
                  address = "http://localhost:8000/MyService/"
                  binding = "wsHttpBinding"
                  contract = "IMyContract"

WCF proxy

It provides the same operations as that of a Service Contract. There are 2 ways to generate WCF proxies.

In Visual Studio 2008
Right click reference > Add service reference

In Visual Studio – Command Prompt
Using SvcUtil.exe tool

ex: ScvUtil    http://localhost/MyWCFService/MyService.svc    /out:MyProxy.cs

Fault Contract

It provides the implementation to handle the error raised by WCF
It also propagates the errors to its client applications.

Collection Types Supported by WCF


Dictionary Collection Types Supported by WCF


I hope, I am able to cover main topics about WCF in this article.

Refer the sample code in the attachment.