Getting Started with WCF Part 8 – REST Services: the Basics and Building Your First REST Service

Previous posts in this series:

… annnnnnd we’re back.

Based on the strengths of REST outlined in my last post in this series, it would be a good tool to add to our WCF service arsenal. Our web-based bagel bakery has been very successful, prompting the opening of new locations. Some of these locations are the traditional “counter service” type of bagel store that people are more accustomed to. Others are a café style with an expanded menu, fancy coffee and Internet access.

Our web page has a list of these locations, but as anyone invested in mobile development  will tell you, you can’t have a successful business these days without having a smartphone application.A feature we would like for our smart phone application is a store locator. For now, we just want to provide a list of stores that the application can consume, but we don’t want this information hard-coded into the application, as it’s possible that any day now a large amount of venture capital will fall into our lap and we’ll want to open more stores

The best solution is to provide a web service that allows the application to access a current list of open stores at any time. To keep this service light weight and ensure that it is open to any smart phone platform we have decided to make this a REST based service. With WCF this is very easy.

Step One: The Service Contract

SOAP and REST based services are very different. The fact is that WCF was built on the idea of building SOAP based services and that is the focus of the classes in the System.ServiceModel assembly. In .NET 3.5 Microsoft added REST functionality to WCF in the form of the System.ServiceModel.Web assembly. This new assembly added some pieces that we will need to create our REST service.

Consider this service contract:

image

By now you should be able to easily determine that any service that implements this IStoreLocatorService contract must expose an action method called GetStores that returns a list of some Store objects. As is this is a standard WCF service an action that responds to an HTTP POST and returns a list of Stores in a SOAP message is created.

In order to tell WCF that we want this to be a REST based service we need to add an additional attribute to our operation:

image

The inclusion of the WebGet attribute in our service contract tells WCF that, depending on some configuration details, a service that implements this contract must be able to respond to an HTTP call with the GET verb (hence the “Get” in “WebGet”). For now don’t worry about the other verbs, we’ll get to them later.

There are several arguments we can pass into the WebGet attribute to change how this method behaves, but for now we’re just using the UriTemplate option. The UriTemplate tells WCF what the URI that access this service should look like. In this case we’re telling WCF that if the base address of our service is “www.WebBagels.com” and the client uses that as it’s URI it will access this method via a pattern match. If we were to make a small change to the UriTemplate for our service….

image

… our service will now be called if the client attempts to access the www.WebBagles.com/Stores URI.

That’s pretty nifty, but what happens if a user is specifically looking for one of our “café” stores? Users are going to want a way to filter this list. And besides, one of the big benefits of REST is supposed to be the cacheable, easy to understand hierarchical way of representing data, right?

WCF makes if very easy, again using a simple pattern matching algorithm to enable us to have dynamic arguments embedded in our URI. We’ll add a new method to our service contract that enables users to search for specific store types:

image

Our new method still responds to an HTTP GET, but we’ve added a second UriTemplate with a different patters to match. In our GetStoresByStoreType method we are now looking for a URI that includes the store type of the stores we are searching for.

The first thing I had to do was create a new method called GetStoresByStoreType that took a string parameter of storeType. It’s important to note that when you are using parameterized URI’s like we are here, the arguments for your method MUST all be strings; no other types are allowed. The reason is that the URI itself is a string and all constituent parts of it must be treated as strings as well. You can cast them all you want once they are passed into your method, but the method prototype must define these as strings. Aside from that you need to make sure that the token you are using in the UriTemplate (in this case {storeType}) matches the name of the parameter you want to map it to, including capitalization. Order is unimportant and if the URI has a token that does not map to a parameter on your method WCF will just ignore it. On the other hand if you have a parameter for your method that does not map to a token in your UriTemplate .NET will throw an error since it is missing parameters for the method call.

Based on this service contract we will have two URI’s that our service is able to respond to:

  • www.WebBagles.com/Stores – Results in a call to the GetStores method, returns a list of all stores.
  • www.WebBagles.com/Stores/{storeType} – Results in a call to the GetStoresByStoreType method, returns a filtered list of stores.

One last thing to notice here: The names of the .NET methods in our service contract has no bearing on or relationship to our URI’s. We could call those two methods anything we want (provided it’s a name .NET deems legal) and as long as our URI templates don’t change our clients would never know. This means that once we expose an API we can refactor internally all we want so long as we don’t change (mess up) those UriTemplates and break the API.

By default WCF returns POX (Plain Ol’ XML) for it’s REST methods. Most users, myself included, would rather consume this information as JSON (JavaScript Object Notation) in many, if not most situations. For one thing as a web developer I find myself taking more and more advantage of AJAX calls from the browser. In these cases I would much rather consume the native JSON object than futz with the JavaScript XML parser.

