A WCF Journey – Creating your first web service

Create a basic WCF service

I recently presented a session on WCF to the St. Louis .NET users group and received some good feedback. (It’s always interesting to speak to a group of people with such a wide range of experience.) I thought I’d try to capture some of the details in a series of blog posts that might supplement that talk and provide more detail. I’m starting off slow for beginners, but you’ll be able to skip ahead to certain topics as I get them out there. Even though I’ve been working with WCF for a while now, I’m drafting this as a journey from start to finish, so each topic builds on the previous one. I hope that is helpful although I’m sure it will not satisfy everyone. 😉

Create host application

Open Visual Studio. (I’m using Visual Studio 2010 Ultimate, but I will try to avoid and / or notify you if I use something specific to this version of the IDE.)

From the Visual Studio menu, go to File -> New -> Project. Under Visual C#‘s WCF sub-category, select the WCF Service Application project template. (See WCF Project Templates for more information on why I chose WCF Service Application.)

In the New Project dialog box, enter GearCatalog.Host in the Name field and just GearCatalog for the Solution Name. Click OK.

Press F5 to build the application and enter debug mode. The “Cassini” web development server will host the service and then the WCF Test Client application will open. Double-click either of the exposed operations and click the Invoke button to execute them. I will revisit the WCF Test Client later, but feel free to enter parameters and invoke away!

If the WCF Test Client doesn’t open, you can open it from the following location: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe. From the File menu, choose Add Service… and in the Add Service dialog, enter the URL to the service running in the ASP.NET development server and click OK. It should be something like this http://localhost:[port]/Service1.svc. The initial port number is auto-generated so you will have to get it by hovering over the ASP.NET Development Server icon or the Web tab found in the project properties page.

Since the WCF Test Client is such a handy tool, you can make it easier to get to by adding it to the Tools menu in Visual Studio. Go to Tools -> External Tools… and in the External Tools dialog, click the Add button. In the Title textbox, enter WCF Test Client and in the Command textbox, enter C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe.

You’ve just created a WCF service application ready to be hosted in IIS, but let me run through some of the more useful details. I think it’s best to start with the interface. In Solution
Explorer, double-click the IService1.cs file to open it in a code editor window. The interface is decorated with the ServiceContract attribute which designates the class as a WCF service. Both of the interface’s methods are decorated with the OperationContract attribute. This designates these methods as the means of interacting with the service. Additionally, each of these attributes has optional parameters that can dictate specific behavior of the service or its operations and I’ll come back to those in a future post.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace GearCatalog.Host
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

}

Below the service interface is a class named CompositeType. The class declaration is given the DataContract attribute which says this type is serializable. Each of the properties is marked with the DataMember attribute to tell the serializer these properties will be available in the serialized class as well. If a service operation or type isn’t serializable, it cannot be used to communicate with a consumer of your service.

[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

Open the Service1.svc.cs file. This class simply implements the IService interface. This is where you’ll put the actual functionality of your service operations.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace GearCatalog.Host
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}

Right-click the Service1.svc file and choose View Markup from the context menu. This file defines the service’s host. The Service attribute ties this host to a fully-qualified type name implementing a service. The CodeBehind attribute defines the file wherein the service implementation is defined.

<%@ ServiceHost Language=”C#” Debug=”true” 
Service=”GearCatalog.Host.Service1″ CodeBehind=”Service1.svc.cs” %>

The web.config file in .NET 4 isn’t very big. While a WCF service is truly defined by Address, Binding, and Contract (the ABC’s of WCF), WCF 4 doesn’t require you explicitly define any of these things. You will probably want to, but we’ll come back to that later as well.

As a developer, getting the details of any thrown exceptions is vital. The includeExceptionDetailInFaults attribute of the serviceDebug element (about halfway down) defaults to true and should remain so in development. As the comment states, you should turn this to false before deploying the service to a production environment so you don’t provide consumers with too much info on the inner workings that could be used against you!

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

In the next post, we’ll start customizing this service. We’ll start by creating our model to represent our business objects.

Advertisements

Posted on March 23, 2011, in Visual Studio and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: