powered by myself

CompactContainer rebump

Almost a year ago I did some experimentation with porting Castle Windsor to be used under the .NET Compact Framework, and while I got it done (excluding several features; mainly everything that has to do with proxys), it was clear that its implementation was not though to be used in a resource-constrained environment.

Windsor has lots of functionality that I was wishing to be able to use in some Compact Framework applications, but according to the results of my tests, it was slower and consumed more memory than my own CompactContainer. Sum that to the fact that Windsor is evolving every day and most of the new stuff use features of .NET that are not available under the Compact Framework, and I had a pretty good reason not go further with this endeavor.

Considering the previously described experiments I’ve decided to add the features I was needing to CompactContainer.

So my first step was to migrate the repository to Mercurial (good: it is so much easy to work with than SVN / bad: you now need a hg client to get the source code), then I refactored a little the existing code-base and finally I added several new features.

Here is a list of the major changes and additions:

  • Ditched .NET Compact Framework 2.0 support
  • Lots of internal refactorings:
    • Changed main namespace from InversionOfControl to CompactContainer
    • Renamed IHandler to IActivator (implementors are responsible of instantiating components)
    • Removed ComponentList and replaced by IEnumerable<ComponentInfo> and extension methods
    • Changed auto registration stuff by implementations of IDiscoveryConvention
    • Removed capability to resolve component given its implementation type.
    • … several others that I cannot remember right now… (I should really keep a changelog file)
  • Major new features:
    • Implemented programmatic registration heavily based on Castle Windsor API
    • Added several extension points: IActivator, IDependencyResolver, IComponentSelector and IDiscoveryConvention
    • Added property injection support
    • Added container events for component registration and component resolution
    • Added basic container facilities support (a-la-Windsor)
    • Added basic configuration method to be used by IComponentsInstaller and IFacility implementors

Another thing that I’ve done is to remove the binary files available for download… I’ve done this for mainly 2 reasons:

  • I don’t have an automated build process, so I needed to remember to make this archive manually in each commit and I always keep forgetting about it (I need to do something about this)
  • the existing file was compiled for just one target (Pocket PC 2003 SE Emulator), but most probably you’d need to compile it again for the target platform that you are actually using, so it seems worthless to have to maintain something that in the end it is not going to be used; however, I see in my Google Analytics reports that the binaries were downloaded several times, so I promise to put it up again once I solve the versioning/automation stuff.

All in all, I’m very happy with the current state of this project and it is actually helping me a lot in some places.

If you have some comment or suggestion or bug report about CompactContainer, feel free to contact me and let me know!

Deferred execution based on PropertyChanged

A few days ago I was implementing toast notifications for a Silverlight application (SL 4 has support for toast notifications but it is only available to out-of-browser applications) and one of the features that I wanted to implement was that the notification doesn’t go away while the user holds the mouse pointer over it – pretty much like Tweetdeck notifications.

The idea was that I’d start a timer when the notification is shown and when it times out, if the mouse pointer wasn’t over the notification window it would fade out, but if the mouse was indeed over the notification, I’d hook into the MouseLeave event to defer hiding the notification until that event was triggered.

Since I was using the MVVM pattern, rather than handling this in code-behind and attaching directly to the MouseLeave event I had a ViewModel bound to the notification view (UserControl) with a property called IsMouseOver (in the sample application I update this property directly from the events handler in code-behind, but in my actual application I’m using Caliburn and doing all this using its Actions feature).

So, the code for the timer tick handler was something like this:

if (!IsMouseOver)
{
	RequestClose();
}
else
{

	Observable.FromEvent<PropertyChangedEventArgs>(this, "PropertyChanged")
		.Where(ev => ev.EventArgs.PropertyName == "IsMouseOver" && !((NotificationViewModel)ev.Sender).IsMouseOver)
		.Subscribe(delegate { RequestClose(); });
}
 

Notice that here I used Rx (because I already had the reference) to hook to the PropertyChanged event of the notification ViewModel to monitor the IsMouseOver property value and trigger the closing of the notification when it becomes false.

At the time of writing, that was the easiest way to accomplish the requirement, but it sparked a light in my head and made me think about which would be the ideal syntax for that code… and I always end up thinking about something like this:

Execute.NowOrWhenBecomesTrue(() => IsMouseOver == false, () => RequestClose());

So, now after a quite lengthy intro I want to show you how did I implement this method:

public static class Execute
{
	private static readonly ExpressionType[] ValidExpressionTypes =
		new[]
			{
				ExpressionType.Equal, ExpressionType.NotEqual,
				ExpressionType.GreaterThan,
				ExpressionType.GreaterThanOrEqual,
				ExpressionType.LessThan,
				ExpressionType.LessThanOrEqual
			};

	public static void NowOrWhenBecomesTrue(Expression<Func<bool>> condition, Action action)
	{
		var compiledCondition = condition.Compile();

		if (compiledCondition())
		{
			action();
			return;
		}

		var binaryExpression = condition.Body as BinaryExpression;
		if (binaryExpression == null)
			throw new ArgumentException("must be a binary expression", "condition");

		if (ValidExpressionTypes.Any(t => t == binaryExpression.NodeType) == false)
			throw new ArgumentException("expression is invalid, it must be ==, !=, >, >=, < or <=");

		var memberExpression = binaryExpression.Left as MemberExpression;
		if (memberExpression == null)
			throw new ArgumentException("left side of expression must be a property access", "condition");

		var propertyName = memberExpression.Member.Name;

		var inpc = GetHostFromExpression(memberExpression.Expression) as INotifyPropertyChanged;
		if (inpc == null)
			throw new ArgumentException("cannot determine INotifyPropertyChanged implementor to watch", "condition");

		PropertyChangedEventHandler handler = null;
		handler = (s, e) =>
			        {
						if (e.PropertyName == propertyName)
			          	{
							if (compiledCondition())
							{
								action();
								inpc.PropertyChanged -= handler;
							}
			          	}
			        };

		inpc.PropertyChanged += handler;
	}

	private static object GetHostFromExpression(Expression expression)
	{
		if (expression.NodeType == ExpressionType.Constant)
			// case with "this" pointer
			return ((ConstantExpression)expression).Value;

		if (expression.NodeType == ExpressionType.MemberAccess)
			// case when accessing a property of an object other than "this"
			return GetObjectFromMemberExpression((MemberExpression)expression);

		return null;
	}

	private static object GetObjectFromMemberExpression(MemberExpression memberExpression)
	{
		var memberAccessor = memberExpression.Member;
		var host = GetHostFromExpression(memberExpression.Expression);
		return host == null ? null : GetObjectFromMember(memberAccessor, host);
	}

	private static object GetObjectFromMember(MemberInfo memberInfo, object host)
	{
		switch (memberInfo.MemberType)
		{
			case (MemberTypes.Property):
				return ((PropertyInfo) memberInfo).GetValue(host, null);
			case (MemberTypes.Field):
				return ((FieldInfo) memberInfo).GetValue(host);
		}
		return null;
	}
}

The main idea is that it takes a the left hand side expression of BinaryExpression, gets the name of the property that needs to be watched and tries to get the object instance that contains that property; it then hooks a handler for its PropertyChanged event where the expression is evaluated and based on its result the required action is executed; it then unhook the delegate to prevent further executions.

While the implementation is not perfect, it provides the desired functionality and some more:

  • it works on “this” class’ properties
  • it works on nested properties: if you have a property (or field) that implements INotifyPropertyChange you can attach to one of its properties too
  • the expression comparison can be any of these: ==, !=, <, <=, >, >=

A simple “notifications” sample application using this helper can be found here

As a side note, I think that this is one piece of code that can benefit from the deployment method that Daniel describes here.

Moving to WordPress

A couple of weeks ago I decided that I would migrate my blog to WordPress, and finally here I am.

I’m writing this mainly to keep record of my motivations, to describe briefly the steps that I’ve accomplished and maybe to give some tips to anyone who is willing to do the same.

Why?