Having said that there are a lot of applications that consume REST services from C# or VB.NET and XML seems to be the more popular choice in those languages. As a result I like to write my REST services in a way that enables the users to determine how they get the data back (POX or JSON). For this service I’ll do that by adding a two new operation contracts to my IStoreLocatorService service contract; one to return all stores as a list of JSON objects and another to return list of stores filtered by store type as JSON objects:

image

First let’s compare the contract for GetStores to the one for GetStoresInJson. The UriTemplate for GetStoresInJson is the same as the UriTemplate for the GetStores contract, except that I’ve added “/js” to the end. When WCF sees a request for a URI that looks like “~/Stores/js” it knows to route that action to the GetStoresInJson method since the incoming URI matches the pattern defined in the WebGet attribute of the GetStoresInJson method. Similarly, the GetStoresByStoreTypeInJson method is able to respond to requests that have URI’s with the pattern of “~/Stores/{storeType}/js” as opposed to “~/Stores/{storeType}” mapping those actions to the GetStoresByStoreType method which returns POX.

The other change to note is that unlike the previous methods we worked with (GetStores and GetStoresByStoreType) we’ve added a new parameter to the WebGet attribute; ResponseFormat. As you can probably infer from it’s name, it’s used to tell WCF how you want the response from the service formatted. As I mentioned before the default is POX, but by specifying a value for the ResponseFormat (in this case WebMessageFormat.Json) we can change how the data is returned. As you may guess there is a corollary parameter, RequestFormat that specifies how the service should expect incoming request data to be formatted, but I’ll get into that in a future post.

I’ve talked quite a bit about the service contact side of building these REST based services, but I haven’t touched on the implementation. That’s because the vast majority of the work to make these WCF services RESTful is done in the service contract. Here are the implementations for GetStores and GetStoresInJson:

image

As you can see, there isn’t really much to these implementations. The methods just return a list of Store objects. The GetStoresByStoreType and GetStoresByStoreTypeInJson just use a LINQ query to get the specific stores that match the store type out of the ListOfStores list. WCF, via the definition in the service contract will serialize this as either POX or JSON when it’s returned.

Step Two: The Data Contract

So how about that Store object? Like all complex structures that are sent received via WCF services, the easiest way to deal with it is to create a Data Contract. The Data Contract for our REST based service is very similar to the data contracts we’ve created for the other services in this series:

image

Like the previous data contracts this one has a class level attribute of DataContract and each property that I want to expose via the service is decorated with a DataMember attribute. In this case I have added a Namespace parameter to the DataContract attribute at the class level. I’ll explain why and more about namespaces in a future post.

Step Three: Updating the Host

The previous services in this series were all SOAP services. As a result we were able to use the ServiceHost class to host those services. Since REST services live by a different set of rules than SOAP services, particularly the use of parameterized URI’s REST services needs a host with slightly different capabilities than the one used for SOAP services.

WCF provides the WebServiceHost class for hosting REST based web services. As you can see from this code snippet, it’s just as easy to use as the ServiceHost class:

image

Now that we have our hosting situation sorted out, it’s time to look as our configuration.

Step: Four: Updating the configuration

Since we’ve added a new service to our solutions, we need to add a new service section to our configuration. We already did this for our SOAP service and our REST service is actually pretty easy by comparison:

image

The address attribute identifies the base address for our service. The URI Template from our service contract is appended to this base URI in the configuration. This means that the URI we will use to get to the list of stores is http://localhost:8733/Stores. To search by store type the URI would be http://localhost:8733/Stores/<store type being searched>.

For binding we’ll need to use the webHttpBinding. This is a REST specific binding and will tell WCF to build a channel stack that includes the serializers for POS and JSON messages. Contract behaves exactly the same way it has for our SOAP services.

This configuration works for our self-hosted service. For hosting REST based WCF services in IIS you will need to make a couple more small changes. I’ll cover those configuration changes in a few posts when I cover deployment.

Step Five: Testing and Profit

To test our SOAP services we either had to use the WCF test client of write an application that created a proxy object that would serialize and send SOAP messages as POST actions and deserialzie the SOAP messages that were returned. Since REST based services are HTTP based and don’t reply with complex SOAP messages we can easily test our service in any web browser. To test our service I’ll start by launching the hosting application:

image

I’ll fire up Chrome (I prefer Chrome over IE for this, you’ll see why in a minute) and put the URI for our Stores REST service into the address bar (this is the base address from the configuration of the endpoint plus the URI template from the service contract) and hit Enter. Since our service just returns POX, we have not problem being able to view the message in Chrome (or any browser for that matter) without our faces melting:

image

To filter this down by store type we can add the store type to the URI as proscribed by the URI template in the operation contract for the GetStoresByStoreType method of our Service Contract:

image

WCF mapped the URI with the store type data to the correct method that filtered the store data by store type. What happens if we supply a store type that has no stores:

image

We simply got an empty list back. This is the preferred way REST services should handle this type of situation; if there is no data that satisfies the query then return an empty result.

Say we want JSON. As we provided additional Operation Contracts that specified JSON as the response format when “/js” was added to our URI we simply need to add that to our current URI to change the format of the response data:

image

Line-breaks aside, JSON is a pretty easy format to understand and digest. Incidentally, JSON services are why I prefer to use Chrome for this kind of testing as opposed to Internet Explorer. For whatever reason IE does not want to render JSON and instead will make you save it to a file which you then will have to open in a text editor:

image

The end result is the same, but I appreciate that Chrome doesn’t make me go through this extra step to see my data.

You may have noticed that we didn’t work much with query strings here. That will be covered in a future post.

In the next post we’ll see how to send data to our service with the POST verb and lean how to test our services with one of my favorite all time developer tools.

Code on!

You Never Forget Your First….

For the one or two people out there who probably haven’t heard yet, I’ve spend the past year writing a book. Well, not completely by myself; I had a lot of help from Jeff McWherter and Mike Eaton. I’m happy to say that after almost a year of hard work, late nights missed social engagements and infinite patience from Gayle, the book is officially released!

cover

For those of you who have received your copy already via Amazon, I hope you are enjoying it. The Kindle version is available today. For those of you who didn’t pre-order, the book should (I hope) now be available at your local book store. Please take a look and visit the Facebook page to tell me what you think.

I’m also happy to report that I’ll be writing another book. This one will still be for Wiley publishing, but will probably not be on the Wrox imprint. More details to follow.

Working with WCF returns from hiatus next week!

DotNetKicks Image

Slides and Code from my Dogfood presentation on WCF

I'd like to again thank everybody who came to my presentation on WCF at the Dogfood conference in Columbus yesterday. The slide deck and the code can be found here.

I'd also like to thank Danilo Casino and all the other organizers for once again putting on a great event. I enjoy almost all the conference, code camps and Day of .NET events I attend every year, but the Dogfood conference is one of the few I truly look forward to every year. If you could make it this year,

DotNetKicks Image

Hockey Jobu

I have no idea who is running this, or who came up with the idea (no, it wasn’t me), but they should be involved in the Space Program. Pure genius!

Jobu, I have a feeling the Nobel committee will be calling soon.

http://www.hockeyjobu.com/

DevLink 2010 Slides and Demo

I had a great time speaking, learning and just generally hanging out at DevLink as always. It’s quickly becoming one of my most eagerly anticipated events of the year.  I was honored to be allowed to speak at this years event, and as promised here are all my slide decks and demos.

See you next year!

DotNetKicks Image

Working with WCF Part Seven - What's the deal with REST?

Previous posts in this series:

We’re gonna step out of the whole Web Bagels/WCF demo thing on this post so I can give you a brief primer on Representational State Transfer (REST).

The good news is that if you are reading this blog then you have used REST. The reason is that REST is the architectural basis for the Internet. When you opened your web browser of choice and typed www.jamescbender.com into the address bar and hit ENTER, the browser issued a request to the access resource located at www.jamescbender.com (whatever that may be) using the REST GET verb. In fact, if you’ve ever navigated to any website you’ve seen REST in action. That’s the basis of REST; clients make requests to servers using a Uniform Resource Identifier (URI) which, depending on which REST verb was used in the request, returns, created, alters or deletes the resource at the location specified by the URI. It’s that simple.

URI’s and You

There are two components of a REST request; the URI and the verb.

The URI is probably the easiest for most people to get their heads around. It’s the location of the resource on the Internet that we want to get/change/delete. We’ve all used websites before, and we generally access them by a URL. You can think of a REST services URI as it’s location. But there is a bit more to it than that. Consider the following list of URI:

www.GloboCorp.com/Departments

www.GloboCorp.com/Departments/Sales

www.GloboCorp.com/Departments/Sales/Employees/JohnDoe

www.GloboCopr.com/Departments/Sales/Employees/search?name=JohnDoe

The first thing to notice about all of these is that they are human readable. You may know nothing about Globo Corp., but you know that it has departments, one of those departments is Sales and it has an employee named John Doe. A big part of our ability to understand that is the hierarchy that the information is presented in. When creating URI’s for REST services it’s important to think about how you want your information to be accessed and conceptualized. In this case it makes sense to have the list of Departments as one of the “top level” branches in the hierarchy. For another company it may make sense to have Employees be the top level. It all depends on what your data is like and how you want it presented.

Another thing to note is the “Universal” aspect of the URI. These are simply locations on the Internet. There is no special decoder ring needed to access these; any application that can use HTTP, and can handle the content type of the response (text, a picture, a sound file, etc.), can use the resources located at these addresses. You could embed these URI’s in a document and anyone reading that document, assuming they had some sort of HTTP capable web browser and access to the Internet could get the resource that resides at that location.

