Friday, June 19, 2009

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.

Submit this story to DotNetKicks

Wednesday, April 29, 2009

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/

Submit this story to DotNetKicks

Monday, March 23, 2009

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.

Submit this story to DotNetKicks

Monday, March 9, 2009

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.

Submit this story to DotNetKicks

Thursday, February 12, 2009

Contextual data using NHibernate filters

I'm in the middle of the development process of an application using NH for data access, and I'm faced with a requirement that could be stated as follows:
The application needs to provide support for different Contexts of execution, and certain entities must be context-aware, which means that at a given time, the application only sees instances of these entities that correspond to the current context of execution.
Now, just remember that I have several entities defined that are used throught the entire application layer stack, so I wanted to solve this issue modifying as little as possible.

I'm very proud with the solution that I came up with, and also very amazed by the power of NHibernate.

To simplify a little lets assume that I have a static class that defines the current context of execution:
public enum ContexType
{
ContextA,
ContextB,
}
public static class Context
{
public static ContextType Current { get; set; }
}
Then, I create an interface that will be implemented by all the entities that need to be contextualized:
public interface IContextAware
{
ContextType Context { get; set; }
}
Given a Cat class that needs to be contextualized, then I add the property to the class and to the mapping:
public class Cat : Entity, IContextAware
{
...
ContextType Context { get; set; }
...
}

<class name="Cat">
...
<property name="Context">
...
</class>
The idea now, is to use the dynamic filtering capabilities of NHibernate to only retrieve the Cats instances corresponding with the current context every time that a query against Cat is issued.
Typically this means that I need to add a filter definition to the mappings and the specify the condition for that filter in every class mapping that need to be aware of this behavior.
But there is an easier way to do this automatically:
var filterParametersType = new Dictionary<string, IType>(1);
filterParametersType.Add("current", NHibernateUtil.Enum(typeof(ContextType)));
cfg.AddFilterDefinition(new FilterDefinition("contextFilter", ":current = Context", filterParametersType));

foreach (var mapping in cfg.ClassMappings)
{
if (typeof(IContextAware).IsAssignableFrom(mapping.MappedClass))
{
mapping.AddFilter("contextFilter", ":current = Context");
}
}
Just do this (cfg is the NH Configuration object) before building the session factory and it creates the correct filter definition and adds the condition to every entity mapped that implements IContextAware.

At this point we just have our filter defined; now we need to enable it in order to actually filter something. It would be very handy if we can enable filtering at session factory scope, but since the session factory is immutable we need to enable it for each session that we will be using.

Wait.... maybe something else can do this work for us...

The following interceptor actually takes care of 2 things:
1. enables the context filter as soon as it is attached to the session, and
2. assigns the correct value to the Context property of entities implementing IContextAware when they are persisted.
public class ContextInterceptor : EmptyInterceptor
{
public override void SetSession(ISession session)
{
session.EnableFilter("contextFilter").SetParameter("current", Context.Current);
}

public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
{
var contextAware = entity as IContextAware;
if (contextAware != null)
{
int index = Array.Find(propertyNames, 0, x => x.Equals("Context"));
state[index] = contextAware.Context = Context.Current;
return true;
}
return false;
}
}
Every session in the application needs to be created specifying this interceptor, but this should be an easy change (that depends on your architecture) if you are doing things right.

And thats all, the rest of the application is untouched and the requirement is fulfilled in a very elegant way.

Submit this story to DotNetKicks

Wednesday, January 7, 2009

Line count in Visual Studio

This is a nice trick that should be spreaded.

Select Edit -> Find & Replace -> Find in files... or just press CTRL+SHIFT+F

Check Use and select Regular expressions.

Type the following as the text to find:

C#
^~(:Wh@//.+)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@/#).+
VB.NET (thanks Steve for the info!)
^~(:Wh@'.+)~(:Wh@/#).+

Select where you want to do the search/count: file, project or solution.

If you select Current project or Entire solution, you also need to specify the file types that will be included in the search.


Proceed with the "search" and at the bottom of the Find results window you will see the total line count.


The regular expression that is used match every line that are not a comment (//), a compiler directive (starts with #), a single opening or closing brace, or blank lines.

Note:
This post is based on this one from Philip Stears (the regex in the original post does not work correctly).

Submit this story to DotNetKicks

Tuesday, December 23, 2008

Polymorphic query using interfaces

Given an object model defined by the following classes/interfaces:

public class Animal

public interface IHasFourLegs

public interface ICanFly

public class Dog : Animal, IHasFourLegs

public class Bird : Animal, ICanFly

public class Unicorn : Animal, IHasFourLegs, ICanFly

Suppose that you want to persist this class hierarchy to a database and be able to easily retrieve all the entities that implement one of both interfaces... then NHibernate is your friend (as always)

I've chosen to map this using the table-per-subclass strategy, but probably the other inheritance mapping strategies would work as well:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Assembly"
namespace="Namespace">

<
class name="Animal">
<
id>...
<property>...
</class>

<
joined-subclass name="Dog" extends="Animal">
<
key>...
<property>...
</joined-subclass>

<
joined-subclass name="Bird" extends="Animal">
<
key>...
<property>...
</joined-subclass>

<
joined-subclass name="Unicorn" extends="Animal">
<
key>...
<property>...
</joined-subclass>

</
hibernate-mapping>
Now that we have our classes and their mappings we are going to query our domain to get all the entities that implement ICanFly.

Basically you have 2 options right now: Criteria API and HQL.


Using Criteria API

This is very simple, all you need to do is this:
var flyers = session.CreateCriteria(typeof (ICanFly)).List<ICanFly>();


Using HQL

This one gets a little trickier (at least it got for me) since you need to explicitly import the interface type inside the mapping to get NH to know about it; this is simply done by adding the following line to your mapping:
<import class="Namespace.ICanFly" rename="ICanFly"/>
After this little addition we can issue a successful HQL query:
var flyers = session.CreateQuery("from ICanFly").List<ICanFly>();


Remarks

  • The import mapping needed when using HQL seems to be used by NH to map the string used in the query (ICanFly) to an actual type... if you'd have put rename="Flyers" in the import element then the HQL would need to be "from Flyers".
  • At first, I thought that specifying the full name of the type directly in the HQL string would have been enough, but it is not.
  • Take special care when trying to retrieve an ordered result set because since NH should issue several SELECT statements to get all the entities from the different tables (instead of using an UNION) the order of the results will probably be wrong.


Conclusion

This polymorphic behavior of NHibernate is just awesome because it allows you to be creative with your domain and frees you of the constraints imposed by the underlying relational model.

Submit this story to DotNetKicks