wcf_ from a beginner's perspective

26
4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 1/26 Articles » Platforms, Frameworks & Libraries » Windows Communication Foundation » General Anurag Sinha V, 5 Apr 2013 CPOL WCF: From a Beginner's perspective & a Tutorial This article tries to dig in as to what is WCF, how to code WCF services Download CP.zip - 59.2 KB Introduction Well, a month ago i wrote an article on ASP.NET Web Services, which can be found here http://www.codeproject.com/Articles/524983/Web-Services-From-a-beginners-perspective, I received a comment that .ASMX Web Services are seldom used now, which is pretty correct to an extent. Hence, I have decided to pen down an article covering WCF, how to code WCF services and stuffs. Let's start with the article without much delay. Well, WCF stands for Windows Communication Foundation, it was first shipped with .NET 3.0 framework along with WPF, Windows CardSpace and WorkFlow Foundation. From a beginner's perspective, what does actually WCF mean? Let's break the abbreviation into single entities and try to debug. It consists of 3 words, a)Windows b)Communication c)Foundation. A beginner would glance at the words and would think, well it is something which deals with Windows platform, which is used to communicate and connect applications. Hmm, well he/she ain't wrong on the first strike... A definition which comes to mind may be summed up as: WCF is a kind of technology, which is used to develop and deploy services on Windows platform. Different books have different set of words to describe WCF, but the gist is almost the same which points to development and deployment of services on Windows Platform. MSDN says, WCF is a framework to build service-oriented applications. So basically WCF revolves around developing applications which are greatly dependent upon services. Need For WCF Next question wobbling the mind would be why WCF, what's the need for it? Well yeah it's the most probable query after a little initial understanding. Prior to WCF, there were a handful of technologies doing tasks of 4.80 (76 votes)

Upload: bogdan-comsa

Post on 12-Feb-2016

215 views

Category:

Documents


0 download

DESCRIPTION

WCF_ From a Beginner's Perspective

TRANSCRIPT

Page 1: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 1/26

Articles » Platforms, Frameworks & Libraries » Windows Communication Foundation » General

Anurag Sinha V, 5 Apr 2013 CPOL

WCF: From a Beginner's perspective & a Tutorial

This article tries to dig in as to what is WCF, how to code WCF services

Download CP.zip - 59.2 KB

Introduction

Well, a month ago i wrote an article on ASP.NET Web Services, which can be found herehttp://www.codeproject.com/Articles/524983/Web-Services-From-a-beginners-perspective, I received acomment that .ASMX Web Services are seldom used now, which is pretty correct to an extent. Hence, I havedecided to pen down an article covering WCF, how to code WCF services and stuffs.

Let's start with the article without much delay.

Well, WCF stands for Windows Communication Foundation, it was first shipped with .NET 3.0 frameworkalong with WPF, Windows CardSpace and WorkFlow Foundation.

From a beginner's perspective, what does actually WCF mean? Let's break the abbreviation into singleentities and try to debug. It consists of 3 words, a)Windows b)Communication c)Foundation.

A beginner would glance at the words and would think, well it is something which deals with Windowsplatform, which is used to communicate and connect applications. Hmm, well he/she ain't wrong on the firststrike...

A definition which comes to mind may be summed up as: WCF is a kind of technology, which is used todevelop and deploy services on Windows platform. Different books have different set of words to describeWCF, but the gist is almost the same which points to development and deployment of services on WindowsPlatform.

MSDN says, WCF is a framework to build service-oriented applications. So basically WCF revolves arounddeveloping applications which are greatly dependent upon services.

Need For WCF

Next question wobbling the mind would be why WCF, what's the need for it? Well yeah it's the most probablequery after a little initial understanding. Prior to WCF, there were a handful of technologies doing tasks of

4.80 (76 votes)

Page 2: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 2/26

communication between a client and a server, they had their pros and cons. For instance:

.ASMX Web Services allowed stuffs to be accessed from any platform.MSMQ allowed queuing of messages, so that communication between a client and server is possibleeven when the server was disconnected..NET Remoting service allowed transfer of data between a client and server on Windows OS.