Finally, since these are simply URI’s, and there is nothing special about them, they can be cached like any other URI. This is a big advantage over the SOAP based services we’ve been using up till now. Since there’s a certain amount of “magic” that happens when a SOAP service is invoked caching is difficult, usually involving some sort of customization on the host. Since REST is URI based most web servers provide the ability to cache right out of the box.

VERB – That’s what’s happening.

Once we have our resource location we need to specify what we want to do with the resource. These is where the HTTP Request Method, a.k.a. the  REST verb come into play. There are a variety of REST verbs available. The four are the most commonly used and you will use in your everyday like are the following:

  • Get – returns the resource at the URI’s location
  • Post – creates a resource at the URI’s location
  • Put – alters the resource at the URI’s location
  • Delete – delete the resource at the URI’s location

In addition to these four, you may start to encounter the HEAD verb as more service providers have begun implementing it. HEAD returns metadata about the resource at the location that you would get if you sent a Get verb.

The benefit of the verb paradigm in REST is that we have a standardized interface. Unlike SOAP based services we aren’t creating our own verbs like GetEmployee or CreateSale. Being able to understand the information hierarchy behind our URI’s and having a standard list of methods (verbs) we can use on those resources makes developing clients that use REST services much easier and more intuitive.

POX and JSON

So now we know how to request resources from REST based web services. But what are we getting back. In the Web Bagels example we’ve been using SOAP based web services, which in fact return SOAP messages. REST doesn’t use SOAP. So what are our options?

POX

One option for our response is Plain Ol’ XML (POX). Like SOAP, our data comes back as an XML stream, That’s really where the similarity ends. Unlike SOAP, POX is very small, terse and easy to read.  For example, consider this SOAP message:

image

Now check out the exact same message in it’s POX version:

image

Wow! Three things were accomplished here. First, and most strikingly it’s a MUCH smaller message. As a result it’s become much more human-friendly. Additionally we’ve trimmed a lot of the complexity that comes with SOAP out of the process. We do need to keep in mind that the simplicity comes at a cost; when we removed the SOAPyness from our message we lost some security as well as some other WS-* abilities like addressing, routing, reliability and anything involving workflow. More on that in a bit. But what we do have is a simple XML document that can be easily understood, parsed and acted upon.

JSON

I’ve you’ve been doing “Web 2.0” stuff you’ve no doubt heard of Asynchronous JavaScript and XML, better known as AJAX. AJAX is all the rage with web developers who want to provide a good user experience on the web by making several “smaller” calls to a back-end web service and using that result to change part of the page instead of doing a full page refresh. These keeps the user from having to sit and wait for the whole page to be re-served and re-rendered when only a small part of the page is changing. Most of these calls are coming from client side JavaScript and in the “dark ages” you would get back an XML document that you would have to parse before you can use.

JavaScript Object Notation or JSON was defined in 2001, but didn’t really gain steam till 2005 when large web properties like Yahoo, Google and Microsoft embraced it. The idea was that since we’re already using JavaScript to make these calls, and JavaScript is a dynamic scripting language, why not just return the text that corresponds to a JavaScript object? This made life a lot easier for the client developers, and once libraries to quickly format messages for JSON it made life just as easy for service developers too. An example of the JSON equivalent of the previous message would look something like this:

image

As you can see JSON shares a lot of characteristics of POX; both are simple, compact and human readable. It’s also instantly consumable by JavaScript so there’s no need to parse it, pull it apart and put it in an object; it’s already in one. Once you get this back from your service you can use it like any other object in your client side JavaScript.

What of SOAP?

The resurgence of REST does not mean the death of SOAP. Yes, SOAP is complex. But that complexity brings power. For the Enterprise, SOAP is not going away. There are still too many things that business cares about that are easier to do in SOAP than with REST-based services. Things like transactions, reliable messaging, workflows and orchestrations, message routing and custom security. SOAP excels at these and that is why you need to know (and care) about it.

What is changing is how you architect and plan your service infrastructure. Specifically where you use SOAP/REST based services. Personally, I’ll start from the standpoint of making something a REST service until a requirement arises that can be more quickly, easily and reliably done with SOAP. Then I’ll switch to SOAP. An emerging pattern many have seen that follows this line of thinking is that we are starting to see REST services deployed along the edges of a service architecture, in places where outside client need to have easy and interoperable access to our data. While SOAP services are still very much relied on in the center of the service architecture, where things like sessions, long running workflows, more advanced security and services busses are needed. Of course the standard Architect mantra of “It depends” comes into play.

Next time we’ll use WCF to add some REST-based services to our Web Bagels application.

DotNetKicks Image

Working with WCF: Part Six – Fault Contracts

Previous posts in this series:

