Archive for March 2008

GhostDoc

Besides ReSharper, there is only one other Visual Studio plugin that I cannot live without — GhostDoc.  If you have not used it before, it basically generates XML comments on your code and makes a best guess on what the comment summary should be.  This feature is pretty standard for Java IDEs (except for the actually generation of the summary for you), but it is yet another thing that is missing in Visual Studio. 

 

If you follow good naming conventions in your code, then you should get pretty decent results on the summary it generates.  It is definately a keystroke saver and makes documenting your code somewhat infectious.  When I see code that is undocumented, it is really hard for me not to hit Ctrl-Shift-D and have GhostDoc document it.

 

There are a number of different features/options and I am definitely not doing it justice in this short post.  The best way to find out if you like it is to try it out.  Small download and quick installation.

Castle ActiveRecord SessionScope and WCF

If you are familiar with NHibernate flushing semantics, then you know you usually want to treat a group of database operations as a single unit of work.  For one reason, flushing is expensive because it requires checking all of your entities for changes to see if they should be persisted to the database.  Second, you often want to treat all of your database operations as an atomic transaction.  Third, any entities that have lazy loaded properties can take advantage of the existing session.  ActiveRecord provides a nice abstraction for treating multiple database operations as a unit of work called SessionScope.  For instance, if all of your database operations are grouped together in one location, you would use SessionScope like:

 

var person = ...
var child = ...
using (SessionScope scope = new SessionScope)
{
  person.Save();
  child.Save();
}

In this case the neither the person or child is saved to the database until the Dispose() is called on the SessionScope.  For  the simple scenarios, this works fine, but in most cases you are doing your database operations in a DAO or Repository class — so you do not know how the database operations are going to be used or what other operations are going to be used with them.

If you are using ActiveRecord with MonoRail or another MVC framework, odds are you are using the built in SessionScopeWebModule to manage the SessionScope for you.  The web module begins a session when an HTTP request begins and ends it when the request has been processed.  Internally, the module uses HttpContext.Current.Items to store the current SessionScope in a thread local while the request is being processed.  If you are hosting your WCF services under IIS, you can take advantage of the web module to manage your SessionScope for you. 

If you are hosting not hosting your WCF services under IIS, then you need another mechanism for managing the SessionScope.  Fortunately, WCF provides a hook for just this type of scenario, ICallContextInitializer.  The WCF examples taking about using this extension point for managing thread context culture or impersonation scenarios.  First you need to implement ICallContextInitializer (I have removed documentation and logging for brevity, but I would recommend putting logging statements in so you can see what is going on at runtime):

    public class ARSessionScopeCallContextlInitializer : ICallContextInitializer
    {

        private const string ActiveRecordSessionScopeKey = "wcf.ar.sessionscope";

        public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
        {
            SessionScope scope = Local.Data[ActiveRecordSessionScopeKey] as SessionScope;
            if (scope == null)
            {
                Logger.Debug("Creating new ActiveRecord SessonScope");
                scope = new SessionScope();
                Local.Data[ActiveRecordSessionScopeKey] = scope;
            }
            return scope;
        }

        public void AfterInvoke(object correlationState)
        {
            SessionScope scope = Local.Data[ActiveRecordSessionScopeKey] as SessionScope;
            if (scope != null)
            {
                scope.Dispose();
            }
        }

    }

 

You can find the Local.Data class in Ayende’s rhino-commons library, but it just a simple wrapper around thread local storage.  Next, you need to implement IEndpointBehavior to add the initializer to your service:

    public class ARSessionScopeBehavior : IEndpointBehavior
    {

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            foreach (DispatchOperation operation in endpointDispatcher.DispatchRuntime.Operations)
            {
                 operation.CallContextInitializers.Add(new ARSessionScopeContextCallInitializer());
            }
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }

    }

And finally, an example for configuring your service:

            var uri = new Uri("net.tcp://localhost/TestSessionScope");
            var host = new WindsorServiceHost(typeof(AuthorizationService));
            var endpointAddress = new EndpointAddress(uri);
            var endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof (ITestService)), new NetTcpBinding(), endpointAddress);
            endpoint.Behaviors.Add(new ARSessionScopeBehavior());
            _host.Description.Endpoints.Add(endpoint);
            _host.Open();

 

And that’s it.  If you want to be more explcit about your flushing behavior — for instance creating a ReadOnlySessionScope that never flushes for read only operations, you can modify the EndpointBehavior to work declaritively with attributes so that you could mark individual WCF methods with configuration information such as [ReadOnly].  I have read some discussions about poor performance do to flushing of read only operations, so this might be worth looking into if you are doing a lot of read only operations on a large object graph.