Dennis van der Stelt

The most votes generally drown out the best votes

Community

News

  • Meet me at PDC08

Email Notifications

I read...

I Use...

Tags

Recent Posts

Archives

WCF Simple Example

On my WCF Introduction post I received a trackback to an example that should be really simple to start WCF with. I'm not here to judge the post (although I could ;-), but it got me thinking. Although I created some small posts on how WCF works, together it might still be too much for people that just want to see the simplest example. So this post is about that example.

There are two ways to present this. In this example I'll use as little code as possible in as few locations as possible. The other way is using the WCF Service Library project that comes with the VS2005 WCF Extension but requires a lot more code, text, etc. More about the in another post.

I'm not judging, but the other post by Ralf Sudelbücher has only one project containing both service, host and client. I'm using two projects, because WCF is all about getting clients to communicate with a service. Let's start.

  1. First, install Visual Studio 2005, .NET Framework 3.0 and the .NET Framework 3.0 WCF/WPF extensions.
    You don't need the SDK. And don't worry about the November 2006 CTP status, this is the latest version.
  2. Open Visual Studio 2005 and create a new console application project, called "Host". 
  3. Add a reference to the project for the System.ServiceModel assembly. It's the core assembly used by WCF.
    If you're using Visual Studio 2008, check out this article if you have problems with adding the service reference.

    add_reference
  4. Add a using statement at the top of your class for System.ServiceModel.
    using System.ServiceModel;
  5. Create a service contract and implement it in the Program.cs file, directly under your Program class. In this example I'm expecting a name and concatenate this to "Hello " and return this immediately.
    [ServiceContract]
    class HelloService
    {
      [OperationContract]
      string HelloWorld(string name)
      {
        return string.Format("Hello {0}", name);
      }
    }
  6. In your Program class, inside the static Main method we need code to host our service. We'll add two endpoints, one for our service and one for extracting the metadata.
        1 static void Main(string[] args)
        2 {
        3   // We did not separate contract from implementation.
        4   // Therefor service and contract are the same in this example.
        5   Type serviceType = typeof(HelloService);
        6 
        7   ServiceHost host = new ServiceHost(serviceType, new Uri[] { new Uri("http://localhost:8080/") } );
        8 
        9   // Add behavior for our MEX endpoint
       10   ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
       11   behavior.HttpGetEnabled = true;
       12   host.Description.Behaviors.Add(behavior);
       13 
       14   // Create basicHttpBinding endpoint at http://localhost:8080/HelloService/
       15   host.AddServiceEndpoint(serviceType, new BasicHttpBinding(), "HelloService");
       16   // Add MEX endpoint at http://localhost:8080/MEX/
       17   host.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), "MEX");
       18 
       19   host.Open();
       20 
       21   Console.WriteLine("Service is ready, press any key to terminate.");
       22   Console.ReadKey();
       23 }

    At line 7 we're instantiating our ServiceHost object, specifying a base address at localhost on port 8080.
    At line 15 we're adding our endpoint, using basicHttp, for our service.
    At line 17 we're adding our metadata endpoint. For this we also need to specifiy the MetadataExchange behavior, which we do at line 10, adding it to our ServiceHost at line 12. At line 11 we're enabling HttpGet, which means we can view the metadata using a browser.

    At line 19 we just open the host and everything should work fine. Lines 21 and 22 are waiting on confirmation of a user to close the console application, automatically closing our ServiceHost and thus our service.

    We only need to ad a using statement for the System.ServiceModel.Description because adding a MEX endpoint using code requires this namespace.
    using System.ServiceModel.Description;
  7. Now this is done, let's try and run our service. If all goes well, we'll see the message that the service is ready. You can check it by opening up a browser and visiting http://localhost:8080/
  8. Now we need to create our client. Add a new Windows Forms project called "Client" to our solution.
  9. Right-click the "Host" project and choose "Debug" and then "Start New Instance". Then right-click the "Client" project and select "Add Service Reference". In the dialog that appears type in the address http://localhost:8080/ and press "OK". Now you should have a new folder in your "Client" project with the reference to your service. Stop the service that's still running in the background.
    The System.ServiceModel assembly should be referenced now, the app.config has been added and modified as well as a proxy class under your "localhost" service reference.
  10. On your form in the "Client" project, add a textbox and a button. Double-click the button.
  11. Add three lines to your button-click event.
        1 private void button1_Click(object sender, EventArgs e)
        2 {
        3   localhost.HelloServiceClient proxy = new Client.localhost.HelloServiceClient();
        4   string result = proxy.HelloWorld(textBox1.Text);
        5 
        6   MessageBox.Show(result);
        7 }
  12. Again, right-click the "Host" project and select to start a new instance and do the same for your Windows application. Then fill in your name and press the button.

Congratulations, the most easy and fastest way to create a WCF service. Source-code can be downloaded here.
UPDATE : The zip file was broken, but is now fixed again.

Comments

Ralf said:

If I inspired you to boil down your previous code to come up with an even simpler scenario to introduce WCF, I´m happy. Maybe we should start a competition on how few lines are necessary to use get started with WCF? ;-)

However, you mentioned twice you wanted to abstain from commenting my sample. Why? What´s wrong with it? I don´t think using two processes is necessary for a WCF introduction. It just makes it more difficult to get the whole thing running. WCF makes process boundaries pretty transparent, so I don´t think they are needed.

Rather much more important I deem separating contract from implementation - which you neglect. Also a WinForms application does not make WCF easier to understand.

Also, do you think meta data exchange makes understanding WCF easier? Hm...

But anyway, I´m happy you took up the challenge ;-)

Cheers

Ralf

# May 14, 2007 12:00 AM

Dennis van der Stelt said:

Hi Ralf,

The single project to get everything going isn't what WCF is about, I think. So that's why I always need at least two projects.

The thing I ment was you were creating client and service by means of multi threading. That doesn't make the example easier to understand, just a lot harder.

The other thing about process boundaries. I'm not sure what you mean there. With WCF you ALWAYS have two process boundaries, because your service/host and client aren't on the same process. In WCF vNext that might be possible, but currently it isn't. Even though you only have 1 project and start everything on multiple threads, still everything is serialized into XML and send cross process boundaries.

# May 14, 2007 10:51 AM

Ralf said:

Hi, Dennis,

I understand what you say, you need two projects. And I agree in the end WCF mostly will be used in such scenarios. But two projects are less easy to set up in VS than one ;-) That´s the only reason I used one project or even just one file. I´m just concerned about getting a WCF sample up and running with the least number of steps and with the least number of files. So I guess we can agree that this is possible only with multithreading like I did it ;-)

In addition, though, I think, WCF is not about a particular "distance" of client and service. It´s perfectly fine to use WCF within the same process, e.g. to cross AppDomain boundaries. And it´s a means to hide "distance" in general so I don´t have to care whether code is running in the same or a different AppDomain or in another process or on another machine. So letting two threads communicate using WCF for me is perfectly valid - albeit maybe a little bit unusual.

What you say about process boundaries does not seem 100% correct to me. You´re right in that messages are always passed between client and service (host). Data always will be serialized. But a process boundary - as you can see in my example - is not necessarily crossed. My client and service host live in the same process and that´s just fine with WCF. However, in a larger scenario I would not just provide a TCP endpoint for intranet communication but also a named pipe endpoint for fastest communication on a single machine - possibly within the same process.

But again: I was not concerned with a real life example of WCF usage but a most easy demonstration.

-Ralf

# May 19, 2007 11:43 AM

Craig Mellon said:

Just like to say thanks for a great article. I just started looking at WCF today, and your article has really helped me get started.
# June 9, 2007 12:05 AM

Earle Beach said:

Thanks a lot! After crashing and burning with MS's "Technology Samples," it's really a great feeling to be able to build a sample that works the first time.
# June 22, 2007 10:38 PM

dylan H said:

Hi,

I just wanted to thank both Dennis and Ralph for your examples. By attempting to create simple example in different ways,  you appeal to varied audiences. Looking at both of your examples will has help get closer to delima I am faced with with.

Thanks

# June 30, 2007 11:50 PM

David T. said:

I wouldn't normally make a WCF project as only one project, so the example of two projects is useful.  However, Ralf's example showed how it could be done in a multi-threaded way - something I would not have known to do.  Thanks to both of you.

# July 19, 2007 4:04 PM

Jeffrey Chilberto said:

WCF example application using headers to pass information between host and client.

# July 26, 2007 3:34 AM

Jeffrey Chilberto said:

The following is an example of passing information in WCF's operation context message headers. In

# July 26, 2007 3:52 AM

Jeffrey Chilberto said:

The following is an example of passing information in WCF's operation context message headers. In

# July 27, 2007 1:14 AM

Jeffrey Chilberto said:

The following is an example of passing information in WCF's operation context message headers. In

# July 27, 2007 1:22 AM

Sanjay said:

Hi Dennis,

Thanks for ur example.

My quest for understanding WCF finally ended by ur example.

# August 21, 2007 12:05 PM

Sivakumar said:

Very nice example with explanation

# September 19, 2007 11:11 AM

Meher said:

Hi... Dennis

I started 3.0 recently and was confused how to start the WCF. Your article is so helpful

Thanks

# October 10, 2007 3:17 PM

Pasquale said:

I couldn't use the example until I had installed not only Visual Studio 2005 and .Net Framework 3.0, but also the "Windows SDK" for .Net (Vista version) and most importantly "Visual Studio 2005 extensions for .NET Framework 3.0" available at: www.microsoft.com/.../details.aspx

Neither this example nor anywhere else I looked explained that.

I can't help wondering where the world will be in 5 years when everyone needs to upgrade from WCF and we are all captive the black magic of this technology.

# October 19, 2007 3:15 PM

Dennis van der Stelt said:

@Pasquale : Just updated the article, you're right, it should've been in there. Other people can thank you for it now. :)

However, you don't need the SDK and your link is to the WF extensions, not the WCF/WPF extensions.

# October 19, 2007 3:28 PM

Pasquale said:

Right, I'm told both WF and WCF/WPF extensions are needed.  Here's the link to the WCF/WPF extensions:

www.microsoft.com/.../details.aspx

# October 19, 2007 3:49 PM

SK said:

Great, Just one word.

ThankYou

# October 25, 2007 5:08 PM

kenny said:

Thank your example, it is pretty helpful and clear to understand the WCF structure in inline code.

you are right, To separate the host and client to different projects makes the route and the concept much more clear, even I modified the binding address from 'localhost' to other '192.168.xxx.xxx' and run the service on other machine, it will be better.

one thing need notifiy is service reference name 'localhost' would be customized to other name by changing the reference name or in its property, it made me confuse at the begining.

Do you have other example using IIS to host the service,config and expose it in web.config? I would like to enjoy it.

# October 31, 2007 4:13 PM

Dennis van der Stelt said:

Kenny, good idea! I'll create an example and tutorial for that. But it'll probably be next week.

# November 1, 2007 10:32 AM

Alan said:

One or Two project samples are nice so long as it's short and simple like this one and i don't see what the fuss is about.

# December 18, 2007 4:03 PM

Dennis van der Stelt said:

Alan, what do you mean with 'the fuss'?

# December 19, 2007 8:26 AM

Sangram said:

Good One

# February 27, 2008 12:54 PM

Waqt said:

Good one it helped me a lot thanx

but can u provide the steps for WCFClassLibrary also

# March 12, 2008 1:16 PM

newbie said:

Nice sample!!!  yes this is what i have been looking for too, nice and simple.  would you happen to have a WF State machine simple sample too?

# March 21, 2008 2:34 AM

jeff said:

Trying to use this with VS 2008 and I cant seem to set the ref to the host service while it is running. Any ideas? All the options on the Client project are grayed out when the host is running.