There are four “major” contract types in WCF and at this point we’ve covered three of them; the Service Contract, Data Contract and Message Contract. The last one to cover is the Fault Contract. I began writing a post on how to work with Fault Contracts, and I immediately got a distinct feeling of déjà vu. It was as if I had somehow written this post before. Turns out there was a good reason for this, I had written it before. Twice in fact. Being a developer who values the concept of keeping your code DRY (Don’t Repeat Yourself) I’ve decided to re-publish these original posts (with a few tweaks) here. Obviously this will not be keeping with our “Bagel Factory” analogy, so think of it as having a substitute teacher.

Before That Though…

What is and why do we need a Fault Contract? Well, if the days of ASMX based web services there was no built-in way to report exceptions back to the client. For the most part, the only way a client found out something was wrong was that the call to the web service timed out. There was no other explanation. This was a tremendous source of frustration for client developers, and also prompted many a developer and architect to pull their hair out over the prospect of reporting some sort of exception information back to the client. A lot of developers, myself included, broke out the duct tape, chewing gum and bailing wire and attempted to build some sort of notification mechanism that would not leave the clients hanging (no pun intended). These solutions ranged from complicated to outrageously complicated. All met with limited success.

WCF introduced the concept of a Fault Contract. As you’ll see below, a Fault Contract is simply a Data Contract that contains some information (as much or as little as you decide) about what happened that caused the call to fail. When you specify a Fault Contract for an operation what you’re doing is telling WCF that in addition to whatever your return type for that action is, it may also send back a FaultException, which is really just a wrapper for the instance of the Fault Contract you specified. This allows you to wrap your service calls in a Try/Catch block and catch meaningful exceptions.

Your Substitute Teachers (Be Nice!)

First off, Scott Hanselman wrote a terrific blog post on exceptions. It’s a great place to start and if you haven’t read it you should.

Using Fault Contracts is very easy. In fact, you can do it in four steps...

Step 1: Admit your faults

The first thing we need to do is determine what kind of information we want to return back to the client and create a Data Contract that contains that information. You may have several kinds of fault classes, and you should so that you can return specific types of information for specific faults. Kinda like why there isn't just one Exception class in .NET. Although these are data contracts, you should not use them for anything other than sending faults back to the client. Here's a sample fault class:

[DataContract]
    public class MyFault
    {
        private string _message = string.Empty;
 
        public MyFault(string message)
        {
            _message = message;
        }
 
        [DataMember]
        public string Message
        {
            get
            {
                return _message;
            }
            set
            {
                _message = value;
            }
        }
    }

Like any .NET class, you can create a fault class the inherits from another .NET class, BUT that class also needs to be a data contract and be a known type.

Step 2: Find where you may go wrong

Next, we need to let WCF know where these faults might be coming from. This is done at the operation in the service contract. You simply use a FaultContract attribute which lets WCF know what kind of possible fault class to expect:

[ServiceContract]
public interface IFaultyService
{
    [OperationContract]
    [FaultContract(typeof(MyFault))]
    void ThrowMeAnError();
}

You can specify as many faults for the operation as you like, simply add more FaultContract attributes:

[ServiceContract]
public interface IFaultyService
{
    [OperationContract]
    [FaultContract(typeof(MyFault))]
    [FaultContract(typeof(MyOtherFault))]
    [FaultContract(typeof(YetAnotherFault))]
    void ThrowMeAnError();
}

Step 3: The throw...

Throwing faults from a service is a little different than throwing them from C# or VB code. We need to enclose our fault class in a FaultException<T>, which represents a SOAP exception. This is just as easy as the other steps:

throw new FaultException<MyFault>(new MyFault("This is a fault"), "Demonstration");

The second argument, in this case "Demonstration" is the reason for the fault. And yes, "reason" is the attribute name of the fault too. This can either be a string or a FaultReason object which allows you to send more detailed information about the exception.

Step 4: ... and the catch

If you've done everything correctly, when you generate a reference to your service, in addition to the normal proxy information, you should have a class representing the data contract you created for your fault class. Catching this exception on the client side is similar to throwing it on the server side. It will come wrapped in a FaultException<T> and you will need to specify that to catch it correctly:

.
.
.
catch(FaultException<MyFault> itsMyFault)
{
    Console.WriteLine("MyFault was caught");
    Console.WriteLine(string.Format(@"Message: {0}", itsMyFault.Detail.Message));
    Console.WriteLine(string.Format(@"Reason: {0}", itsMyFault.Reason));
}
.
.
.

As you can see, getting the reason is pretty straight forward. Our message, and any other field me might have added, will be accessible as a member of the Detail child object of our fault.

That's it. See, nothing to it.

Actually, this rabbit hole does go a little deeper…

When you use WCF on the client side, and your service back-end is not necessarily WCF, then you may not necessarily get a WCF-style Fault Contract. Even WCF, being a close cousin of ASP.NET, can send non-service friendly messages down the pipe (sort of it’s version of the “yellow screen of death”). Lets look a little more closely at how exceptions get received by a WCF client and how the WCF channel reacts to exceptions. We’ll start with what happens if you just throw a normal .NET exception. For this example we’ll be looking at a mock up of a service to return prices for stocks based on a ticker symbol.