So if a developer had to develop an architecture having all the above functionalities, he had to learn theabove technologies, which was a cumbersome task. Hence WCF was introduced by Microsoft to overcomethese shortcomings. Basically WCF unified the above technologies into a single programming model for theease of developing service oriented architecture.

I hope that the readers have got an initial understanding of WCF by now, let's move on.

WCF Architecture

Below is the image of WCF Architecture (courtesy: Google Images) :

WCF has a multi-layered architecture namely Contracts layer, Service Runtime Layer, MessagingLayer and Activation and Hosting Layer. I'll try to explain major architectural stuffs in a simple language.

Contracts Layer

In a layman's terms, a contract may be seen as a kind of agreement between 2 or more parties, over somegoods or services. The contract will define what kind of services need to be offered, how they need to beoffered, details about the place etc. Similar is the case with WCF Contracts Layer. It's an agreementbetween 2 machines defining the terms and conditions for the messages to be exchanged. Let'shave a look at the individual items of the Contracts Layer.

Data Contract: Agreement between a service and a client on the data that has to be exchanged.Also defines what data structures and parameters to be used by services in order to interact with the

Page 3: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 3/26

client.Message Contract: Provides control over the SOAP messages that are produced and consumed byWCF. It also provides direct access to message header & body to alter the SOAP message as perthe requirement.Usually developers don't pay much heed to message contracts in normal scenarios,but there arises a need for message contracts and their use when interoperability is important orsecurity needs to be maintained at the message level.Service Contract: Defines the kind of operations supported by the service. It also exposes certaininformation to the client such as:

1. Data Types in the message.2. Locations of the operations, or where the methods are defined3. Protocol information and serialization format4. Message exchange patterns(whether the behavior of the message is either one-way, duplex or

request/reply type)

Policy and Binding: Specify important information such as security, protocol.

Let's switch over to the Service Runtime layer:

Service Runtime layer specifies and manages different behaviors of the service that occur during theservice operation. Behaviors of the service or Service Behaviors as they can be fondly called, arebasically objects that modify and control the run time characteristics of WCF. Below is a list of ServiceBehaviors managed by the Service Runtime layer:

Throttling Behavior: Determines the number of processed messages, which varies according to thedemand of the service.Error Behavior: Specifies what kind of action to be taken when any of the messages give errorduring runtime.Metadata Behavior: Specifies whether metadata is available across the network.Instance Behavior: Specifies the number of service instances that are available to process amessage.Message Inspection: Inspects a message totally or partly during runtime.Transaction Behavior: Enables the transaction operation, which rollbacks the transaction if anyprocess fails during runtime.Dispatch Behavior: Determines the handling and processing of a message.Concurrency Behavior: Specifies whether the messages are processed sequentially orconcurrently.Parameter Filtering: Filters the message headers & executes preset actions based on the filter ofthe message headers.

Let's discuss stuffs about the Messaging Layer:

Messaging Layer is responsible for the pattern of exchanges and its format. It's composed of the followingcomponents and channels:

WS-Security Channel: Enables message security by implementing the WS-Security specifications.Extensive coverage on WS Security can be found out here: http://msdn.microsoft.com/en-us/library/ms977327.aspxWS Reliable Messaging Channel: Guarantees delivery of messages.Encoders: Provides the number of encoders for messages, such as Binary, XML, Text, MTOM.HTTP Channel: States that HTTP is used to deliver messages.TCP Channel: States that TCP is used to deliver messages.Transaction Flow Channel: Governs transacted message patterns.Named Pipe Channel: Enables Inter Process Communication.MSMQ Channel: Enables services to operate with MSMQ.

Let's move on to Hosting and Application Layer:

This layer provides a number of options in which a service can be activated and hosted. Hosting can be of 2types: self hosting, hosting on external agents, such as IIS. Various options provided by this layer are asfollows:

Page 4: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 4/26

Windows Activation Services: Enables WCF applications to automatically activate, when deployedon a system running WAS..EXE: WCF services can also be run as executable files.Windows Services: WCF services can also be run as Windows services.COM+: WCF services can also be run as COM+ app.

After a discussion about the architecture, let's move on to the features of WCF, which is an importantdomain as well.

Features of WCF

Features of WCF can be described as follows:

Endpoint SupportImproved Transport LayerQueuing SupportImproved Transactional processImproved SecurityHosting Support on various environmentsAJAX Integration and JSON Support

