Home .NET A simple example of using WCF inVisual Studio 2010.Part 1

A simple example of using WCF inVisual Studio 2010.Part 1

by admin

There are two parts waiting for you :

A simple example of using WCF inVisual Studio 2010.Part 1
It’s been a long time since I wrote the original post A simple example of using WCF This was before Visual Studio 2008 came out, and a lot has changed since then. Since a lot of people are still asking questions inthe comments of that post, let’s look at what we currently have to do to get the service up and running, and to access it from a client application.
This time we’ll start with classlibrary assembly (DLL) and we’ll also put the service inside the console application. The client will again use the Windows Forms application. Although we’re doing everything in Visual Studio 2010, a lot of it applies to VS2008 as well. I’ll mention when it won’t and I’ll suggest an alternative. This time I’ll be a little more detailed about what we need to do, so this post will be a little more than the original post.

Project creation

First, create a newclass library where we will define the service itself. Select New Project and Class Library as the project template. Specify the project name "EmailService" and the solution name "WCFSimpleExample2010". If you cannot set a name for the solution, check whether the option Create directory for solution

Contract creation

First, we’ll create a contract with only one method, or operation, as they’re called in WCF. Rename the file to IEmailValidator.cs and create an interfacewith the same name.
Now add a signature for the ValidateAddress method that takes a single EmailAddress argument of type stringand returns a boolean value. It’s a common interface, nothing complicated.

    public interface IEmailValidator

  1. {
  2. bool ValidateAddress( string emailAddress);
  3. }
  4. * This source code was highlighted with Source Code Highlighter

    Now we have to tell WCF that this is our contract. We do this by adding attributes, but first we must add a reference to System.ServiceModel. Right-click on the project and select Add reference , then select System.ServiceModelfrom the list. I use Visual Studio 2010 Pro Power Tools , so my image in the screenshot may be different from yours, but the idea is the same.
    Now you can add attributes to the interface. Above the interface definition, put the attribute ServiceContract , and above the operation, the attribute OperationContract Add the directive using System.ServiceModel at the beginning of the code file, or let Visual Studio do it for you when you hover over one of the attribute names. If you have entered it correctly and case-sensitive, you can press CTRL +. and then a context menu will appear that will allow you to add the using directive automatically. Your interface should look like this

    1. [ServiceContract]

    public interface IEmailValidator

  5. {
  6. [OperationContract]
  7. bool ValidateAddress( string emailAddress);
  8. }
  9. * This source code was highlighted with Source Code Highlighter

    Creation of service implementation

    Now that we’ve created the contract, we have to write code for the service to actually do what we want to do. Create a newclass that implements the interface. We will use a regular expression to check the email address and returntrue if it is correct. You must either type something like the following code or write your own. 🙂

      public class EmailValidator : IEmailValidator

    1. {
    2. public bool ValidateAddress( string emailAddress)
    3. {
    4. Console WriteLine( "Validating: {0}" , emailAddress);
    5. string pattern = @"^([0-9a-zA-Z]([-.w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-w]*[0-9a-zA-Z])*.)+[a-zA-Z]{2, 9})$" ;
    6. return Regex.IsMatch(emailAddress, pattern);
    7. }
    8. }
    9. * This source code was highlighted with Source Code Highlighter

      Now you have the two most important classes for your service. You don’t actually have to use an interface, but it’s best practice. So you can inherit multiple interfaces, and you can implement different versions of the interfaces.

      Host creation

      As already mentioned, we will use the console application as the host. Add a new project and now select ConsoleApplication as the project template. Name it "ConsoleHost".
      Add a link to System.ServiceModel again, and to the project EmailService In your Main method, create a ServiceHost object and pass it the correct arguments in the constructor, as shown below.

      1. Type serviceType =

      typeof (EmailValidator);

    10. Uri serviceUri= new Uri ( "http://localhost:8080/" );
    11. ServiceHost host = new ServiceHost(serviceType, serviceUri);
    12. host.Open();
    13. * This source code was highlighted with Source Code Highlighter

      On line 4, we create a ServiceHost object. It gets the implementation type of our service as the first argument. And the base address as the second argument. You can read more about base addresses here and more about posting here The type is defined in line 1, the base address in line 2. Finally, on line 5, our host is started.

      WCF4: Standard Endpoints

      This is already a feature of the .NET Framework 4.0 and cannot be done in the previous version of .NET. Standard endpoints are a new feature created to make configuring your service less of a hassle. I would like to explicitly define everything in detail, so that everyone knows what’s going on. But in our example, everything works very well as it is. If you’re not using . NET 4.0, you can read no further and go to part 2 which will be published later.
      You can add standard endpoints yourself by adding host.AddDefaultEndpoints (); to the code, just before the host.Open (); line.
      How can we see that the endpoints are configured by default? I have a little script from from the distant past. , which displays everything that’s running now. I won’t go into details, just insert the following lines of code after host.Open ();.

        #region Output dispatchers listening

      1. foreach ( Uri uri in host.BaseAddresses)
      2. {
      3. Console WriteLine( "t{0}" , uri.ToString());
      4. }
      5. Console WriteLine();
      6. Console WriteLine( "Number of dispatchers listening : {0}" , host.ChannelDispatchers.Count);
      7. foreach (System.ServiceModel.Dispatcher.ChannelDispatcher dispatcher in host.ChannelDispatchers)
      8. {
      9. Console WriteLine( "t{0}, {1}" , dispatcher.Listener. Uri ToString(), dispatcher.BindingName);
      10. }
      11. Console WriteLine();
      12. Console WriteLine( Press <ENTER>to terminate Host" );
      13. Console ReadLine();
      14. #endregion
      15. * This source code was highlighted with Source Code Highlighter

        You now have the ability to see the endpoints as inthe first screenshot below. You can use your browser to go to the service URI and look at the standard MEX endpoint.
        As you can see, this tells us that the MEX endpoint (aka metadata) is not yet configured. There is now an easy way to do this via the newstandard endpoints. My first impression was that this would work.

        1. Type serviceType =

        typeof (EmailValidator);

      16. Uri serviceUri= new Uri ( "http://localhost:8080/" );
      17. ServiceHost host = new ServiceHost(serviceType, serviceUri);
      18. host.AddDefaultEndpoints();
      19. // This actually doesn't just simply work.
      20. host.AddServiceEndpoint( new ServiceMetadataEndpoint());
      21. * This source code was highlighted with Source Code Highlighter

        On line 5 you see that we add the standard endpoints, and on line 7 we add the ServiceMetadataEndpoint or MEX endpoint. Unfortunately, the Metadata behaviorcannot be added by itself, so you still have to do it yourself. Another way is to be able to specify inthe configurationthat you want to include metadata. Another newfeature in WCF4 is the ability to inherit configs. You can specify in machine.config or in your local configurationwhat should be enabled by default for WCF services. I recommend that you don’t do this in machine.config, but that’s just my opinion. Here’s how I implemented it in my project configuration, the app.config file of our console host application. Note that in the next article we will do it the old fashioned way, the way that will work in Visual Studio 2008 and which I prefer myself.

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

        1. < configuration >
        2. < system.serviceModel >
        3. < behaviors >
        4. < serviceBehaviors >
        5. < behavior >
        6. < serviceMetadata httpGetEnabled ="True" />
        7. </ behavior >
        8. </ serviceBehaviors >
        9. </ behaviors >
        10. </ system.serviceModel >
        11. </ configuration >
        12. * This source code was highlighted with Source Code Highlighter

          As you can see I didn’t specify a name for the behavior, in WCF4 that means it will be used by all services. It also means that each service needs a base address for the HTTP endpoints.
          For reference, here is the code for our console host application :

            static void Main( string [] args)

          1. {
          2. Type serviceType = typeof (EmailValidator);
          3. Uri serviceUri= new Uri ( "http://localhost:8080/" );
          4. ServiceHost host = new ServiceHost(serviceType, serviceUri);
          5. host.Open();
          6. #region Output dispatchers listening
          7. foreach ( Uri uri in host.BaseAddresses)
          8. {
          9. Console WriteLine( "t{0}" , uri.ToString());
          10. }
          11. Console WriteLine();
          12. Console WriteLine( "Number of dispatchers listening : {0}" , host.ChannelDispatchers.Count);
          13. foreach (System.ServiceModel.Dispatcher.ChannelDispatcher dispatcher in host.ChannelDispatchers)
          14. {
          15. Console WriteLine( "t{0}, {1}" dispatcher.Listener. Uri ToString(), dispatcher.BindingName);
          16. }
          17. Console WriteLine();
          18. Console WriteLine( Press <ENTER> to terminate Host" );
          19. Console ReadLine();
          20. #endregion
          21. }
          22. * This source code was highlighted with Source Code Highlighter

            Gaining access to metadata

            Now we can open Internet Explorer or any other browser, start our console host application (otherwise the endpoints will not be available) and go to the URI of our service : http://localhost:8080/
            If you see a screen with a link to the WSDL, you have most likely succeeded in creating the service.

            Creating a client application

            Now we will add another project which will call the service and we will be able to check if the specified email addresses are valid, or at least satisfy our regular expression.
            Add a new console application and this time name it ConsoleClient. Make sure that your service (host) is running and not in debug mode. The easiest way is to set your ConsoleHost project as your start project and press CTRL + F5 to run it in non-debug mode.
            Now we need a proxy class between our client and the service. There are two ways to create a proxy for our service. I prefer to do it manually so I know exactly what’s going on. I will show you this first.

            Manual creation of proxy

            To start, run Visual Studio 2010 (or Visual Studio 2008) command line and navigate to the location of ConsoleClient Since this is a Visual Studio command line, you should have access to the proxy generator svcutil.exe. Enter the following command :

            svcutil http://(parser on_habre_loh)localhost:8080/ /o:ServiceProxy.cs /config:App.Config /n:*, ConsoleClient

            This command should generate two files: a proxy service file and an application configuration file. Go back to your ConsoleClient application in Visual Studio. To make App.Config and ServiceProxy.cs available, you need to click the icon at the top of Solution Explorer as shown in the screenshot below. The new files are now displayed and you can include them in your project.

            Note : the screenshot in the console window shows the wrong namespace ConsoleHost instead of ConsoleClient.

            When we ran svcutil.exe we gave it as first argument the location of our service as specified in the host.This is the base address.The second argument is our proxy. The third argument indicates that we also want to update the configuration of the application, and ifit is not available, to create it. The last argument is the namespace for our proxy, which is currently the same as our application.

            Service call

            Now we can finally call the service. We go to the method Main in the class Program again. We now have access to a proxy class that has our service name with the suffix Client In this case EmailValidatorClient

            1. EmailValidatorClientsvc =

            new EmailValidatorClient();

          23. bool result = svc.ValidateAddress( "dennis@bloggingabout.net" );
          24. * This source code was highlighted with Source Code Highlighter

            On line 1 you can see the initialization of the proxy. This doesn’t mean the connection is established, it will happen on the first call. On line 2 you see the service being called and getting the result back.
            Below is our method code Main which will ask for email addresses.

              static void Main( string [] args)

            1. {
            2. while ( true )
            3. {
            4. Console WriteLine( "Enter an email address or press [ENTER] to quit..." );
            5. string emailAddress = Console readLine();
            6. if ( string IsNullOrEmpty(emailAddress))
            7. return ;
            8. EmailValidatorClient svc = new EmailValidatorClient();
            9. bool result = svc.ValidateAddress(emailAddress);
            10. Console WriteLine( "Email address is valid : {0}" , result);
            11. }
            12. }
            13. * This source code was highlighted with Source Code Highlighter

              Creating a proxy through Visual Studio, the easy way.

              Instead of creating a proxy service manually, with svcutil.exe, you can also let Visual Studio create it for you. Just right-click on the project and select "Add Service Reference…" A dialog box will appear where you will need to enter your service address and namespace.
              We are now in the space of names ConsoleClient but it also integrates existing namespaces. So now you can access the EmailValidatorClient via ConsoleClient.EmailValidatorClient And this is one of the reasons why I don’t like using the automatically generated proxy class. Now you have to remember to add the using directive for this namespace. Probably the best solution would be to specify the namespace in the Proxies or something similar, so that the full namespace name makes more sense.

              Client startup

              If the service is still running (if not, restart it), you can right-click on the ConsoleClient project and select Debug and Start new instance That’s it, you’re done.

              What’s next?

              Next I will explain how to manually add endpoints and how to place services in IIS. You can read about it here
              From here you can Download solution for Visual Studio 2010 A solution for Visual Studio 2008 will also be available in the next part.

              You may also like