The service contact:

   1:      [ServiceContract]
   2:      public interface IMyWcfService
   3:      {
   4:          [OperationContract]
   5:          decimal GetStockPrice(string symbol);
   6:      }
 

And the implementation:

   1:      public class MyWcfService : IMyWcfService
   2:      {
   3:          public decimal GetStockPrice(string symbol)
   4:          {
   5:              switch (symbol)
   6:              {
   7:                  case "MSFT":
   8:                      return (decimal) 1.41;
   9:                  case "IBM":
  10:                      return (decimal).89;
  11:                  case "JAVA":
  12:                      return (decimal).10;
  13:                  default:
  14:                      throw new ArgumentOutOfRangeException("symbol", "bad symbol");                   
  15:              }
  16:          }
  17:      }

Since this is a contrived demo, we only handle three symbols and return a static value. This does however provide us with an opportunity to see how .NET exceptions work in WCF. If we receive a symbol that is not in our list, we are throwing an ArgumentOtOfRangeException. If we were using this as just a .NET object we wouldn’t have a problem; either our code would catch the exception and do something with it, or it would bubble up to the user.

Our client is a winform application. The important part is the call to our service (via a proxy of course):

   1:  public partial class Form1 : Form
   2:  {
   3:      private readonly MyWcfServiceClient _proxy;
   4:   
   5:      public Form1()
   6:      {
   7:          InitializeComponent();
   8:          btnCallService.Click += CallService;
   9:          _proxy = new MyWcfServiceClient();
  10:      }
  11:   
  12:      public void CallService(object sender, EventArgs e)
  13:      {
  14:          lblResult.Text = _proxy.GetStockPrice(txtSymbol.Text).ToString();            
  15:      }
  16:  }

So all we’re doing is grabbing a value (the ticker symbol) from a text box and passing it as an argument to the service. The result is used to set the value of a label control. When we run this and feed one of the three symbols that our service uses, the expected happens: a value is returned and set to the text of the label. When we provide an unsupported symbol, we get an error:

image

The exception text should look familiar to anyone who has worked with ASP.NET…

System.ServiceModel.FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

Like ASP.NET, WCF will not return detailed exception information to clients as a security measure. Also like ASP.NET, we have the ability to change the configuration to return more detailed exception information. One line nine below, we have set the includeExceptionDetailInFaults value to “True”:

   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <configuration>
   3:    <system.serviceModel>
   4:  ...
   5:      <behaviors>
   6:        <serviceBehaviors>
   7:          <behavior name="Service1Behavior">
   8:            <serviceMetadata httpGetEnabled="True"/>
   9:            <serviceDebug includeExceptionDetailInFaults="True" />         
  10:          </behavior>
  11:        </serviceBehaviors>
  12:      </behaviors>
  13:    </system.serviceModel>
  14:  </configuration>

This results in the details of the error message being passed back to us:

image

This can be OK for development, but is not a good idea for production.

Let’s make a few changes to our client application:

   1:  public void CallService(object sender, EventArgs e)
   2:  {
   3:      try
   4:      {
   5:          lblResult.Text = _proxy.GetStockPrice(txtSymbol.Text).ToString();            
   6:      }
   7:      catch
   8:      {
   9:          MessageBox.Show("Service call failed");
  10:      }            
  11:  }

By catching the exception we can let the user know that something happened and handle it gracefully. Running the application and use the symbol “ORCL” causes the exception, which is handled:

image

So, we can just re-submit a supported symbol right…?

image

Uh-oh.

Turns out that when a WCF service throws a normal .NET exception, it faults the channel. Any subsequent calls to the channel results in a CommunicationObjectFaultedExcption being thrown immediately. The channel cannot be salvaged; your only option is to throw it out and recreate it. The proxy implements an interface called ICommunicatioObject that has a Faulted event that we can subscribe to.A few more changes to our client…:

   1:  private MyWcfServiceClient _proxy;
   2:   
   3:  public Form1()
   4:  {
   5:      InitializeComponent();
   6:      btnCallService.Click += CallService;
   7:      _proxy = new MyWcfServiceClient();
   8:      ((ICommunicationObject)_proxy).Faulted += RecreateProxy;
   9:  }
  10:   
  11:  void RecreateProxy(object sender, EventArgs e)
  12:  {
  13:      _proxy = new MyWcfServiceClient();
  14:  }

… and now our client is able to recreate the proxy if a communication fault occurs.

This way of dealing with exceptions in WCF works well if you are a client of a service that you may not control or have the metadata needed to create a fault contract for. Otherwise, using the FaultException class and/or WCF fault contracts are a better way to go. I’ll be covering them more in detail in the next couple posts.

Code on!

DotNetKicks Image

Central Ohio Give Camp is around the corner

givecamp And if you’re involved in software development in anyway, we need you!

Give Camp is three day event where software development professionals can get together and help local non-profits with IT needs. These could be anything from building new websites to updating older CMS systems to proving a “face lift” to an existing application. Over the course of the three day event we split into teams and help these charities with their IT needs. You’re welcome to stay on-site the whole weekend, 24/7 and work if you like (we have overnight access to the facility) or come and go if needed. Give Camp is a great, fun experience that is unlike any development community event you’ve attended. Think of an all-nighter from back in college, but more fun. Food will be provided, and we’ll have a few cool prizes for some lucky campers.

This is NOT a .NET only event. We have plenty of need for Java and Ruby developers, DBAs, designers, testers; you name it. If you are involved in software development, you can contribute.

We are also looking for sponsors. If you’re company would like to help us help the community, please let us know.

The Give Camp will be July 9-11 at the ICC office near I-270 and Cleveland Ave. Big thanks to ICC for providing the space!

You can find more information at http://www.columbusgivecamp.org/GiveCamp

See you there!

DotNetKicks Image

Codestock is Next Week!

Nerdette_skull-2010 And if you haven’t registered yet, don’t you think you should? It’s easy, just go to http://codestock.org and click on the Registration link.

You don’t want to miss Codestock this year; there are plenty of great speakers, a lot of terrific sessions to attend and a lot of fun to be had. This will be my third Codestock and I can’t wait!

See you there!

DotNetKicks Image

Working with WCF: Part Five - Message Contracts

Previous posts in this series:

Like all Internet based businesses, our Web Bagels company has become wildly successful. This, of course, has resulted in Venture Capitalists throwing obscene amounts of cash at us. There is only one thing to do: expand. In addition to our retail delivery business we now want to start supplying local grocery stores, coffee shops and restaurants with our bagels. To accommodate this, we also have expanded our physical resources and now have several smaller commercial bakeries scattered across the region. Each satellite kitchen is responsible for one or more commercial accounts (baking and billing). We want this to be somewhat transparent to our customers; we don’t want them to have to specify (or even have to know) the specific bakery that will be producing their bagels. Another design consideration is that with each order the customer will be sending super-secret payment information to cover the cost of the bagels, which requires that the message be encrypted. We also have the issue that our clients are running on a variety of platforms, with different messaging requirements and conventions. So, while we want all the commercial clients to send their orders to the same service, the service needs to be able to route the message to the appropriate bakery without being able or needing to read the message.

Sounds difficult? Not really.

Getting SOAPy

SOAP messages, which are the types of messages we have been working with all this time, use a message layout paradigm similar to an envelope. When you send a letter through the snail-mail (do people still do this?) you would write on the envelope all the information that the Post Office needed to deliver that message to the intended recipient. The mail carrier didn’t need to open your envelope and read the letter to figure out where it needed to go.

A SOAP message is an XML document that has two “main” sections: the header and the body. The header is equivalent to the envelope you put your letter in and the body is the letter. So what does that mean to our service implementation? Consider the following topology:

image

This diagram represents the basic topology of our service infrastructure. Our clients will send their requests to the public service. The message then has to be routed, without actually reading the message, to either Bakery A or Bakery B. The Public Service is what’s referred to an an “intermediary service.” It’s job is to accept messages, perhaps perform some processing based on the message, and to send it along to another service, where the ultimate goal is for the message to reach it’s final destination. If, as is our case, the intermediary service simply needs to route the message to the next service then it doesn’t need to look at the body; the header should have all the information that’s needed for the service to figure out where the message needs to go. You may know this concept as WS-Addressing and is a very important standard in SOA implementations.

Back to Bagels

For our contrived example need to create a new data contract for corporate orders. Add a new class called CorporateOrder to the WebBagles project and add the fields as shown here:

image

This is pretty much the same order information that our WebBagles service takes in for orders now. To accommodate the commercial accounts we’ve added the SuperSecretPaymentData field as well as the DeliveryLocation field which is a  customer location code number for the store we are to deliver the bagels to.

Note: We will not be encrypting the message in this demonstration. Security will be covered in a future post. For now, we will pretend that the message is encrypted.

It’s time to introduce the Data Contracts cousin; the Message Contract. Like the Data Contract, the Message Contract tells .NET how to format messages to be sent with WCF. Whereas the Data Contract defined how we want the messages body to look, the Message Contract allows us to control what fields are written to the body of the message and which are written to the header. Will use the same declarative model to let WCF know that CorporateOrder is a Message Contract. For now, we’ll just write everything to the body by decorating the fields with the MessageBodyMember attribute:

image

Remember, pretty much everything in WCF works on the opt-in model. This means that we must decorate ALL the fields on the class that we want to be included in the message. If we don’t decorate a field, it gets ignored.

