What the heck is WCF? For a long time, I couldn't tell you exactly what it was. And honestly, I still don't think I can. WCF is such a broad concept that it's hard to boil down into a concise explanation. When I finally started reading about it, and getting beyond the concepts, things started to clear up. That's what today's tutorial is about - cutting through all the concepts and just use WCF to build a basic server and a basic client.
At its core, WCF is a mechanism that facilitates communication between processes - either on the same machine or separate machines. Part of the confusion I had when trying to understand WCF was the almost limitless ways WCF can accomplish this. We're not going to worry about all of that though. We're going to strip out everything except the bare essentials required to get a client/server system up and running - and it's actually very little code.
What we're building today will look a lot like a simple remote procedure call. We'll be building a server that exposes a function that can be called by a client. Just to show how easy it is to change the transport layer, the client will connect to the server through two different mechanisms - http and named pipe.
The first thing we need to do is define what the client will have access to. We do this by defining an interface in C# and giving it a few attributes for WCF. The server will create a class that implements the interface to actually do the work. The client will just be provided the interface so it knows which functions are available.
using System;
using System.ServiceModel;
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
Here's my simple interface. It provides a function that takes a string
and returns a new string with all of the characters reversed. The
ServiceContract attribute tells WCF that this interface can be exposed
for client use. The OperationContract attributes tells WCF that
ReverseString is part of this service contract and can be used by
clients. There are lots of optional settings that can be applied to both
of these attributes, but this is all that's required to get things up
and running. The System.ServiceModel namespace is available by adding
a reference to the System.ServiceModel assembly to your project, which
is available in the default installation of .NET 3.5.
Starting with the server, the first thing we need to do is create a
class that implements this interface and provides the functionality
behind ReverseString.
using System;
using System.ServiceModel;
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
public class StringReverser : IStringReverser
{
public string ReverseString(string value)
{
char[] retVal = value.ToCharArray();
int idx = 0;
for (int i = value.Length - 1; i >= 0; i--)
retVal[idx++] = value[i];
return new string(retVal);
}
}
Pretty simple, right? There might be more elegant ways to reverse a string, but we're not here to criticize the implementation of this function. It's actually not required to use the interface method for defining service contracts (i.e. you could stick the attributes directly on the class), but it's the recommended way, and it makes client applications much easier to implement if they can simply share the same interfaces.
Surprisingly, there's actually very little code required to make the
server fully functional. We'll begin by creating a ServiceHost, which
is responsible for most of the work behind exposing the service to
clients.
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(
typeof(StringReverser),
new Uri[]{
new Uri("http://localhost:8000"),
new Uri("net.pipe://localhost")
}))
{
}
}
}
The most difficult thing here is the array of Uri objects. These are our base addresses that clients can use to connect to this WCF server. Like I said before, we're exposing two ways to connect to this service: http and named pipe. How the address is formatted depends on the type of Binding it represents.
Now that we've got our ServiceHost created, we need to configure some endpoints. These will actually enable the http and named pipe bindings and give them the address required by the client.
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(
typeof(StringReverser),
new Uri[]{
new Uri("http://localhost:8000"),
new Uri("net.pipe://localhost")
}))
{
host.AddServiceEndpoint(typeof(IStringReverser),
new BasicHttpBinding(),
"Reverse");
host.AddServiceEndpoint(typeof(IStringReverser),
new NetNamedPipeBinding(),
"PipeReverse");
host.Open();
Console.WriteLine("Service is available. " +
"Press <ENTER> to exit.");
Console.ReadLine();
host.Close();
}
}
}
Here we're adding two endpoints - one for http and one for named pipe.
The address that's passed in is what appears after the base address
specified in the ServiceHost constructor (e.g. for http it would be:
"http://localhost:8000/Reverse"). We have to specify a base address for
each endpoint we're configuring. So if the net.pipe base address was not
present in the ServiceHost constructor, the server would throw an
exception when it attempted to create the named pipe endpoint. After the
endpoints are configured, we simply call Open on the ServiceHost to
enable it.
Believe or not, that's it for a fully functional WCF server. Below is all of the code put together.
using System;
using System.ServiceModel;
namespace WCFServer
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
public class StringReverser : IStringReverser
{
public string ReverseString(string value)
{
char[] retVal = value.ToCharArray();
int idx = 0;
for (int i = value.Length - 1; i >= 0; i--)
retVal[idx++] = value[i];
return new string(retVal);
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(
typeof(StringReverser),
new Uri[]{
new Uri("http://localhost:8000"),
new Uri("net.pipe://localhost")
}))
{
host.AddServiceEndpoint(typeof(IStringReverser),
new BasicHttpBinding(),
"Reverse");
host.AddServiceEndpoint(typeof(IStringReverser),
new NetNamedPipeBinding(),
"PipeReverse");
host.Open();
Console.WriteLine("Service is available. " +
"Press <ENTER> to exit.");
Console.ReadLine();
host.Close();
}
}
}
}
Now we can move on to the client. The first thing we'll need in the client code is the same interface, with the same attributes, that we defined in the server. If this were being used in a production environment, these interfaces would probably be created in a dedicated library that could be easily distributed. For now, I just copied and pasted the code into another project.
We have to first establish a channel between the client and a server. A
channel is basically a connection that allows the client and server to
send messages to each other. Fortunately, WCF provides something called
a ChannelFactory that makes creating these very simple.
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace WCFClient
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
class Program
{
static void Main(string[] args)
{
ChannelFactory<IStringReverser> httpFactory =
new ChannelFactory<IStringReverser>(
new BasicHttpBinding(),
new EndpointAddress(
"http://localhost:8000/Reverse"));
ChannelFactory<IStringReverser> pipeFactory =
new ChannelFactory<IStringReverser>(
new NetNamedPipeBinding(),
new EndpointAddress(
"net.pipe://localhost/PipeReverse"));
IStringReverser httpProxy =
httpFactory.CreateChannel();
IStringReverser pipeProxy =
pipeFactory.CreateChannel();
}
}
}
We're building two proxies here - one for http and one for named pipe.
The addresses passed into the ChannelFactory constructor are the same as
those configured on the server. We also have to pass in the specific
bindings we want: BasicHttpBinding and NetNamedPipeBinding. Lastly we
call CreateChannel on each channel factory, which returns an
IStringReverser interface. Now we can call functions on those
interfaces and WCF makes a remote call through the channel to our server
to get the result.
string str = Console.ReadLine();
Console.WriteLine("http: " + httpProxy.ReverseString(str));
Console.WriteLine("pipe: " + pipeProxy.ReverseString(str));
Incredibly, we're now done with the client. Here's the client program in its entirety:
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace WCFClient
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
class Program
{
static void Main(string[] args)
{
ChannelFactory<IStringReverser> httpFactory =
new ChannelFactory<IStringReverser>(
new BasicHttpBinding(),
new EndpointAddress(
"http://localhost:8000/Reverse"));
ChannelFactory<IStringReverser> pipeFactory =
new ChannelFactory<IStringReverser>(
new NetNamedPipeBinding(),
new EndpointAddress(
"net.pipe://localhost/PipeReverse"));
IStringReverser httpProxy =
httpFactory.CreateChannel();
IStringReverser pipeProxy =
pipeFactory.CreateChannel();
while (true)
{
string str = Console.ReadLine();
Console.WriteLine("http: " +
httpProxy.ReverseString(str));
Console.WriteLine("pipe: " +
pipeProxy.ReverseString(str));
}
}
}
}
It's amazing when you think about the amount of stuff happening behind the scenes that developers no longer have to worry about. Basically, all developers have to do is define interfaces and objects and WCF takes care of the rest. The server side and client side code can be drastically reduced by using configuration files to replace the setup we did in code, but for the purpose of understanding, explicitly setting it is a good way to know what's behind configuration settings.
I think that about wraps it up for this introduction to WCF. There's an immense amount of configuration and customization supported by WCF, and volumes could be dedicated to it. Hopefully we'll slowly unravel WCF's complexity and introduce new concepts in following tutorials. You can download Visual Studio 2008 solutions for both the client and the server here.
Source Files:
what is meant by end point can you explain those briefly
the client who connects is known as the end point. Regards,
Kathirvel
hi, can u explain at which place WCf is used and how ?,pls explain at low level.
I implemented a WCF web service for a client recently, and it works great - so I definitely don’t need to be sold on it.
However, now I’m doing research for another client who would like a real-time chat app. I’m trying to find out what, if any, are the differences between implementing a WCF server app and implementing a Socket server app? I’ve heard that WCF doesn’t allow tcp/ip connections beyond LAN boundaries but I’m not sure if that’s accurate or not. I’ve also heard that one cannot create persistent tcp/ip connections with WCF, but like the previous statement that did not come from an authority on the matter.
Do you have any insight? Have you attempted to create any kind of RTM app with WCF?
hi, can u explain at which place WCf is used and how ?,pls explain at low level.
Hi,
I have created a chat application using WPF and WCF using net.tcp binding and it works well beyond the LAN.
I am currently working on Silverlight 5 chat application using the same net.tcp binding and a special port which is required by the Silverlight to connect to WCF using TCP.
So far everything is working fine.
Thanku very much for the sample code provided. The code helped me in finding a design solution for my application gud work
You better explain main concepts of WCF before jumping on code.That is one problem as most developers want to do stuff in minutes without understanding the main concepts. Look at one reader, he/she didnt understand end point.me too.
i think microsoft gave the archecture to WCF pretty same as .Net Remoting.
It is always nice to explain the basics, but not every post is going to do that. You mention that most developers want to do stuff very quickly, this isn't something I think is always wanted but needed. I find that sometimes things just need to get done. Also, if you don't understand some of the basics I think that you should take some initiative to learn them before jumping into code. Now, maybe we should have a few more links for the basic information.
yes...I agree with you
Actually it's depend on who is the reader. For me, I really hate those lengthy articles, especially those at Microsoft website, quite a pain in the a.. to read.
I prefer those straight to the point with the examples first. Then if the technology, through the examples, is what I need, then I will find a real book on it to read.
The code is pretty neat but you havent explained how to create a host and expose these services to the client. I do understand the features of WCF but building something from scratch should be simple and start from the beginning like creating a project and then implementing the interface in it.
very true for the sentence "this isn't something I think is always wanted but needed. I find that sometimes things just need to get done." I just explore WCF and campared WCF vs Web services and got point , actually WCF gonna be next communication platform leaving behind webservice for sack of a true SOA architecture.Good work in your example.
Hi,
I have an application architecture in which I have one WCF service and multiple .net applications on same machine. Since everything resides on same machine I'm using namedPipeTcp. .Net application/s calls the WCF service and WCF service stores the callback channel of each application in it, since it (WCF service) might need to call .Net application's side method later. Its a duplex channel mechanism. But the scenario is not Actually a async operation where request is made to WCF service and reply it sent back after some time. it is just that WCF service stores the callback channel of each application and whenever it wants to send any other message to .net client it uses the stored callback. Everything works great!!!
Instead of this architecture, we have another option..that, have one WCF service and each .net application will again host its own WCF service.. So whenever, main WCF wants to send message to .Net application it will actually send message to WCF service residing in that application.
Can you please let me know advantages/disadavantgs of both of these approaches?
Thanks Rahul
Option 1 definitely sounds like a cleaner approach.
Since you're using named pipes, if you were to do option 2 each client you create would have to create a service using a unique named pipe. You would then have to add the ability for each client to give the main service the new pipe name so it could then connect back to it.
From a performance and resource standpoint, option 1 is much better. Named pipes provide duplex communication, so you should use it. Option 2 basically mimics duplex communication using multiple one-way communication paths.
Unless the callback system doesn't provide all the functionality you need, I wouldn't recommend changing to option 2. The architecture you created is basically straight from Microsoft's recommendations.
Its a very good sample code to start working on WCF thank you SVMP
Well done! thanks.
Nice article for beginners.
Hi, Sir I have tried with the same code its looks good. But when I tried to generate proxy is giving me error. Can you help me, how should I do it by using Svcutil.exe.
The error message it is giving is there is end point.
Thanks, AbdulAleem Mohammad.
I am looking for some help in creating a client server app wherein I want to install & update client software on local lan machines by pushing from the server.
Everytime client fires up, connects to server to check for an update\patch, downloads it, updates itself & restarts if required.
How do i achieve this? Can WCF do it?
Regards, Tanmay.
Its very nice article to understand the basic concepts of WCF. Thank you, sujith
This tutorial is great. One thing good to mention is that in order to the service to be able to return reference types, I need to use [DataContract] and [DataMember]. i.e.:
Then I'm able to use:
If I don't declare the DataContract attribute, it returns an empty array.
Great tutorial and great tip from Chesare. Thanks to both!
Need not to declare DataContract at all. You may experiment with adding serializable attribute at server side and also add the same class at your client. If you already have a similar class with exact the same definition even if in different namspace, you are flexible to use it and need to refer the one declared at server side. Just make sure the type definitions are same!! I would recommend port this into a distributed library so you can avoid duplicating the shared class ( the one mentioned as DataContract) in both server and client
This is the BEST tutorial I have read that gives a simple yet clearly illustrated example of basic WCF.
Thanks!
Indeed, I found this post very helpful. I'm new to IPC programming in general, so I'm exploring my options.
Although there is one issue that really bugs me. To communicate through a Http binding, one must change the URL Access Control List on the OS for "http://localhost:8000" to allow connections. This must be done through external tools, as described in the article below:
http://msdn.microsoft.com/en-us/library/ms733768.aspx
... which is not exactly convenient for deployment purposes. My question is, can this be done programmatic-ally? Does .net have provisions for changing URL ACLs?
I think I might use named pipes instead. However, can someone shed light on how to best manage multiple clients for the same pipe server?
Suggestions would be appreciated wise.monkey [at] gmail.com
Thnks
IT HELPED ME THNX :) 4M NOOR PATEL
Thanks for the article, it works for me but I have one observation though. When server is started, no StringReverser service is created instead a service instance is created for each call and unloaded immediatly. How can I make StringReverser service run and ensure all proxy calls reach same service instance?
You'll want to set the InstanceContextMode to Single.
You can also use a different constructor for ServiceHost to pass it the object you'd like to use (instead of the type).
Thank you
Hi Thanks for the great article."What the heck is WCF" thats what I was thinking this morning and I started to google it. After exploring couple of sites I came to this article and WOW. Now I know what basically WCF works. Now I can go more deep in technical terms.
Thanks again
Thanks for this great tutorial. Is the best-simplest one that I found. In only a read I have discovered the WCF essentials.
Thanks.
The BEST WCF tutorial I have ever seen. This turorial is right to the point and gets the job done in most efficient way.
This tutorial is not very precise. You are not telling what files/projects are you creating. Just pure coding.
mk, You just need to create two console projects in a single solution. One project for the client and one for the server. Then in the page that contains the main() function delete all the code and paste in the complete examples that he shows. Also don't forget to add a reference for each project to System.ServiceModel.
Craig
Thank you for this tutorial. This gives me a great start on my project until I learn more about WCf. I like that I don't have to use svcutil.exe to create a proxy class. This is a much simpler to maintain approach.
Simple and great to start with
Thanks a lot for sharing the article........
checkout the tutorial for wcf beginners here: http://tutorials.downloadsparade.com/2011/01/wcf-tutorial.html
Thanks.
Very Nice Article, which helped me a lot.
Many Thanks for sharing this article and thanks to Chesare also.
Thank you for a simple and fully functional example with explanations. I learned the basics by working with it.
Good explanation. Thanks
Brilliant! I steel do not understand where was a mistake in my application, but when I had done everything as you say here, it finally worked! Thanks a lot!
Hi, Iam new to WCf. Tried the whole code given here. When I tried entering any text on client console and hit enter I get an Inner exception " An error occured while receiving http response to http://localhost......this could be service endpoint not using http bingimg..... could be http request context being aborted by the server(possibly due to service shutting down). See server log for more details..".
Service is started but I did not get message ""Service is available. Press to exit." on console.
Did you try downloading the source at the bottom of the article (above the comments) and running that?
basic knowledge and architecture needed that will be better
nice article....
Thanks a lot. :)
Great tutorial, Thaks a lot !
Superb example, thanks
Here is a great article at MSDN that helps you work through actions and decisions that you need to make during a WCF project: http://msdn.microsoft.com/en-us/library/hh273114.aspx
Hey thanks. This compiles it runs, it works. Couldn't get the Microsoft tutorial to run. Why did they have to use that damn svcutil utility when this is so much easy. When you have something that runs you can play around it with it find out. You can go back and read the theory and understand all the details later. So thanks again! My next mission is how to set up a proxy object
This is not concept rather implementation. I'm lost in terminologies like, binding, endpoint etc.
Is there any way i can use WCF to make communication between windows service and windows application. I have a situation like, i need to call a method in the windows service when user changes a value in the windows application. I am using Visual Studio 2008.
Thanks in advance.
Wonderful example
I'm very worried reading these comments where people who should be writing their "Hello World" programs are trying to grasp things like WCF. Before using WCF one should understand how TCP/IP works. Then they need to understand parallelism and the problems related to that. After that gathering some knowledge of how operating systems work and what is a process maybe? Perhaps then the things that are mentioned here would be safe to use. It is indeed quite scary how little code is needed to setup simple process-to-process communication, I almost hope it would not be this easy to prevent 'IT-Solution'-houses doing their horrible copy-paste programming which results in catastrophic "programs" and services. Most of these comments are not even thedailywtf funny anymore.
Basically you are asking all developers who wants to use web service to do a degree in computer science
hay m getting this error when m running server side project
HTTP could not register URL http://+:8000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).
-------- n getting this error on client side
{"Could not connect to http://localhost:8000/Reverse. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8000. "}
my id: parasgreens@gmail.com
Take a look here : http://msdn.microsoft.com/en-us/library/ms733768.aspx You need to add your url address as well as port on URL access control list in OS.
Hi Paras,
Windows only permits the address "http://localhost:8732/Design_Time_Addresses/[anything here]" by default. (e.g. "http://localhost:8732/Design_Time_Addresses/Reverse" will work)
This is a security feature but you can later override it.
Amazing tutorial thanks a lot!
gud one
Nice tutorial!
Nice one!!!
Good tutorial. Thanks
Good one ..Cool
A very good tutorial as the others on this site. Thank you very much.
Shouldn't your string reverser implement IChannel? I was wondering how are you supposed to close or do whatever is the opposite to CreateChannel (which must be something since you cannot have unlimited channels), and seems like that's handled by the IChannel.
Hi all,
Please explain below concepts for beginner level and request to provide us the ref link and ppt if any.
WCF Architecture & Advantages contracts &Bindings Consuming WCF in ASP.NET application. Hosting WCF Handling Errors by Using WCF.
I have interview on Thursday before that anyone can help me on below concepts its will be grateful.
Thanks SS
Hello, I am getting this error on client: {"Could not connect to http://localhost:8000/Reverse. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8000. "}
Any help would be appreciated. I have looked at a previous message but only the namespace reservations was addressed.
man great tutorial - it was very usefull for me, but still have one problem: how do you set the size of that "maximum string content length quota"? When you try to pass a string longer than 8192 charachters, a faultException will be thrown. I tried to changed these lines: --- ChannelFactory pipeFactory = new ChannelFactory( new NetNamedPipeBinding(), new EndpointAddress( "net.pipe://localhost/PipeReverse")); --- with those ones: --- NetNamedPipeBinding binding = new NetNamedPipeBinding(); binding.MaxReceivedMessageSize = Int32.MaxValue; binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue; ChannelFactory pipeFactory = new ChannelFactory( binding, new EndpointAddress( "net.pipe://localhost/PipeReverse")); --- but no success. Can you help with this problem?
nearly correct: you have replaced your mentioned lines on server side. then everything works fine!
Fine tutorial, but I wonder if it's possible to run the server on a computer and the client on another computer on the same network?
Exe: pc2 pc1 192.168.1.100 and 192.168.1.101.
I tried to replace "localhost" by IP, but not worked, the client returns the error 10060, "server not responding"
Thanks for sharing this article. Nice article.
Fantastic tutorial! Thank you very much for the tips!
Thanks for sharing your WCF knowledge, it was a wonderful article and tutorial sample source code,
hello, thank you for the great tutorial. I want to do this between a "Windows Service" and "Application". i tried to do it but it didn't work. please can you help. should there be any difference for windows services ( it hosts the wcf service ). i even tried using config file. the error i get it that "the service is not available, make sure its running and exposed".
This is really a great tutorial. Thnx for sharing Wedding Photography Vancouver
Superb!!! Well done and thank you
This is by far the simplest example i have found on internet.can you please post an article about how to write WCF Duplex service with exmaple & detailed explanation.Thank you very much...
Really Perfect, the way it is written is amazing