Let's start with a brief discussion about each of them

Endpoint Support: An endpoint is basically a resource or an entity in the network to which messages canbe sent. Endpoints are responsible for the communication between a client and the service. Elements ofendpoints are:

Addresses to locate the serviceBindings to communicate with the serviceContracts to specify the functionalities to be performed while communicating with the service.Endpoint behaviors to specify the runtime behavior of the service endpoint.

These Addresses, Bindings and Contracts are normally referred to as ABC's of WCF.

Let's discuss a bit about these ABC's.

Addresses: In order to send a message to a service, you would need its address. An address in WCFwould consist of the following items:

Scheme : Basically the transport protocol used.Machine : Full Domain Name of the machine.Port: Defines the port number where the service is running.Path: Path of the service.

Example can be written as:

scheme://domain_name:port/pathhttp://localhost:8080/services/MyFirstService

In the above example, a service is locally hosted with HTTP being the transport protocol and 8080 being theport used, path being services/MyFirstService.

Bindings: Facilitate the communication between the client and the service. Specify the communicationprotocol used to access the service. Below is the list of pre-defined binding elements:

basicHttpBindingwsHttpBindingwsDualHttpBinding

Page 5: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 5/26

wsFederationHttpBindingnetTcpBindingnetNamedPipeBindingnetMsmqBindingmsmqIntegrationBindingnetPeerTcpBinding

Well I would discuss a little about one of the bindings and details on the use and implementation of otherscan be searched easily on MSDN and even on CP...

basicHttpBinding: This type of binding is used by the WCF services to configure and expose thoseend points that are able to communicate with .ASMX Web Services and clients. Transport protocol used isHTTP, while message encoder used is Text/XML. Security is disabled by default in this, to enable thesecurity BasicHttpSecurityMode needs to be configured. Have a look at the below code on how toconfigure the host of the basicHttpBinding.

<?xml version="1.0" encoding="utf-8" ?><configuration>

<system.serviceModel> <services>

<service name="MyFirstService">

<host> <baseAddresses>

<add baseAddress="http://localhost:8080/MyFirstservice"/> </baseAddresses>

</host> <endpoint address="" binding="basicHttpBinding" contract="MyFirstService">

</endpoint> </service>

</services>

</system.serviceModel></configuration>

Let's discuss about Contracts as in C of ABC's of WCF:

Contracts: Agreements between the client and services. 3 basic contracts are:

Service Contracts: Defines the methods of the service.Data Contract: Defines the data types used by the service methods.Message Contract: Ability to control the message headers during the creation of the message.

The second feature of WCF is Improved Transport Layer: Unlike .ASMX web services, WCF servicesuse a numerous protocols for communication between a client and the service. It uses HTTP, TCP, HTTPS,Named pipes. Hence, improved transport facility.

Queuing Support: WCF supports queuing, which allows messages to be stored in a queue and then sentin a timely manner, thus giving a consistent state of communication.

Improved Transactional Support: WCF incorporates improved transactional support, which says if anyprocess fails during service runtime, the transaction doesn't commit, it rollbacks.

Improved Security: Authentication plays a big role in WCF, also WCF ensures that during transit, order ofthe messages ain't altered.

Hosting support on various environments: WCF allows hosting of services in a number ofenvironments, such as Windows NT Services, Windows Forms, Console Apps, IIS, Windows ActivationServices(WAS). IIS provides added advantages such as automatic start and stopping of the service.

AJAX Integration and JSON Support: WCF supports ASP.NET AJAX and JSON data format, which allowsWCF services to expose operations to AJAX clients. JSON is a data format used to carry data exchange

Page 6: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 6/26

between AJAX enabled services and their clients. Let's start with the coding part now.

Background

There ain't any pre-requisites as such, just the presence of Visual Studio 2008 client is enough.

Using the Code

We will first code a simple WCF service and test it via inbuilt WCF test client.

1. Open Visual Studio 2008 and click on File> New> Project.

2. Create a new Blank Solution to start with.We will add projects later in the next step.

Give the name of the solution as MyFirstServiceSolution and the location where you want to store thecodes.

3. A solution will be created by VS, then right-click the solution explorer Add> New project.