A couple of my reasons:

  • I got tired of dealing with a formatting issue in Blogger that made my posts look ugly when I post any source code.
  • I was hosting a set of static pages (About, Projects, etc) at the root of my domain and I wanted that content to be integrated with the rest of my blog; I didn’t find out (didn’t research much either) how to do this in blogger, but with WP pages this is a standard feature.
  • I decided to restyle my blog and it seemed that there were a lot more of options with WP than with Blogger.
  • WP admin features and extensibility options looked outstanding (they are indeed).

How?

I was lucky enough to be using a custom subdomain (blog.schuager.com) instead of using the default Blogger domain (gschuager.blogspot.com); this allowed me to setup WP in another subdomain (blog2.schuager.com) and swap them when I finished.

The WordPress installation was very easy. I used this link as reference.

After that, I used a plugin to import all my posts and comments from Blogger.

I configured my new blog’s permalink options to match the url structure used by blogger and then put some code into web.config to tell IIS URL Rewrite to play nice with the new url format.

Then I moved to the styling phase:

  • I tried several themes (there are too many of them), but none of them convinced me as they were.
  • I research a little about theme authoring, theme frameworks, WP actions & filters, etc.
  • I ended up using WP framework and writing custom a CSS file (and some php code) to adapt the layout to what I was looking for
  • Firebug & Chrome developer tools where of great help at this point

I installed plugins for: syntax highlighting, comments spam filtering, broken links verification, Feedburner feed redirection, Google Analytics integration, etc.

The final step in my conversion was to review my old posts and update the embedded code to fix the styling issue mentioned above using the syntax highlighter plugin.

Conclusion

Here are images of the old blog vs the new one for comparison:

I think I’ve come up with a nice design and I’m very happy with the result
All that’s left now is to start bloging more often!

Contextual Lifestyle Reloaded

Some time ago I did some experimentation with a custom Castle Windsor lifestyle under the main motivation of coming up with a way for managing the NHibernate session in a fat client application.

After I posted my findings on that matter I have continued spiking a cleaner solution and I’ve came up with something worth sharing again; but this time, rather than posting the code here, I preferred to share it in a more visible and maintainable place, so I asked Mauricio if he was willing to include it in the Castle.Windsor.Lifestyles contrib project on github and he certainly did that (after reviewing my implementation and adding code for coping with components release – thanks Mauricio!)

As explained in my previous post about this matter, the idea of this lifestyle is to be able to define a context (or scope) in which the container will resolve always the same instance of a given component and when asking for the same component outside of that context, a new instance will be created.

One of the main changes from my previous attempt is that before I used an implicit delimitation of the context based on “a single call to container.Resolve”, but since then I’ve found that that strategy was rather limiting, so in this new implementation, the context can be explicitly defined by the ContainerContext class; although it is worth noting that the implicit delimitation of contexts can still be used in this new implementation.

To better describe the intended behavior, I’m including here a few tests that I think that should help make my intention clearer:

[Test]
public void Should_resolve_the_same_instances_when_inside_the_same_context()
{
	kernel.Register(Component.For<ComponentA>().LifeStyle.Custom(typeof(ContextualLifestyle)));
	using (new ContainerContext(kernel))
	{
		var c1 = kernel.Resolve<ComponentA>();
		var c2 = kernel.Resolve<ComponentA>();
		Assert.That(c1, Is.SameAs(c2));
	}
}

[Test]
public void Should_resolve_different_instances_when_inside_different_contexts()
{
	kernel.Register(Component.For<ComponentA>().LifeStyle.Custom(typeof(ContextualLifestyle)));

	ComponentA c1, c2;
	using (new ContainerContext(kernel))
	{
		c1 = kernel.Resolve<ComponentA>();
	}
	using (new ContainerContext(kernel))
	{
		c2 = kernel.Resolve<ComponentA>();
	}

	Assert.That(c1, Is.Not.SameAs(c2));
}

