Miguel A. Castro's Blog

# Tuesday, July 27, 2010

Note: Using a Console app for hosting should be done for development only !

Now that the disclaimer is out of the way, I currently doing some development work for a customer and I had the need to know every time any of my services receives a call.  Since I do my development using a console application for service hosting, it was easy enough to write out to the console from each service operation.  Of course, putting code in every method was possible but not only would it be time consuming, to turn it off later would be a pain.  The answer needed to be something that gets hit on every operation.  Since WCF is essentially one giant inversion of control container, I knew there was a point I could tap into before any operation call.

Enter behaviors !

This turned out to be a multi-step process but once it’s in my library of WCF stuff, I can reuse it and it actually turned out to be quite cool.  I’ll explain each step and the reasons for the step.

Step 1 – Write a custom Parameter Inspector

The first class you need to write is one that implements the IParameterInspector which is in the System.ServiceModel.Dispatcher namespace.  This class will later be installed in such a way that it gets hit on every operation call.  The operation name is one of the arguments you have access to, as well as all the operation arguments which I don’t need in this case.

The methods in this implementation are BeforeCall and AfterCall, and it is the BeforeCall that I’m interested in.  The code I’ll place in this method very simply outputs something out to the console using Console.Writeline.

Unfortunately the name of the service is not passed into this method so I need to get that into this class using a custom constructor; you’ll see how I’ll get it to the class later.

Here’s the code for my ConsoleReportInspector class:

 

public class ConsoleReportInspector : IParameterInspector
{
    public ConsoleReportInspector(string serviceName)
    {
        _ServiceName = serviceName;
    }

    string _ServiceName = string.Empty;

    void IParameterInspector.AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
    {
    }

    object IParameterInspector.BeforeCall(string operationName, object[] inputs)
    {
        Console.WriteLine(string.Format("{0} - '{1}.{2}' operation called.", DateTime.Now.ToLongTimeString(), _ServiceName, operationName));

        return null;
    }
}


 

Step 2 – Install the class using an Operation Behavior

In order to install the parameter inspector, I’ll need to write a custom operation behavior class.  This is a class that implements the IOperationBehavior interface.  You need to remove the throw to NotImplementedException from all the methods; and the method of concern here is ApplyDispatchBehavior.

The name of the service being called is accessible through the Parent property of the dispatchOperation argument.  I need to instantiate my ConsoleReportInspector class and send the service name into the constructor I added earlier.  Afterward, I just need to add my parameter inspector class to the list of parameter inspectors accessible in this behavior.

I also inherited this class from the System.Attribute class so I can use it as an operation behavior attribute on individual operations if I wanted.  This is just for flexibility since I plan on hooking this into a service so it affects all operations.

Here’s the code for my ConsoleReportOperationBehaviorAttribute class:

 

[AttributeUsage(AttributeTargets.Method)]
public class ConsoleReportOperationBehaviorAttribute : Attribute, IOperationBehavior
{
    void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {
    }

    void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        string serviceName = dispatchOperation.Parent.Type.Name;
        dispatchOperation.ParameterInspectors.Add(new ConsoleReportInspector(serviceName));
    }

    void IOperationBehavior.Validate(OperationDescription operationDescription)
    {
    }
}


As-is, I can simply decorate a service operation with [ConsoleReportOperationBehavior] and if hosted on a console application, you’ll see output to the console when the decorated operation is called.

 

Step 3 – Install the operation behavior on all operations using a Service Behavior

Next I need to write a service behavior.  This is a behavior that gets installed when the service loads (the host is opened).  The job of this behavior is to install my operation behavior on all the service operations.  A service behavior is a class that implement the IServiceBehavior interface.  Like before, I’ll remove the exception calls and once again the method I’m interested in is ApplyDispatchBehavior.

I’m going to iterate through all the endpoints of this service, which are accessible through the serviceDescription argument, and for each endpoint I will iterate through the operations of the contract of each endpoint.  To each operation I will add an instance of my ConsoleReportOperationBehaviorAttribute class.

This class too I will inherit from Attribute so I can use it to decorate a service in the case that I wanted to take this approach at some time. 

Here’s the code for my ConsoleReportServiceBehaviorAttribute class:

 

[AttributeUsage(AttributeTargets.Class)]
public class ConsoleReportServiceBehaviorAttribute : Attribute, IServiceBehavior
{
    void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
    }

    void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
            foreach (OperationDescription operation in endpoint.Contract.Operations)
                operation.Behaviors.Add(new ConsoleReportOperationBehaviorAttribute());
    }

    void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

 