Page 7: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 7/26

4. After clicking on Add>New project, a dialog box will open with few options. Select WCF servicelibrary, provide the name as MyServiceLibrary, location as desired and click on OK.

5. A new WCF service library will be added to the solution, which will have 2 default class files namely,Service1.cs and IService1.cs, providing default implementation of the WCF Service library. Since wewill configure the library on our own, so delete both these class files.

Page 8: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 8/26

6. Now, right click the WCF service library and add a new class file, name it as MyService.cs

7. Open MyService.cs, initially it will just have a class called MyService. We need to define what kindof data the service needs to expose. Primitive datatypes such as int, string, float don't need to beexposed as data contract, they are pretty much understood by the .NET engine, whereas userdefined data types such as class, enumerations need to be exposed as data contracts. Hence define

Page 9: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 9/26

a class called as Maths and define 2 properties over there.

Individual members of the Data contract class need to be exposed as data members. Thenamespace System.Runtime.Serialization needs to be added for data contract to comealive.Then, we will have to define our service contract, which ensures what operations are exposedby the service. Add an interface, call it as IMaths and add individual methods inside it which willaccept the Data contract class as argument to work upon. Service contract will come alive viainclusion of System.ServiceModel namespace. Next comes the actual implementation of theservice, extend the MyService class to implement the interface and its operations. Define thefunctionalities of the operations as you desire. In the below code, normal arithmetic operations aredefined in the MyService class. Build the solution, it should compile without any error.

using System;<pre>using System.Collections.Generic;

using System.Linq;using System.Text;using System.Runtime.Serialization;

using System.ServiceModel;namespace MyServiceLibrary{ [DataContract]

public class Maths {

[DataMember] public int Number1 { get; set; } [DataMember] public int Number2 { get; set; }

} [ServiceContract] public interface IMaths {

[OperationContract] int Addition(Maths obj1); [OperationContract]

int Subtraction(Maths obj2); [OperationContract] int Multiplication(Maths obj3); [OperationContract]

int Division(Maths obj4); } class MyService:IMaths

{ #region IMaths Members public int Addition(Maths obj1) {

return (obj1.Number1 + obj1.Number2); } public int Subtraction(Maths obj2)

{ return (obj2.Number1 - obj2.Number2); } public int Multiplication(Maths obj3)

{ return (obj3.Number1 * obj3.Number2); } public int Division(Maths obj4)

{ return (obj4.Number1 / obj4.Number2); }

#endregion

Page 10: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 10/26

}}

8. Next, we need to configure the App.Config file. First of all, we need to change the service name topoint to MyServiceLibrary.MyService, intially it would have pointed toMyServiceLibrary.Service1, but since we have deleted Service1.cs and have includedMyService.cs, we need to alter the service node in the config file.

9. Next we need to configure the endpoints. Change the contract name to point toMyServiceLibrary.IMaths. Here, I have configured 2 different endpoints to make the servicetalk via 2 means. Have used wsHttpbinding and basicHttpBinding. Have changed the baseaddress to a simpler path.

10. Well, when you try to debug the WCF service after making all the changes, it might give you anAccess Denied exception as below, saying the base address can not be reached. Debug your WCFservice in Administrator mode, then it will work.

Page 11: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 11/26

11. Let's now debug the service and see how it works. press F5, then a WCF test client will be launchedas below. The .NET engine looks for the base address and pings it to get the metadata of the serviceand eventually gives us all the operations which were exposed by the service.

12. It shows the same operations twice, coz we have added 2 different bindings to use. Double click anyof the operations and then you can give the values of the parameters and invoke the service. Theservice in turn will return the response. Let's invoke the Addition operation as below:

Page 12: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 12/26

13. Give some random values and click on Invoke button, the service will return a response based uponthe functionality of the operation as below:

In the above example, we saw the creation of a WCF service library from scratch, which involves creatingjust a single class and implementing everything in that, though it's not actually mandatory to implementeverything in the same class.It was just for demonstration.

Next we will see how to call and consume a WCF service from a client. Let's start.

1. Open your Visual Studio once again and click on New>WebSite as below.

Page 13: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 13/26

2. A dialog box will open, select WCF service , give the location where you want to store it.

3. The template will add up a WCF service project in the solution, having 2 class files IService.cs,Service.cs and a Service.svc file.

4. Service.svc file is helpful when we want to host the service within the IIS. Service.cs and IService.csclasses will provide some default implementation of the service. For the time being, leave them as itis. Build the solution, set the Service.svc file as Start Page and debug it. You will see that the

Page 14: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 14/26

ASP.NET Development server browses over to a URL and sends back a Service implementationsomething like below. It implies that the service has been created and is up and running.

5. On clicking the URL inside the page, you'll be redirected to the Web Services DescriptionLanguage (WSDL) page:

6. Let's view the skeleton of the Service.svc file:

<%@ ServiceHost Language="C#" Debug="true" Service="Service"

CodeBehind="~/App_Code/Service.cs" %>

The element Service shown as bold in the above piece of code refers to the Service class presentin theService.cs file, which is further stored under App_Code folder.

Above was just an intro to the WCF service and its features, let's start to code a WCF service and tryto consume it in a console application.

Page 15: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 15/26

7. Rename the IService.cs, Service.cs files to something appropriate like IMathService.cs andMathService.cs. Accordingly you'll have to alter the names within the Service.svc and web.config file.Have a look at the below code for IMathService.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

// NOTE: If you change the interface name "IService" here, you must also update the reference

to "IService" in Web.config.

[ServiceContract]

public interface IMathService

{

[OperationContract]

int Addition(Math obj1);

[OperationContract]

int Subtraction(Math obj2);

// TODO: Add your service operations here

}

// Use a data contract as illustrated in the sample below to add composite types to service

operations.

[DataContract]

public class Math

{

int number1, number2;

[DataMember]

public int Number1

{

get { return number1; }

set { number1 = value; }

}

[DataMember]

Page 16: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 16/26

public int Number2

{

get { return number2; }

set { number2 = value; }

}

}

Here in the code, we have a class as Math which is a DataContract since it acts as a user-defined datatype. It has 2 members and 2 properties defining the numbers. Then we have a ServiceContract calledas IMathInterface which exposes 2 operations to the client.

8. Have a look at the MathService.cs file:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

// NOTE: If you change the class name "Service" here, you must also update the reference to

"Service" in Web.config and in the associated .svc file.

public class MathService : IMathService

{

#region IMathService Members

public int Addition(Math obj1)

{

return (obj1.Number1 + obj1.Number2);

}

public int Subtraction(Math obj2)

{

return (obj2.Number1 - obj2.Number2);

}

#endregion

}

The MathService class inherits the IMathService interface and provides the implementation of theoperations exposed by the service.

Page 17: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 17/26

9. Build the solution, set Service.svc as Start Page and debug. It should work without any errorsand you'll see the Service page in the browser as below:

It shows as to how we can use this WCF service in a client application. Let's now try to code aconsole application to consume this service. Stay Tuned..

10. Right click on the solution and click on Add>New Project as shown below:

11. A dialog box will be opened, select Console Application from the list of templates, store thisapplication inside the same solution in which the above service is kept and give a name forthe application as DemoClient.

Page 18: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 18/26

12. A Console Application project will be added to the solution, now we need to refer the WCF service inthis application. Right click on References>Add Service Reference.

13. This will open a Add Service Reference window. We need to search the WCF service to add, giveits URL in the Address textbox and hit Go. The service will be evident and its services and operationswill be listed.

Page 19: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 19/26

Give the namespace as localhost, since it is the domain name(providing domain name is theconvention) and hit OK. The service reference will be added to the Console Application project.

Now open the program.cs file of the Console app and start coding as shown below:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace DemoClient

{

class Program

{

static void Main(string[] args)

{

localhost.MathServiceClient obj = new DemoClient.localhost.MathServiceClient();

localhost.Math mathobj = new DemoClient.localhost.Math();

Page 20: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 20/26

mathobj.Number1 = 10;

mathobj.Number2 = 5;

Console.WriteLine("Addition continues..");

Console.WriteLine(obj.Addition(mathobj));

Console.WriteLine("Subtraction continues..");

Console.WriteLine(obj.Subtraction(mathobj));

Console.ReadLine();

}

}

}