[Test]
public void Should_implicitly_initialize_a_new_context_when_there_is_none_created()
{
	kernel.Register(Component.For<ComponentA>().LifeStyle.Custom(typeof(ContextualLifestyle)));

	var c1 = kernel.Resolve<ComponentA>();
	var c2 = kernel.Resolve<ComponentA>();
	Assert.That(c1, Is.Not.SameAs(c2));
}

This lifestyle is supposed to work with nested dependencies, generic components, and in multithreaded scenarios, so if you use it and find anything wrong with it, please let me know.

You can get the code from here: https://github.com/castleprojectcontrib/Castle.Windsor.Lifestyles

How to setup Mercurial server on Windows/IIS

In this post I will enumerate the resources and the steps required to setup a Mercurial server under a Windows environment running on top of IIS 7.

This is not as straight-forward as it should be but it is not very difficult either.

You will need to download the following:

I will split the configuration steps into setting up the file system and configuring IIS.

Setting up the file system

1. Install Mercurial. I will assume the default install path: C:\Program Files (x86)\Mercurial

2. Install Python. I will assume the default install path: C:\Python26

3. Create a folder for your Hg web application. I will assume this path: C:\hg

4. Create a subfolder called lib and uncompress the contents of the file C:\Program Files (x86)\Mercurial\library.zip into C:\hg\lib

5. Copy the folder C:\Program Files (x86)\Mercurial\Templates into c:\hg\lib

At this point you should have something like this:

6. Copy the hgwebdir.cgi (link at the top of the post) file into your wep app folder root c:\hg and modify it so that it match your Python installation folder and your lib folder. Using my current path assumptions you should end with something like the one in the left of the following picture:

7. Create a folder named repos in c:\hg\repos. This folder will contain all our mercurial repositories. For testing purposed now we will create a test repository inside there; just run this from the command line “hg init c:\hg\repos\test” (this will create and initialize the test repository)

8. Create a file named hgweb.config at c:\hg\hgweb.config with the following content:

[paths]
/ = repos/*

[web]
baseurl = /hg
push_ssl = false
allow_push = *

here we are telling Mercurial basically 3 things: where are the repositories that it should serve, everybody can push, and it should allow pushes through non-secure connections (so we don’t need to setup https)

Configuring IIS

9. Add a new web application to your “Default Web Site”, name it “hg” and assign “c:\hg” to its Physical path.

10. Now we need to configure our newly created app to be able to execute Python scripts. Click on the “Handler Mappings”

then in “Add Script Map…” from the right menu

and then enter the script extension and Python executable path as shown in the following picture:

11. The final step is to configure Url Rewriter module correctly to allow us to use our repository with a nice URL like this: http://server/hg/test instead of http://server/hg/hgwebdir.cgi/test. For this you need to install the Url Rewriter module either using Web Platform installer or by manually doing so (link at the top of the post).

Once you have Url Rewriter installed, select it from you application Feature View:

then click on the “Add Rules…” action from the right side panel and select “Blank Rule”:

and enter the new rule data as shown in the following picture:

This should be all.

Now try to navigate to http://localhost/hg with your browser and you should see something like this:

Just remember to setup authentication if you are going to use this server over the internet. I left this to you since you can use any of the standard IIS authentication methods available.

NAnt task for getting Mercurial current revision

As part of my continuous integration process I like to get the current VCS revision and stick it somewhere in the build output (almost always to be displayed in some kind of “About” screen)

When using Mercurial in combination with NAnt, you can do this as follows:

<property name="hg.revision.hash" value="N/A" />

<target name="common.find-hginfo">
   <property name="vcs.revision" value="0" overwrite="false" />
   <exec
       program="hg"
       commandline='parents --template="{node|short}"'
       output="_revision.txt"
       failonerror="false"/>
   <loadfile file="_revision.txt"
             property="hg.revision.hash" />
   <property name="hg.revision.hash" value="${string::trim(hg.revision.hash)}" />
   <delete file="_revision.txt" failonerror="false" />
   <echo message="INFO: Using Hg revision: ${hg.revision.hash}"/>
</target>

Just put this target as a dependency somewhere else and use the property “hg.revision.hash” as you see fit.

Case-sensitive queries in NHibernate using SQL Server

Depending on the collation setting of your database (you probably already know this) the queries that you issue against it are treated as case-insensitive (CI collations) or as case-sensitive (CS collations).

If your database use a CI collation and you need to do some case-sensitive querying, the target SQL statement would be something like this:

SELECT u.Name
FROM Users u
WHERE u.Name like 'SomeName' COLLATE Modern_Spanish_CS_AS

Now, if you are using NHibernate you can do some things to make it help you issuing this kind of query.

The first one is to just use the Criteria API specifying the desired SQL expression:

var user = session.CreateCriteria(typeof (User))
    .Add(Expression.Sql("Username like ? collate Modern_Spanish_CS_AS", username, NHibernateUtil.String))
    .UniqueResult<User>();

This approach has the drawback that you tie your code to SQL Server specifically, and that will give you some headaches if you ever try to target another RDBMS.

The other (more elegant) option is to subclass the dialect that you are using (in this case MsSql2005Dialect) and register in it a custom function to perform case-sensitive comparisons.

public class CustomMsSqlDialect : MsSql2005Dialect
{
    public CustomMsSqlDialect()
    {
        RegisterFunction("sensitivelike",
            new SQLFunctionTemplate(NHibernateUtil.String,
                "?1 like ?2 collate Modern_Spanish_CS_AS"));
    }
}

Then you can use this new sensitivelike function inside any HQL statement and NHibernate will generate the correct SQL for you.

var user = session.CreateQuery("from User u where sensitivelike(u.Username, :username)")
    .SetParameter("username", username)
    .UniqueResult<User>();

This way allows you to support a different RDBMS just by registering the corresponding function implementation in a new derived dialect and without modifying your code.

Thanks to Dario for the tip.

Introducing NLaunch

In the last month I’ve been working in several desktop applications and faced the situation of having to remotely update my clients machines repeatedly. It is not fun. The process that I was using for accomplish this task was the following:

  1. build the application locally (I’m not using CI)
  2. upload the result somewhere (ftp, Mediafire, etc.)
  3. notify the client that I will be logging in to do some work
  4. log in remotely using Remote Desktop or LogMeIn (great tool BTW)
  5. backup the current running version (just in case)
  6. download and install the new version

I can tell you that it takes a lot of time to do these simple steps (and it is boring as hell) so I’ve decided to do something about it… I automated it.

The first thing that I’ve done is to evaluate the existing tools for this job. Here are some of them:

Clickonce

I had spent almost 3 non-consecutive days trying to integrate Clickonce deployment into my nant build scripts and I had failed; besides this, along the way I’ve discovered some limitations of Clickonce that made me look in other direction:

  • Target directory can’t be specified, it will always deploy to the Clickonce cache
  • Not easy to deploy updates without running through the whole workflow (signing, uploading, etc). This means that you can’t just recompile and xcopy the files to the target system (this is useful when you are at the client site).
  • Complex. Application manifest, deployment manifest, signing, mage (some things can be only done through mageui), etc, etc.

Updater Application Block

It has lots of functionalities, extensibility points and configuration options but it seems too big for my needs. I was looking for something simpler that just works with almost no configuration.

.NET Application Updater Component

Not looked at this enough. It is bundled as a component that must be dragged into a form of your application (didn’t liked that)

NLaunch

Anyway… those were some of the existing options, but I was looking for something a lot simpler, something that I hadn’t found, so I decided to write it myself.

My two main requirements were:

  • Dead simple: it must consist of a single executable file and maybe some configuration.
  • Unobtrusive: it must not require to add anything to the target application, it should work on its own.

The simplicity requirement have taken me to make a lot of assumptions and to apply some conventions (a good thing as long as they are documented) that may not apply in everyone’s scenario, for this reason, I’ve created several interfaces first and then developed its implementations to fulfill my requirements; this would allow anyone to easily replace some of my implementations with its owns in order to adjust NLaunch behavior. Right now it is not easily extensible without requiring source code modification, but I plan to fix that in the future.

Now with NLaunch my deployment process is reduced to this:

  1. Build the application locally and upload the results to an FTP server (all with just 2 clicks)

I can’t say that this is actually fun, but at least is it neither boring nor tiresome… because I don’t have to DO anything! :)

Well, enough writing for now, you can check out the project’s home page for a little more specific information and you can also download the source code (it is really simple) or a ready-to-work binary.

http://code.google.com/p/nlaunch/

Rich-client NHibernate session management

I’ve been struggling with this subject for quite some time now, and I’ve just seem to found the ‘sweet spot’.

Before we start, I need to describe some facts about the target application:

  • rich-client: this approach will work the same for a Winform application as for a WPF application.
  • multi-screen UI: it could be multi-form or tabbed or MDI… the important thing here is that you “will” have several screens opened at the same time.
  • application uses an Inversion of Control container for wiring up dependencies among other useful things (I’m using Castle Windsor/Microkernel)

Ok.

Before we continue, I recommend that you read the work of Sebastian Talamoni, that although not finished yet, covers a lot of ground.

Basically there are 4 options for NH session management on a rich-client environment:

  1. Session per application (per thread)
    • the simplest approach
    • only 1 session opened for the whole application lifecycle
    • lots of problems: cache size, stale data due to other users, unrecoverable exception, etc.
    • Fabio Maulo calls this pattern TIME BOMB
  2. Session per screen
    • 1 session opened for each form/tab/view/whatever
    • implies multiple concurrent sessions
    • since a single screen could be left opened for quite some time, this approach is almost equally susceptible to stale data as the previous one
  3. Every data access – Fine-grained sessions
    • every repository/DAO opens and closes a new session each time that a DB access is requested.
    • loss of some useful NH features like lazy loading and 1st level cache… not worth it.
  4. Session per use-case
    • also implies multiple concurrent sessions
    • this seems to be the right choice, however it is the most difficult to implement

Per-thread session management

Options 1 and 3 are easily implemented using some kind of thread-static session manager. Examples of this are Rhino.Commons and Castle NHibernate Integration Facility.

Each repository/DAO gets an instance of the a global “session manager” and uses it to get hold of the right session:

  • if 1 session per application is used, this “global” session is return by each call to SessionManager.OpenSession()
  • if fine-grained sessions are used there are two possibilities:
    • we are in the scope of another session… the outer session is returned
    • we are not in the scope of another session… a new one is created

The easy thing about this is that each repository/DAO can access to the “session manager” through some static accessor, or even better, they can receive a singleton (as in singleton lifestyle) instance as a parameter of its constructor, which enable us to use an Inversion of Control container to wire up these dependencies and ease the unit testing of these components (no statics = easier testing).

public class Presenter {

   private IBlogRepository blogRepository;

   public Presenter(IView view, IBlogRepository blogRepository)
   {
       this.blogRepository = blogRepository;
   }

   ...

}

public class BlogRepository : IBlogRepository

   private ISessionManager sessionManager;

   public BlogRepository(ISessionManager sessionManager)
   {
       this.sessionManager = sessionManager;
   }

   public Blog Get(int id)
   {
       using (ISession session = sessionManager.OpenSession()) {
           return session.Get<Blog>(id);
       }
   }
}

This pattern is suitable for a web application, where the context is usually given by the current request, but in a rich-client application it would imply that two opened screens (different contexts) would share the same session manager and therefore the same session when they intend to do some data access at the same time.

Contextual session management

Options 2 and 4 require another approach since they imply several simultaneous sessions through the lifecycle of the application. We can no longer have a static or singleton session storage from where to get the right session for each thread… we need some kind of “contextual session management” where each screen/use-case is treated as a different context and provided with sessions accordingly.

This don’t seem so hard, right? We can just do something like this for option 4:

public class Presenter {
   private ISessionManager sessionManager;
   private IBlogRepository blogRepository;

   public Presenter(IView view)
   {
       sessionManager = SessionManagerFactory.CreateNewContext();
       blogRepository = new BlogRepository(sessionManager);
   }
}

The implementation of BlogRepository in this case is the same as before.

At first sight this seems like a nice way to define contexts, but that is until you realize that you are making very hard to unit test this class (hardcoded dependencies) and you are neglecting the help of the IoC container to wire up things.

Imagine that now, instead of BlogRepository we need something like AggregatorService that depends on BlogRepository, UserRepository and CommentService, and CommentService depends on UserRepository and CommentRepository. In this case, you’d need to create the session manager and then to instantiate every one of this components passing the right arguments to them…. this seems too much work for me.

Managing the dependencies yourself is not fun, and your IoC container enjoys doing it for you anyway.

Maybe something can be done using some kind of service location and passing the current context down the chain, like this:

container.Resolve<IBlogRepository>(With.Dependency<ISessionManager>(sessionManager)); // imaginary syntax
container.Resolve<IAggregatorService>(With.Dependency<ISessionManager>(sessionManager)); // imaginary syntax

but there is an easier way, let me introduce you to the…

Contextual Session Manager

This is an extension to the NHibernate Integration Facility of the Castle project that allows me to control the scope of my session and do not impose a global per-thread scope.

The solution is integrated by the following components:

  • ContextualNHibernateFacility: inherits from NHibernateFacility and all it does is to replace some of the standard components registered by the original facility specifying the right Lifestyle for the new ones.
  • ContextualPerThreadStore: inherits from AbstractDictStackSessionStore and provides a contextual session storage where there will be a different session for each instance of this class for each thread (tricky). The original CallContextSessionStore uses the call-context to store sessions, that means that two different instances of CallContextSessionStore will return the same session for the same call-context… this behavior is the one that I didn’t like.
  • ContextualSessionManager: just inherits from DefaultSessionManager to specify a custom lifestyle (see below) to be use by Microkernel to manage this component.
  • ResolutionContextLifestyleManager: inherits from AbstractLifestylemanager. This is the “thing” that delimits our contexts. For more information go here.

This set of components allow me to use the container to resolve presenters, ViewModels, forms, or anything else that I’d like to use to delimit a context, like this:

var presenter = container.Resolve<IBlogPresenter>();

then, every required dependency (including the NH session manager) is resolved within the same context, all of this without even making any component aware of the existence of such grouping.

It is all handled by the container, which is exactly what I was looking for.

Sample Project

I’ve put together a small spike to illustrate these concepts. Maybe a more complex application would be more suitable to present some things, but for now this is all I’ve done.

The sample solution uses NHibernate, Windsor, NH facility, ATM (automatic transaction management) and a simple WPF UI using Caliburn’s Action support.

If you’re using SQL Server Express you just need to create an empty DB called “test”, otherwise just modify the settings in App.config to suit your needs. The tables and initial data are created by the application at startup.

You can download the sample here.

Improvements

One obvious thing that is left out here is the capability to resolve more than one root component for a given context (two repositories in two different presenters that get the same ISessionManager) but that is something that could be added with no problem.

There are probably a lot of scenarios where the approach described here does not apply… I’ve just implemented a solution to my problem that works well for me and I think that maybe someone else can benefit from this.

I would like to know what do you think about this approach.

Reporting Services + LocalReport hang

Just for future reference…

Winforms application + Reporting Services + LocalReport + bad luck = Application hangs without throwing any exception :(

I’ve just spend a lot of time trying to figure out what the hell was causing this issue.
It happened when I did this:

localReport.LoadReportDefinition(stream)
localReport.GetDataSourceNames()  // here it hangs 2 of 3 times

I’ve managed to get the data source names from the stream reading some XML but then it hung at another point where the report was referenced again… agrhh!

Researching a bit more and using Reflector a lot I’ve found out that the issue might have something to do with the report definition being compiled in another application domain the first time that it is required.

All in all, I’ve solved this issue by changing the threading model of my application from STA (single-threaded apartment) to MTA (multithreaded apartment) by changing this:

[STAThread]
public static void Main()
{
   ...
}

to this:

[MTAThread]
public static void Main()
{
   ...
}

Perhaps this can save somebody some time.

Keep in touch

Categories