Step 4 – Apply the service behavior to any service I want programmatically at the host

Whatever approach you take to hosting, all you need to do is access each instance of ServiceHost and add the service behavior to the list of behaviors in the host.  I have my own techniques for hosting which include some custom declarative stuff to allow me to turn hosting on and off at will through config.  I also like to separate the accumulation of my ServiceHost instances from the actual application that will do the hosting.  This way I can move it to a Windows Service when I’m ready to go to production.

Here’s the code that installs the behavior:

 

 

ConsoleReportServiceBehaviorAttribute behavior = serviceHost.Host.Description.Behaviors.Find<ConsoleReportServiceBehaviorAttribute>();
if (behavior == null)
    host.Description.Behaviors.Add(new ConsoleReportServiceBehaviorAttribute());

 

The host variable is an instance of ServiceHost.  I perform the code above in between a config check so I can toggle it off at will.

The end result is quite cool since when turned on, every call to any of your services will be shown on the console.

 

Until next time…

Tuesday, July 27, 2010 10:57:11 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1] - - Follow me on Twitter
Dev Stuff | WCF
# Monday, May 24, 2010

WCF 4.0 incorporates the features previously only obtainable via the REST Starter kit for .NET 3.5.  Among the features included is the ability to cache REST requests using a similar technique to caching ASP.NET pages.

The 4.0 version of the System.ServiceModel.Web assembly includes an attribute called AspNetCacheProfile which takes a string as an argument.  The attribute is to be used on a service contract operation as follows:

[OperationContract]
[WebGet(UriTemplate = "/{name}/getGreeting.xml",
        BodyStyle = WebMessageBodyStyle.Bare,
        RequestFormat = WebMessageFormat.Xml,
        ResponseFormat = WebMessageFormat.Xml)]
[AspNetCacheProfile("CacheFor10Seconds")]
string GetGreetingXml(string name);

 

The string points to a cache profile to be defined in the config section as follows:


    
        
            
        
    

 

As you can see, this is pretty much identical to setting up cache profiles for ASPX pages.  The effect is pretty much what you would expect, the caching of a REST request.  This can be proven and tested by implementing the above contract as such:

public string GetGreetingXml(string name)
{
    return string.Format("Hello {0}.  The time is {1}", name, DateTime.Now.ToLongTimeString());
}

 

Now you can refresh the request and you’ll see the same time for 10 seconds before it changes; once again, the same effect as in caching an ASPX page.

So what did I learn the hard way you ask?  Well, common sense dictates that the request go through ASP.NET in order to use its caching capability.  This not only means that you have to host in IIS or WAS, but also that you need to turn on ASP.NET compatibility mode.  This shifts the processing of the REST request over to an HTTP handler that also sets an HTTP Context for you, something not normally done with conventional IIS hosting for REST services.  To turn this on, you must enable it in the section under the section using the aspNetCompatibilityEnabled attribute.  Not only that, but you have to “allow” it on the service using the AspNetCompatibilityRequirements attribute.

This part was not a surprise for me since I was already familiar with this technique and the added scope your service receives because it.  I’m referring to the entire HTTP Context including session, application, cache, etc.  Keep in mind that this is not for everything and should be used in very specific scenarios as it ties the service to the hosting style quite tightly.

What drove me crazy is something I’m surprised I did not notice in the past and that is the fact that your REST requests will not work while using the Visual Studio development server.  Meaning you need to create an application in IIS and run it that way.  No big deal but it drove me a little crazy since the meta data exposure worked fine, and so did the new HTML Help pages (another new feature in WCF 4.0 For REST).  But the second I tried to request one of my URLs, it bombed out.  Once I set up my application under IIS, everything was fine.

I have to give credit where it’s due and thank Jon Flanders.  I found the answer in his book Restful .NET from O’Reilly press.

Until next time…

Monday, May 24, 2010 4:50:14 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - - Follow me on Twitter
Dev Stuff | WCF
# Tuesday, March 16, 2010

In the never-ending quest to keep my site up-to-date, I wanted to add a “latest tweet” area to the top of my blog.  All these tweakings I’ve done (the syntax highlighter, licensing, branding, etc) were actually inspired by a talk that Scott Hanselman made in Cairo Code Camp on making your blog suck less.  The talk is based on this posting he made some time ago.  I’ll post on all the tweakings I’ve done later; let’s get back to the Twitter feed.

