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

Review: Azure in Action

A few weeks ago I was able to get an advance copy of the book Azure in Action by Brian Prince and Chris Hay. AzureInAction

The book takes a standard, logical path through the subject, explaining cloud computing in general, understanding and working in Azure’s implementation of the cloud paradigm, how Web Roles work and sections dedicated to each type of Azure storage (Table, Blob and Queue). The flow is logical, and if you follow along you’ll be building Azure based applications in no time. The books also works well as an ad hoc reference if you already have some knowledge of how Azure works. The book covers a wealth of material, from standing up your first Web Role to an in-depth discussions of deployment, including an explanation of how patches and upgrades should be applied to your Azure application.

Azure as a platform is going to be a bit of moving target for some time. It’s always a challenge to write books/blogs/documentation for these types of technologies. As a result, the book tends to stay kinda broad on some elements that are likely to change, and avoids some that are in a heavy state of flux altogether. There are sections on SQL Azure and Windows Azure Platform, but they are not deep dives; frankly both of those parts of Azure are big enough to warrant their own books.

So in summary, if you’re new to Azure and want to quickly learn how to properly build, deploy and manage applications for the cloud, this book is for you!

DotNetKicks Image

Central Ohio Day of .NET is a week away!

The Central Ohio Day of .NET is a joint event hosted by the Central Ohio .NET Developers Group (CONDG), the Cincinnati .NET Users Group (CINNUG), the Dayton .NET Developers Group and the Cincinnati SQL Developers Group. It is being held at the Roberts Center in Wilmington OH on June 5th

If you are a .NET developer (or anyone who wants to learn more about .NET for that matter) in Columbus, Cincinnati, Dayton or the surrounding areas I HIGHLY recommend you attend this event. There are a lot of great speakers and topics, and the opportunity to see this kind of content in almost your own backyard only comes around once a year. Don’t miss it, register today!

DotNetKicks Image

Richmond Code Camp 2010.1 is in the books! Plus, the part my WCF talk I wasn’t able to give.

I had a great time at last years Richmond Code Camp (RichCC) and was thrilled and honored that I was picked to speak yet again! I was especially happy to help out by agreeing to do a second talk when another speaker had to cancel. As great as last years RichCC was, I think this was better. People seemed more engaged, yet more laid back. I had some great questions in both of my talks and would like to thank everyone who attended.

As promised, the content from my talks:

Getting Going with WCF: The Lost Scenes!

As mentioned above, Justin had a couple speakers who were unable to make it and asked me to sub in for one with my Getting Going With WCF talk. This is a talk I give at a lot of user group meetings, and usually clocks in around 1:30. I kinda had to “rip” through the last several slides to allow the next speaker time to set up. The way I tend to build my slide decks is based around the premise that I will actually be there when the slides are presented, so I didn’t think just putting the slides up here to be downloaded was quite enough. Below are the slides I hurried through and a brief explanation of each:

image

Among the things in ASMX and Remoting that were more difficult then they should be was security. Especially when you tried to accommodate all the various WS-* security needs. As a result, most people just didn’t secure their services and crossed their fingers. WCF addresses this by giving us a declarative security model that accommodates most common scenarios without having to write a lot of additional code, but allows us to use our own custom providers where we wish. But the great news is that even if you don’t explicitly an security, most out of the box bindings come with some sort of default form of security by virtue of the transport they employ.

When thinking about security in WCF, there are two ways to secure your messages. You can use either, both or neither forms.

imageTransport based security secures the channel that is used to send the message across the wire, in an effort to keep the message from being snooped by a hacker. If you’ve used SSL or TCP you’ve employed transport security. One of the main benefits of transport security is that it’s very fast. Once the initial secure connection is established there is really not much additional overhead. One drawback to transport security is that there can be some interoperability issues across platforms. The other being that transport based security is only “point to point” based security. This means that If there are any intermediary services between the client and the service the channel will only be secure between the client and the first intermediary service. After that first hop the message will be “in the open” and could be viewed and/or changed by a hacker.

imageAnother way to secure your communications over WCF is to used message based security. When you this method the message, meaning anything in the body of the SOAP message is encrypted. If the message is spoofed, the encryption protects the message from being read or altered by hackers. This works well in situations where there are intermediary services between the client and the service since the header of the message, which contains the routing in formation is not encrypted and the intermediary service (generally) does not care or need to know what the content of the message is. The draw back is that this method can be a bit slow; encryption/decryption can be slow. The encrypted messages also tend to “bloat” a bit.

Both of these methods can be combined; you can send and encrypted message over a secure transport. This combines the benefits and costs of each method.

The great thing about WCF is that unless you select the basicHttpBinding (which should only be used for legacy, pre WS-I 1.1. Basic Profile services anyway) you have some implicit level of security by virtue of the transport you are using. This is a low-level of security; you should always do a security assessment as part of your design and determine what, if any additional security is needed.

 

image

There are some great new things coming in .NET 4. The most eagerly anticipated one is default endpoints and behaviors. As you write a lot of WCF services, you’ll see that you tend to repeat the configuration required for you endpoints over and over. WCF will now take this most common endpoint scenario and use it as a default endpoint. For example, if you tell WCF that you want you service to have a wsHttpBinding endpoint, but provide no other information, it will use the default definition of a wsHttpBinding endpoint. If you want to extend/change the configuration for your endpoints you can do that; WCF in .NET 4 supports the same configuration model used in .NET 3.5. But you’ll find that you spend less time in the configuration, which is where most problems with WCF occur.

The other big new feature is Dynamically Discoverable services. These allow you to create clients which probe the network to locate services that support the contract and requirements of the contract at runtime instead of having to have the address of the service statically stored in the client configuration. This allows you to move services, create services with different Quality of Service (QoS) settings and have the clients be able to locate and consume these services as needed.

Thanks again to everybody who came to my sessions. If you have any questions about Dependence Injection, WCF or anything please feel free ask them in the comments.

Code on!

DotNetKicks Image

I Got To Watch A Shuttle Launch!

Gayle took this picture of Atlantis launchingFor what has to be one of the coolest birthday gifts ever, Gayle arranged a trip to see the shuttle Atlantis launch on her last flight. She booked everything on her own, which is no small feat when you consider she had to book flights, a hotel and a rental car for a very popular destination in a short amount of time and managed to keep me completely in the dark as to where we were going and what we were going to do. I knew we were going somewhere. I even knew it was in Florida. I even gave her advice about certain aspects of the trip. I had no idea where we were going till she told me. And every time I thought I knew, something would happen or a piece of information would be disclosed that indicated I was way off. She literally kept me guessing until the last possible moment.

Being a geek, I’ve always been into space and the idea of space travel. When I was five I remembering pestering my Mom to take me to see this weird science fiction movie that had just come out called “Star Wars.” It was the first movie I remember going to. My mother was working at a company called United Technology at the time as office staff on a “big project.” Turns out this project was building components for the solid rocket boosters (SRB) for the first space shuttle, Columbia. This worked out great for me since UT would allow families to attend some of the test firings of the booster rockets. They tested these by putting them in the group upside down so the nozzle was pointing in the air. These tests were so cool; watching a giant burst of fire blast into the sky and hearing the deafening sound of the booster firing was geek heaven.

As an adult I’m sad to see the shuttle program coming to an end. Frankly I think it’s a mistake; we’re abdicating our position as a leader in space exploration and technology. Being someone with Libertarian leanings I understand the importance of allowing the private sector to begin working in space. But, and I understand this flies in the face of the plotline of every feel-good sci-fi story out there about the evil military, but the fact is that space is something that can be easily militarized and we have a national defense interest in space travel. What happens if a year from now North Korea launches a space shuttle? But, it looks like the program is coming to an end. I had always wanted to attend a shuttle launch, but never thought to actually try to go to one. With the program ending I just figured it was one of those things that I would miss. I’m glad I was wrong.

STS-132_patch

So what was it like?The launch was at 2:20 PM and right on time we could see a giant cloud of white smoke emerge from the base of the shuttle. A few seconds later the shuttle took off. Watching on TV I don’t think I ever really got a sense for how fast the shuttle takes off; it always seems to slowly climb past the tower into the sky. Being there I can tell you that once the ship breaks the inertia, it hauls ass! For about the first 45 seconds we just stood there watching. Then the sound hit us. It wasn’t the big, sudden "BOOM!” like I expected and experienced as a kid at the SRB test; it was kind of a VERY loud, rolling “GRRRRRR!” that only lasted about ten seconds. About that time the shuttle started making its “arc” towards entering orbit. It was so far away by this point that we were watching a small silvery dot ridding on plume of flame about 25 stories high. A few seconds after that the SRB’s shut down. We watched until the shuttle was too far away for us to follow. It was amazing!

We weren’t able to get into Kennedy Space Center for the launch. Gayle tried very hard to get us tickets, but even before the program was cancelled it was a difficult process that had you competing with thousands of other people who also really want to be there. Instead we were able to find a nice park across the river from the launch pad. I would guess we were about four to five miles away and had a good clear view of the shuttle on the pad. We got to the park about two and a half hours before the launch. We didn’t have to park far, and while the park already had a lot of people in it, I wouldn’t call it crowded. As more and more people started to arrive, Gayle and I entertained ourselves with some “people watching.” The crowd seemed to be a pretty diverse bunch, mixing locals and people who had come to town for the launch, as well as people (like us) who were “first-timers” and some people who have attended almost every launch.

Two days later we went to Kennedy Space Center and went on the tour. We saw a lot of really cool stuff; the Vehicle Assembly Building is HUGE, but you have to see it in person to really appreciate it. But I got a sense of sadness from a lot of the people there. They are witnessing the end of an area. And unlike the people who worked on the Mercury, Gemini and Apollo programs, there is no clear direction as to what, if anything, is next.

I had a great time! It was an amazing experience, and I hope to have an opportunity to watch whatever the next generations of space vehicle is take off one day.

DotNetKicks Image