One wrinkle we encounter when using Message Contracts as parameters for our service methods is that we must also return a Message Contract or void; no other primitive types and no Data Contracts. Let’s create a return message contract. Right click the WebBagles project and add a new class called CorporateResponse. Add the following code:

image

Just because we can’t directly return Data Contracts from our service method doesn’t mean we can’t return Data Contracts from our service method at all. We just need to wrap them in a Message Contract. We already have all the response information defined in BagelOrderResponse. It wouldn’t make sense to redefine it. It’s easier to simply define our message as returning an instance of BagelOrderResponse in the message body.

You can wrap as many Data Contracts in a Message Contract you want, just remember that you CAN NOT put a message contract in a Data Contract or in another Message Contract. The Message Contract MUST be at the top of the abstraction layers. And remember; there can only be one Message Contract in your message stack.

Now we need to add a new method to our service to consume this message.  Open the IBagelOrderService interface and add a method called PlaceCorporateOrder so that it appears as follows:

image

Now, a question you may be asking yourself is “Hey, why did he use a different method name? Why not just overload PlaceOrder?” The reason is that services don’t use method names like we think of them in .NET. They use something called “Actions” which WCF abstracts away from us, so that 99% of the time we don’t need to worry about them. This is done in the interest of interoperability, and in this paradigm there is really no good, reliable way to differentiate web service methods (actions) with the same name based on the signature. Therefore we need to name every action on a web service with a unique name. There is a way we can use overridden method names in our .NET contracts while giving them unique action names, and it will be covered in a future post. For now we’ll just change the name of the method in our contract.

The next step is to implement the new method in our service class. Add the following method to the BagelOrderService class:

image

This is just a stub implementation that we’ll use for now, we’ll make changes in a few minutes that show how we deal with message contracts, but you can already see that we are able to access the fields on order (an instance of our Message Contract CorporateOrder) the same way we use Data Contracts. Make sure that the WebBagels project is default running project (right click the WebBagles project, select “Set As Startup Project”) and hit F5 and… you’ll get a build error:

image 

 

 

 

 

 

Remember; we added a method to the BagelOrderService. Our custom BagelOrderServiceClient uses the same .NET code to define it’s methods unlike the other two proxies (right click, add service reference and SVCUTIL) which use the WSDL emitted from the service. This is easily fixed though, just implement the method in the proxy:

image

It’s as easy as that. Our Client doesn’t need to know that CorporateOrder is a Message Contract; WCF insulates us from that implementation detail. Now that that’s taken care of, we can hit F5 and take a look at how our Message Contract is being used. You’ll notice that our new method is listed in the WCF test client:

image

Will invoke this method with some test data:

image

 

 

 

 

 

 

 

 

And invoke the method. It returns as expected and if we take a look at the XML of the outgoing method we don’t see anything too different. The data is all in the message body, albeit in a slightly different XML wrapper as before:

image

The point of this demo was to get some of that data, specifically the delivery location, into the header. Let’s go back to our CorporateOrder class and make a that change. Right now Delivery Location is set as a Message Body Member. That attribute, as you can see, tells WCF to write our data to the messages body. Let’s change that attribute to Message Header:

image

That’s all we had to do. WCF now knows that when this message is serialized DeliveryLocation, and any other field decorated with the MessageHeader attribute should be written to the SOAP header, not the body.

Let’s change our service to look at that value and route our order accordingly. In this case we have two bakeries. If the delivery location code is even, it goes to bakery A, otherwise it goes to bakery B. Again notice that I’m simply accessing a field on the order object. I don’t have to know that it’s part of the header or do anything special to deal with that fact:

image

 

Each RouteToBakery method simply calls a method with the bagel processing logic we’ve been using, but provides a hard-coded confirmation number so we can see that the message was routed correctly:

image

When we run the application the input for our method doesn’t look any different; the same fields are listed and there’s no indication what goes in the header and what goes in the body:

image

If we supply this method with some data and call it though, we can see that our Delivery Location is now being delivered as part of the head and is no longer part of the message body:

image

 

 

 

 

When to Message

As you’ve seen in previous installments of this series Message Contracts are not required to create and consume WCF services. Their job is to provide a simple, easy to use way to customize your SOAP messages both for security concerns and to conform to various interoperability standards. You may also find them handy if you have an existing corporate SOA standard that you must work in. Message Contracts are powerful tools (we’ve only scratched the surface here) and like all powerful tools should be treated with respect and used when needed. Unless you have a need to define what goes in a message body and what goes in a header, you’re OK sticking with Data Contracts.

Like Service and Data Contracts, there are many more customization points in Message Contracts than we’ve explored here. They will be covered in a future post. For now, stick with the basics and you’ll be able to control how your data is sent across the wire.

DotNetKicks Image