# March 28, 2008 7:41 PM

Dennis van der Stelt said:

Jeff, check out the following post I just wrote for the solution:

bloggingabout.net/.../quot-add-service-reference-quot-is-disabled.aspx

# March 28, 2008 9:17 PM

Robbie Huttenhower said:

Great article.  I like simple.

# May 22, 2008 10:50 PM

Sujith said:

Great one, It was really helpfull

# June 3, 2008 8:55 AM

David Rogers said:

Nice simple article. However, I ran into a gotcha immediately:

"HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see go.microsoft.com/fwlink for details)."

Apparently, metadataexchange requires elevated privileges? Is this something I am getting because this is VS2008? Vista Ultimate? Any ideas on how to be able to tell Visual studio to debug with elevated privileges?

Thanks,

David

# June 8, 2008 11:23 PM

Amit Dave said:

Hi

First of all would like to thank you for such an encouragin example;

and am sure this is just a begining would like to have more detail and indepth use of WCF, could you just let us know that how wsdl and wcf are inter-related with each other and more inportantly scenarios suitable for WCF...

thanks again and expect such articles in future as well...

# June 9, 2008 10:55 AM

Dennis van der Stelt said:

@David : It's a Vista 'problem'. Run VS2008 as administrator (which I always do), or check out this article : blogs.msdn.com/.../addressaccessdeniedexception-http-could-not-register-url-http-8080.aspx

@Amit : There are more articles on my weblog, just click the "WCF" tag in the tag-cloud.

I'll make a post about WSDL and MetadataExchange in the future to try and explain it the simple way! :)

For now I can say the "WSDL" is the "WebService Description Language". You can enable it via the metadata service behavior. WSDL is like an "addon" feature on MetadataExchange so that consumers (clients) that don't support metadataexchange are still able to retrieve the WSDL.

# June 24, 2008 12:18 PM

chandru said:

Thank you very much.Its really useful for beginners in WCF.This real time exmaple helped me to understand better.

# July 9, 2008 8:49 AM

Venkat R Y said:

I am new to WCF this example has helped to understand how WCF works... Thanks very much Dennies.

# July 13, 2008 10:22 AM

prabhu said:

Thank you, Simple example has helped lot to understand WCF

# July 24, 2008 6:40 AM

Aravinthan said:

Hi Dennis,

Thanks a million. I am a newbie to the WCF and simply couldn't get a clue of how and where to start. Your simple example gave me a solid starting point. Once again.. thanks a lot and keep up the good work.

# July 24, 2008 1:27 PM

abraham said:

Dennis,

Your's was the first WCF example that I was able to get working successfully, Thank you.

I have been trying one example after another in the hope that I could better wrap my head around WCF concepts once I had a working model to play with.

Your example creates a temporary web service. How does one go about deploying the service to IIS 5 & 6?

Appreciate the hand-holding.

# August 5, 2008 8:44 PM

Kenneth said:

Thanks for the great example. But I wonder if you can tell me why my service reference will not update. I have changed the endpoint addresses to a foreign machine's address and I can view the output in a browser when I navigate to that ip. However, when I try to do "Update Service Reference," it errors out. It is not a firewall issue as I can browse to the machine, but what else could it be?

Thanks.

# August 13, 2008 4:12 PM

sandhya said:

Really this is very nice example for those who started 3.0

can u please give some more examples

thanks and regards

sandhya

# August 14, 2008 3:36 PM

Dennis van der Stelt said:

@abraham: I'll try and post something soon about that.

@Kenneth: Normally you can only see the nice HTML page when going to the service when you're browsing locally on the machine (or server). Maybe you don't have a MEX endpoint on the server so it can't update?

Either way, when from development the service its interface hasn't changed, you should be able to change the url of the service in the web.config or app.config and be fine. You don't have to actually update the service reference, that's just for updating the underlying proxy code, for when you've changed your interface (ie. added new operations, changed parameters, etc).

# August 24, 2008 6:20 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)