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.
using System.ServiceModel;
[ServiceContract]
class HelloService
{
[OperationContract]
string HelloWorld(string name)
return string.Format("Hello {0}", name);
}
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 }
using System.ServiceModel.Description;
1 private void button1_Click(object sender, EventArgs e)
3 localhost.HelloServiceClient proxy = new Client.localhost.HelloServiceClient();
4 string result = proxy.HelloWorld(textBox1.Text);
5
6 MessageBox.Show(result);
7 }
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.
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
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.
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
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
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.
WCF example application using headers to pass information between host and client.
The following is an example of passing information in WCF's operation context message headers. In
Hi Dennis,
Thanks for ur example.
My quest for understanding WCF finally ended by ur example.
Very nice example with explanation
Hi... Dennis
I started 3.0 recently and was confused how to start the WCF. Your article is so helpful
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.
@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.
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
Great, Just one word.
ThankYou
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.
Kenny, good idea! I'll create an example and tutorial for that. But it'll probably be next week.
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.
Alan, what do you mean with 'the fuss'?
Good One
Good one it helped me a lot thanx
but can u provide the steps for WCFClassLibrary also
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?
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.
Jeff, check out the following post I just wrote for the solution:
bloggingabout.net/.../quot-add-service-reference-quot-is-disabled.aspx
Great article. I like simple.
Great one, It was really helpfull
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
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...
@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.
Thank you very much.Its really useful for beginners in WCF.This real time exmaple helped me to understand better.
I am new to WCF this example has helped to understand how WCF works... Thanks very much Dennies.
Thank you, Simple example has helped lot to understand WCF
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.
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.
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.
Really this is very nice example for those who started 3.0
can u please give some more examples
thanks and regards
sandhya
@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).
thank you, very helpful article !
Suresh .... where's the Choclate?
HTTP could not register URL http://+:8080/ because TCP port 8080 is being used by another application.
I am getting this exception for each and every WCF example that I try to run.
I am a student and rwally need somebodys help.
Please tell me how to go about it in detail since I am a student I really understand only if told me in detail please.
@Pooja : That's the problem with students, if you don't tell them in detail, they won't know. That's not what we need at companies! Nah, just kidding! ;)
Anyway, only one application can host something at a specific port. So if some other tool is using 8080, use a different port. You can also use 81, or 8081 or any number. I also like port 1337 :)
It's also possible that Vista doesn't allow you to open the port and that VS2008 (or .NET actually) reports a strange message. Are you running Vista? And if so, are you running VS2008 in Administrator mode?
"@abraham: I'll try and post something soon about that."
Just a reminder if you can make the time.
I admit once I got your example working I was able to implement a nice prototype that involves queuing messages on MSMQ and processing them asynchronously.
I still have run into trouble deploying to IIS however :(
Thanks for getting us all started.
@abraham: You're right, and promised is promised. I'll set a reminder in Outlook
Excellent example for demonstrating the basics of WCF. Just what I needed - thanks!
Great article, thanks for taking your time an putting it together.
I am using visual studio 08
I created the host and tried to test it using IE7 but it returns an error.
any solution......
darge : You seriously can't expect me to help you with so little information.
Nice Article..Thanks Dennis van der Stelt
Thanks Dennis,
This is a very cute and rich example to start with. Expect more examples to lead us to grow better on different scenarios.
Really appreciate for what you deliver.
regards
Sunil Kurian
Thanks !
This help to understand
All the steps till 8 were successful however I dont find localhost.map and localhost.cs file under Service Reference. app.config is available though. I am stuck with the button event coz of that.
I am using VS 2008. I could see those files in your downloaded code after successfully opening in VS 2008.
Please help.
@Vaishnavi : Were you able to create the "Service Reference" in VS2008 in your client project? ie Client Project being the project that would call the service?
Cooollllllllllllllll
I referenced your arrticle in a submission to CodeProject.
www.codeproject.com/.../WCF_MSMQ_Integration.aspx
Hope that's ok.
@abraham : no problem, of course!!!
Hey how can i host service and client on different machines please provide me a url if u already hav a sample on it
@arun: Just run the service on another machine and change the url in your web.config on your client... If that's what you mean?
What a great example for a beginer.
Thanks alot for this article.
I'm a VB.NET programmer and have managed to convert your example, albeit the following line.
localhost.HelloServiceClient proxy = new Client.localhost.HelloServiceClient();
Vb does'nt recognise 'Client.localhost.HelloServiceClient()
Can you help?
@Barney : Maybe remove Client or Client.localhost altogether. If it does recognize localhost.HelloServiceClient then you're okay, because you need exactly the same on the other end :)
Hi dennis...I'v successfully done a simple wcf application using your code. I needed to use a wcf service using java client though..Can you help me in this by providing the client code of your apllication in java????
@Sally : Java? What's that? :) But seriously, I could not tell you how to do that as I have no idea. But if you lookup how to connect to ASP.NET Webservices from Java or how to do SOAP 1.1 or SOAP 1.2 style services, than you should be okay.
Some examples:
www.codeproject.com/.../WSfromJava.aspx
stackoverflow.com/.../301120
forums.sun.com/thread.jspa
and from MSDN
msdn.microsoft.com/.../ms953968.aspx
As far as I know, you do need some extra framework though. It's not by default in java.
thanks a lot neways...i'l check out d refernces
Thanks Dennis - did you mangage to get this example to work across two different machines?
So far i've been unable
@Barney : Sorry mate, but your last comment can't be approved by the system. Maybe it's because it suspects HTML in the comment. I'll have to look into it.
But... Is your service actually running? If the service isn't running (ie. the host project should be started and doing it's work) than no one will ever be able to find the service.
About the last comment, yes I have! :)
First try to get it working with basicHttp and if that's working, try other bindings. A lot of bindings can give problems with security. For example netTcp is secure by default, but if you don't know that and/or the service is in another domain or in a workgroup, you can run into all kinds of problems.
If you want to use authentication, try to use Windows authentication as it's the easiest. Almost everything else needs X509 certificates.
Your simple example was very helpfull. Thanks for making my day.
Didier M
Installed all Net.3.5 SP1 VC 8, wcf framework,
Still getting
------ Build started: Project: wcf_node, Configuration: Debug Any CPU ------
C:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v3.5\Debugger\BCL\System.Core.dll" /reference:"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v3.5\Debugger\BCL\System.Data.DataSetExtensions.dll" /reference:"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v3.5\Debugger\BCL\System.Data.dll" /reference:"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v3.5\Debugger\BCL\System.dll" /reference:"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v3.5\Debugger\BCL\System.ServiceModel.dll" /reference:"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v3.5\Debugger\BCL\System.Xml.dll" /reference:"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v3.5\Debugger\BCL\System.Xml.Linq.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\wcf_node.exe /target:exe Program.cs Properties\AssemblyInfo.cs
D:\_FL\wcf_node\wcf_node\Program.cs(11,6): error CS0246: The type or namespace name 'OperationContract' could not be found (are you missing a using directive or an assembly reference?)
D:\_FL\wcf_node\wcf_node\Program.cs(11,6): error CS0246: The type or namespace name 'OperationContractAttribute' could not be found (are you missing a using directive or an assembly reference?)
D:\_FL\wcf_node\wcf_node\Program.cs(8,2): error CS0246: The type or namespace name 'ServiceContract' could not be found (are you missing a using directive or an assembly reference?)
D:\_FL\wcf_node\wcf_node\Program.cs(8,2): error CS0246: The type or namespace name 'ServiceContractAttribute' could not be found (are you missing a using directive or an assembly reference?)
@Marius : Did you use "Using System.ServiceModel" at the top of your code as I point out in bullet 4?
When your cursor is on the OperationContract or ServiceContract attribute, a small red line should appear, if you didn't include the "Using System.ServiceModel". The text should also be black if you didn't. You can then press CTRL+. (So press CTRL and the . at the same time) and it should popup a small menu that allows you to add the using statement.
If you _did_ use the using statement, both attributes should display in a bluish or greenish color, just like the code snippet 5 displays.
Dennis
Thanks - got it working over different servers - forgot to amend the app.config to new server name.
Brilliant example by the way
Hello Dennis,
Your sample is excellent and I'm wondering if it's possible to use it in Silverlight application? I've tried that, but there's HelloWorldAsync method that accepts string argument, but returns void. Do you happen to know how to overcome this?
Thank you in advance.
Goran
Hi Goran,
Yes I do. In Silverlight they don't allow you to wait for the result, because that would mean the screen would lock up. Therefor everything is asynchronous.
There should be an event, called HelloWorldCompleted. You recognize it in the intellisense list by the lightning icon. Select it, type += behind it and press [TAB] a few times.
A new method should be created in which you can handle the return value.
It should look something like:
public void MyButtonClick()
HelloServiceClient svc = new HelloServiceClient();
svc.HelloWorldCompleted += new EventHandler<HelloWorldCompletedEventArgs>(svc_HelloWorldCompleted);
svc.HelloWorld("dennis");
public void svc_HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs e)
string result = e.Result;
But that's from the top of my head, so I could be wrong somewhere.
If it doesn't work, let me know.
Its very good example.
Hi Dennis I like your example! thanks.
HI,
nice example, could u give an example code of WCF web service returning data from SQL Server.
thanks,
hallo,
i am using from today VS 2008. so i want to try tu use WCF on it. but i couldn't the Service references by the Way above. does anybody have any experience about it?
thanks
ich mean, i couldn't add/create the Service references by the Way above
You mean you've got this problem? What's your actual problem?
Good Article
Thanks!
kapil
Dennis van der Stelt, Your efforts are appriciated.
I am new to WCF. based on your article, I am able to create and run WCF ..... cool
Its really useful for beginners in WCF.
hi,
at Host.Open() i get following exception
Message="HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see go.microsoft.com/fwlink for details).
i visited microsoft link, but is not clear what command i have to key and if i need to open command windows from netsh tool. I'm working with win7.
can you help me?
Thank you very much!
This example was exactly what I needed :)
Andrew
hi i think these posts also will be useful for you in wcf :
ledomoon.blogspot.com/.../getting-started-wcf-1.html
ledomoon.blogspot.com/.../getting-started-wcf-2-wcf-terms.html
ledomoon.blogspot.com/.../getting-started-wcf-3creating-your.html
Thanks so much!
This sample as a start point!
Please tell me how to create client in VS 2005
@bas : Maybe this article will help : bloggingabout.net/.../WCF-Part-4-_3A00_-Make-your-service-visible-through-metadata.aspx
It says something about "svcutil" and how to run it. I'm not sure if, after install of .NET 3.0 SDK, the "Add Service Reference" is available in VS2005. If not, use svcutil.exe, that's what VS2008 uses itself.
i am having a problem while running this application,as u are saying right click on host->debug->new instance then click on client -> service refrence ,its not allowing to add service reference ,its showing in disabled form.without doing debug-> new instance ,if I do the same ,then its showing error occured,as its not taking http://local host/8080/ ,saying no service is there.please look into the issue and let me know if you can fix it.
@dinesh : Check out this article : bloggingabout.net/.../quot-add-service-reference-quot-is-disabled.aspx