I will explain the above code. We haven't done anything special, we have just created an object of theMathService client as obj and have tried to access the operations which were exposed in the WCF service.Since the operations of the WCF service accept an argument of type Math class, we have to make anobject of the Math class, shown above as mathobj. This mathobj will be able to access the properties ofthe Math class. Then we have given some values to the properties and have just called the individualoperations Addition() and Subtraction() as exposed by the WCF service.

14. Now, we need to debug our console application to see whether the implementation is successful ornot. Well, right-click on the console app name in the solution and set as 'Startup Project'.

15. Now debug the application and if everything's correct, then the console app would work without anyerrors, shown as below:

Page 21: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 21/26

Hence, we have been pretty successful in creating a WCF service and consuming it via a client, aconsole application in this case.

I want to emphasize as to what happens when a service reference is added to anapplication, what's the internal mechanism and stuffs. Let's see.

16. Click on localhost service under service references and click on 'Show All Files'.

17. A list of files will be evident as shown below:

Page 22: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 22/26

18. Click on Reference.cs under Reference.svcmap classification, which will contain the mappings,serialization and proxy class stuffs. For ex: In the below image we can see that a partial class namedas Math has been created, in which the DataMembers are serialized, it implies that the user-defineddata type, Math class in our WCF service is serialized when the service is consumed by a client andthen it's referenced.

Page 23: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 23/26

19. Have a glance at the below image too, implementation of the operations has been created, whichmeans that we will have to code the same way if we have to consume these operations in our clientapplication. Also, we can see that a proxy class named as MathServiceClient has been created,we just need to instantiate the proxy class in our main method and then we're good enough to usethe operations which have been exposed by the WCF service.

Page 24: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 24/26

Gist is that, when we add a service reference to a client application, Visual Studio looks at the WSDL file ofthe service, downloads it and prepares similar methods and functions inside Reference.cs file. Post that wejust need to refer these methods and functions in our main application.

I guess I have reached the end of the article for now. I have discussed:

What is WCF, its architecture, its features, uses.How to create a WCF Service Library and test it via WCF Test Client, from scratch.How to create a WCF Service and consume it in a client application.

In the next part of the article, I would like to deal with how to consume a WCF service in an ASP.NET Webapplication and how to write WCF Services with ASP.NET AJAX (This article will come soon)...

Points Of Interest

Well, I learnt a lot while writing this very article.

A tip which I want to share with our readers is that when you are declaring a DataContract or aServiceContract and these terms don't highlight (show error), probably because we haven't includedthe required namespaces, we can do Ctrl+Dot key to implement the namespaces rather than by explicitlytyping. Have a look below:

Page 25: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 25/26

Same applies when you are trying to refactor the Interface.

A zipped folder has been added which has the source codes referenced in this article. It has 2 foldersbasically, MyFirstServiceSolution(WCF service library coded from scratch) andWCF_WebService(having a WCF service and a console app). Do make use of that.

I would like to give credit to MSDN and the Black Book of C# and ASP.NET from where I have referencedcertain definitions and stuffs.

Sequel to this article can be found at : http://www.codeproject.com/Articles/570036/WCF-From-a-Beginners-perspective-and-a-tutorial-Se. It helps the readers to consume a WCF service in an ASP.NET website andto create an AJAX enabled WCF service. View it and enjoy coding WCF services.

History

Version 1.0 of WCF article completed on 25th, March 2013.

License

This article, along with any associated source code and files, is licensed under The Code Project OpenLicense (CPOL)

Share

About the Author

Page 26: WCF_ From a Beginner's Perspective

4/17/2015 WCF: From a Beginner's perspective & a Tutorial - CodeProject

http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial?display=Print 26/26

Permalink | Advertise | Privacy | Terms of Use | Mobile

Web04 | 2.8.150414.1 | Last Updated 5 Apr 2013 Selectaţi limba ▼Article Copyright 2013 by Anurag Sinha V

Everything else Copyright © CodeProject, 1999-2015

Anurag Sinha VSystems Engineer India

An electronics engineer landed in the crazy .NET world...

Comments and Discussions

45 messages have been posted for this article Visit http://www.codeproject.com/Articles/566691/WCF-From-a-Beginners-perspective-a-Tutorial to post and view comments on this article, or click here to get aprint view with messages.