The Twitter site self has a section where you can step through creating an embedded Twitter feed, either in Flash or HTML.  In fact if you Google or Bing the phrase “embed twitter feed on website”, you’ll see many different techniques.  The one I used is the one right off the Twitter site.

After walking through the wizard, the site gives you this code:

<div id="twitter_div">
    <h2 class="sidebar-title">Twitter Updates</h2>
    <ul id="twitter_update_list"></ul>
    <a href="http://twitter.com/miguelcastro67" id="twitter-link" style="display:block;text-align:right;">follow me on Twitter</a>
</div>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/miguelcastro67.json?callback=twitterCallback2&count=5"></script>

I first inserted this code as-is, just to get things working (my usual approach to things).  The div tag was inserted into my homeTemplate.blogTemplate in the area where I wanted to display my Twitter feed.  In my case, this was just below the area that shows the admin bar (shown only when logged in).  The two script tags need to be placed at the bottom of the same file, just above the closing body tag.  This displayed my last five tweets in a unordered list.  The first script tag includes the function that the Twitter site will call back to after retrieving my feed information.  The second script tag makes the call to the Twitter API and defines the name of the callback function defined in the first script.  This worked fine but I wanted a different look.

The first thing I did to modify the display is to browse to the http://twitter.com/javascripts/blogger.js link and place the function in a javascript file in my site; then I replaced the src attribute in the first script tag to point at my function.  The results of this of course were no different than before – good.

Next I modified the div section for my display to look like this:

<div class="twitter-div">
    <a class="twitter-header" href="http://twitter.com/miguelcastro67" alt="Follow me on Twitter">Last Tweet:</a>&nbsp;
    <span id="twitter-post" class="twitter-post"><i>retrieving last tweet...</i></span>
</div>
<br/>

 

As you can see, I eliminated the unordered list and replaced it with something more simple, that’s one line only, and that expects only one tweet.  Then I took the function I had obtained from the blogger.js file and modified to look like this:

function twitterCallback(twitters) 
{
    var statusHTML = [];
    var username = twitters[0].user.screen_name;
    var status = twitters[0].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
        return '<a href="' + url + '">' + url + '</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
        return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
    });
    statusHTML.push('<span>' + status + '</span> - <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[0].id + '">' + relative_time(twitters[0].created_at) + '</a>');
    document.getElementById('twitter-post').innerHTML = statusHTML.join('');
}

function relative_time(time_value)
{ var values = time_value.split(" "); time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3]; var parsed_date = Date.parse(time_value); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - parsed_date) / 1000); delta = delta + (relative_to.getTimezoneOffset() * 60); if (delta < 60) { return 'less than a minute ago'; } else if (delta < 120) { return 'about a minute ago'; } else if (delta < (60 * 60)) { return (parseInt(delta / 60)).toString() + ' minutes ago'; } else if (delta < (120 * 60)) { return 'about an hour ago'; } else if (delta < (24 * 60 * 60)) { return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'; } else if (delta < (48 * 60 * 60)) { return '1 day ago'; } else { return (parseInt(delta / 86400)).toString() + ' days ago'; } }

Now I only worry about one tweet and display information about that tweet into the inner section of the span tag called twitter-post.  Incidentally, the original callback function looked like this:

function twitterCallback2(twitters) {
    var statusHTML = [];
    for (var i = 0; i < twitters.length; i++) {
        var username = twitters[i].user.screen_name;
        var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return '<a href="' + url + '">' + url + '</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
        });
        statusHTML.push('<li><span>' + status + '</span> - <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + '</a></li>');
    }
    document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

 

Obviously I changed the name in the call to the Twitter API to use the callback function twitterCallback instead of the original twitterCallback2, but of course this can be anything so long as the two match.

The last change was to change the count attribute in the call to the Twitter API to 1 instead of 5.  This wasn’t crucial since I was only dealing with array item 0 in my callback function, but in the interest of getting as much performance as possible I thought it was a good idea.

I added the style sheet tags to make the display look the way I wanted and voila.  Because of the callback-nature of this technique, the blog page will render first while the call to the Twitter API is made and in the meantime I display a “retrieving…” message.

Until next time.

Tuesday, March 16, 2010 4:54:16 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - - Follow me on Twitter
Dev Stuff
Search
Me & My Flair

Read all about me here.
Download my Resume here.

Check out where I am here.
 
Click on logos above for profiles.
Archive
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
Statistics
Total Posts: 25
This Year: 25
This Month: 2
This Week: 0
Comments: 28