Power To The Developers!

Previously on this site I've demonstrated a couple of different ways to have a WCF service implement a custom behavior. Configuration allows service behaviors to be added and managed at runtime by system administrators via configuration files. Adding the service in your service host code ensures that in a given hosting environment a service will use a specific behavior in a specific way.

But as service developers, there are going to be times when we want to ensure a particular service or service operation employees a behavior. We can't rely on our hosting environment to know about our requirement for this custom service. Leaving it to configuration opens us to more issues as we are pinning our hopes on a pile of documentation that probably hasn't been read since it was written.

Keep things close

In the course of your WCF-travels, you've probably seen something like this:

[ServiceBehavior(IncludeExceptionDetailInFaults = false, 
    TransactionTimeout = "00:05:00")]
public class HelloWCF : IHelloWCF
{
    public string SayHello(string name)
    {
        return string.Format("Hello {0} from WCF{1}", name);
    }
}

In this case the developer of this service is using a ServiceBehaviour attribute to set some service behaviors at development time (providing the underlying hosting environment supports the service behavior options you've specified). This code is the equivalent of the following configuration:

<behaviors>
  <serviceBehaviors>
    <behavior name="CustomBehavior.Service1Behavior">
      <serviceDebug includeExceptionDetailInFaults="false" />
      <serviceTimeouts transactionTimeout="00:05:00" />
    </behavior>
  </serviceBehaviors>
</behaviors>

Wouldn't be great if we could have our custom behavior implemented as an attribute?

Wish no more

.NET developers have had the ability to create custom Attributes since .NET 1.0, simply by inheriting from the System.Attribute class.

Consider this example:

class errorServiceBehavior : IServiceBehavior
{
    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        return;
    }

    public void AddBindingParameters(ServiceDescription serviceDescription, 
        ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, 
        BindingParameterCollection bindingParameters)
    {
        return;
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, 
        ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            if (dispatcher != null)
            {
                dispatcher.ErrorHandlers.Add(new customErrorHandler());
            }
        }
    }
}

Here we have a standard, run-of-the-mill service behavior that adds an instance of a custom error handler to our service. More on that custom error handler later. To implement this in our service as-is we would need to have the host process attach this behavior at runtime. If we wanted to have it added and managed via configuration at runtime we would need an instance of BehaviorExtensionElement and override the BehaviorType property and CreateBehavior method.

Let's make a little change to the class declaration here:

[AttributeUsage(AttributeTargets.Class)]
 class errorServiceBehavior : Attribute, IServiceBehavior
 {

By inheriting from Attribute, our behavior now has the ability to be used just like an other .NET attribute. The AttrbuteUsage attribute is optional, but is a good idea to use. In this case we are telling the .NET runtime that this attribute can only be applied at the class level. If we wanted to create an operation behavior attribute (yes! you can do this with operation behaviors too!) you would set the AttributeUsage to AttributeTarget.Method

From here it's a simple matter of implementing our custom behavior by applying our custom service behavior attribute to our service class:

[errorServiceBehavior]
public class HelloWCF : IHelloWCF
{
    public string SayHello(string name)
    {
        return string.Format("Hello {0} from WCF{1}", name);
    }

    public void ThrowAnError()
    {
        throw new FaultException<Behavior.CustomFault>(new CustomFault("This is a test."));
    }
}

This custom behavior implements a custom error handler:

public class customErrorHandler : IErrorHandler
{
    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var customFault = new FaultException<CustomFault>(new CustomFault(error.Message), 
            "You did _something_ wrong.");
        var msgFault = customFault.CreateMessageFault();
        fault = Message.CreateMessage(version, msgFault, customFault.Action);
    }

    public bool HandleError(Exception error)
    {
        return true;
    }
}

To keep things simple, this handler simple adds some custom message text to the fault exception before the fault is returned to the client. When running the services client we can see the custom error handler in action:

image

This is just a simple example. With some experience working with classes inherited from Attribute you can put a lot of power in the hands of your service developer to control how their services are used. Have fun!

Print | posted on Monday, October 13, 2008 10:21 PM

Feedback

# re: Power To The Developers!

left by Checks at 4/4/2010 12:44 PM Gravatar
Thanks for sharing your thought. Wish you good luck for your future endeavors.

# re: Power To The Developers!

left by CDPdiazhuLJPYLL701 at 8/4/2010 1:31 AM Gravatar
70-680 Exam
Exam NetApp Certified Implementation Engineer-SAN and Virtualization 70-270
Exam Number/Code : NS0-502 Exam Name : NetApp 70-290
Certified Implementation Engineer-SAN and Virtualization Questions and Answers : 106 Q&As It is well known that NS0-502 exam test is the hot exam of Network 70-291
Appliance certification. TestInside offer you all the 70-291
Q&A of the NS0-502 real test . As a Network Appliance ...

# re: Power To The Developers!

left by Kingkle at 8/8/2010 2:44 AM Gravatar
By training your thoughtsreplica Hublot watches
to concentrate on the brighOmega replica watches
t side of things, you are more likely replica Audemars Piguet watches
to have the incentive to follow through on Tag Heuer replica watches
your goals. You are less likely to be held back byAudemars Piguet replica watches
negative ideas that might limit your performance.

# re: Power To The Developers!

left by gucci bags at 8/12/2010 12:12 AM Gravatar
BEAUTIFUL

# re: Power To The Developers!

left by WoW Carte prépayée at 8/21/2010 5:06 AM Gravatar
Gagnez votre WoW EU Clé CD, Aion EU Clé CD, WoW Carte prépayée dans CD Clé store. Tous en stock, rapide, recevoir dans minutes.

# re: Power To The Developers!

left by coach bags at 8/22/2010 11:41 PM Gravatar
Market is flooded UGG Boots on Sale with different types UGG Classic Short Boots of leather UGG Classic Tall Boots bags and wallets UGG Argyle Knit Boots. When it comes to UGG Bailey Button Boots choosing a leather bags UGG Classic Cardy Boots or wallet, UGG Baby Coach Leather bags Kids UGG Boots and wallets are Timberland Shoes something that Shoes Timberland you can rely Vibram Five Fingers on. Coach leather bags Vibram FiveFingers and wallets a have Discount Vibram Five Fingers been in the Discount Vibram FiveFingers market since Discount Vibram 1940s. These leather bags Prada Shoes have made a distinguished Gucci Shoes in the market. Not only Coach Bags in terms of quality these leather Coach New Style Bags are popular for both Coach New Style Bags and elegance. Before you go to purchase a leather prada Bags, make up your Gucci Bags which kind of Chanel Bags you want to go for Louis Vuitton Bags. Since these wallets are Jimmy Choo Bags in different colors, Tous Bags and design MBT Shoes you are a MBT Shoes on sale confused as to which MBT Sandals to buy MBT Shoes Outlet. Here are a MBT Sandals on Sale tips to MBT Outlet choose which for MBT Men’s Shoes who are fond of carrying MBT Women’s Shoes all the time, going for a Outlet MBT leather bag also. Ray Ban Sunglasses or bag suits Oakley Sunglasses. Here are lots of Chanel Jewelry first of all Outlet kind of Tiffany Jewelry outlet who carry more Tiffany Jewelry cards than Chanel Jewelry Online, go for the Jewelry Online Outlet which have more credit Cartier Jewelry compartments.

# Miss Mughal

left by Sarah Mughal at 8/26/2010 1:26 PM Gravatar
Learn Online English Language ||| ||| Learn Free Online English Language
Free English Learning ||| ||| Learn free english language course and english grammer
Online Games ||| ||| Action games, adventure games, kids games, online games ……
Cellular Phone Services ||| ||| Mobile services like Nokia, Samsung, Sone Errection
All About Fashion ||| ||| Shoes, Dresses, Purse, Volets, Botique and Modern Fashion
Buy Electornics ||| ||| Buy Electronics Buy Computers Buy Laptops Buy DVD Buy Watches Buy Cameras Buy Cell Phones Accessories
buy watches ||| ||| Buy wholesale watches and wall clocks at affordable cost.
buy dvd and vcd ||| ||| Buy wholesale dvd and vcd at affordable cost.

# re: Power To The Developers!

left by pangsiyan at 8/26/2010 11:33 PM Gravatar
38.Candidates need to keep in mind passport and visa details if traveling to another country to take the ccie bootcamp training as well as factoring in the cost of the travel ccie voice lab boot camp. The locations of the ccie voice training can be found here.
Title  
Name
Email (never displayed)
Url
Comments   
Please add 3 and 4 and type the answer here: