Creating .In and .NotIn extension methods for NHibernate 3 Linq provider

In Bringing the IN clause from SQL to C# I have shown how to create extension methods for C# that mimic the “in” clause from SQL. I like these methods a lot, but they cannot be used in Linq to NHibernate queries, because it cannot interpret them by default. Luckily, it’s not that hard to extend NHibernate’s Linq provider behavior. Fabio Maulo has already blogged about the extension points here NHibernate LINQ provider extension, so I’m just going to jump straight into the code.
Read more of this post

Attaching to Telerik MVC Grid’s client event using jQuery

Telerik MVC Grid component offers a way to subscribe to client side events by using ClientEvents method in your views. You can see the examples here: http://demos.telerik.com/aspnet-mvc/grid/clientsideevents. It works fine, but sometimes you’d like to use jQuery to subscribe to these events more dynamically. An example of that might be a global error handler for all grids.

Although I couldn’t find a snippet on the web that does it, it turned out to be very easy. Just use the standard bind() method that jQuery offers, something like this:

$(function () {
    $('.t-grid').bind('error', function(e) {
        if (e.textStatus == 'error') {
            alert(e.XMLHttpRequest.responseText);
            e.preventDefault();
        }
    });
})

This event handler will show an error message if something went wrong during grid’s ajax call. Since this piece of code runs whenever the page loads it attaches to every grid (Telerik MVC Grids have t-grid CSS class applied) on the page. That way, we can change the behavior of the components more flexibly. As for the exact event names, it seems they’re the same as the methods you use in views, just without ‘On’ and starting lowercase, like ‘OnError’ -> ‘error’.

ASP.NET MVC localization using ActionFilter

Action filters in ASP.NET MVC provide a great way to apply custom behavior to selected controller actions. They let you execute code before or after the actual action has been executed. That reminds of Aspect Oriented Programming and can be used to apply cross cutting concerns to controllers.

One of the things that first seemed reasonable to apply using action filters was localization. An action filter that sets current thread’s culture before an action is invoked might look like this:

public class LocalizationCacheFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en");
    }
}

When you apply this action filter to your actions, the culture is set before the action, causing any code that is run later, including the action, to use the given culture. Easy and nice, however, there’s a small problem.

It seems that model binding happens before action filters are excuted, so that means that model binder will have no idea about a custom culture. That means that any validation that will be made on the model will produce validation error messages for the default culture, not the one you will set in the action filter. JavaScript validation will, however, produce the correct localized error messages, because JavaScript error messages are created at view’s render time and embedded in the output HTML. At that time, the action filter has already have been executed.

This issue caused me some head-scratching. The fix is to set custom culture earlier, in HttpApplication‘s BeginRequest event handler, for example.

Logging NHibernate queries with parameters

NHibernate lets you log the SQL statements it constructs using log4net. I’m not going to explain how to do it, because it is already well explained. It gives you flexibility on where you want to log: console, text file, xml file etc. The output that you get looks something like this:

12:33:54,464 DEBUG SQL:56 - 
SELECT
    count(CategoryId) 
FROM
    ProductCategories 
WHERE
    ProductId=@p0;
 @p0 = 65536 [Type: Int32 (0)]

Notice, that the query contains parameter name, not value – values are listed on the bottom.

Sometimes you want to run this query using a tool other than NHibernate, Sql Server Management Studio, for example. Then you’ll have to copy the appropriate parameter values and replace it in a query. Doing it by hand is a waste of time, so I wrote a custom log4net appender, that does it for us. Here’s the source code:

public class NHAppender: ForwardingAppender
{
	protected override void Append(LoggingEvent loggingEvent)
	{
		var loggingEventData = loggingEvent.GetLoggingEventData();

		if(loggingEventData.Message.Contains("@p"))
		{
			StringBuilder messageBuilder = new StringBuilder();

			string message = loggingEventData.Message;
			var queries = Regex.Split(message, @"command\s\d+:");

			foreach (var query in queries)
				messageBuilder.Append(ReplaceQueryParametersWithValues(query));

			loggingEventData.Message = messageBuilder.ToString();
		}

		base.Append(new LoggingEvent(loggingEventData));
	}

	private static string ReplaceQueryParametersWithValues(string query)
	{
		return Regex.Replace(query, @"@p\d(?=[,);\s])(?!\s*=)", match =>
		{
			Regex parameterValueRegex = new Regex(string.Format(@".*{0}\s*=\s*(.*?)\s*[\[].*", match));
			return parameterValueRegex.Match(query).Groups[1].ToString();
		});
	}
}

What I’ve done here, is derive from a ForwardingAppender, that let’s you transform the output logged and forward it to another appender. The NHAppender replaces the parameter names in query (@p0, @p1 and so on) with appropriate values, taking batch commands into account (notice the usage of Regex.Split).

You can use this appender to forward fully executable SQL queries to the console like this in your configuration:

<appender name="NHAppender" type="NHibernatePlayground.Custom.NHAppender, NHibernatePlayground">
	<appender-ref ref="console" />
</appender>

<root>
	<appender-ref ref="NHAppender" />
</root>

This way, you can copy the queries from console output and execute it immediately.

Using MVC Mini Profiler as a Http Module

MVC Mini Profiler is a great tool to profile your ASP.NET MVC apps. It’s easy to setup: all you need is to render some includes in your page’s HTML and start/stop the profiler on BeginRequest/EndRequest event handlers, as desribed here.

However, I did not want to include that code and HTML includes in production pages, so I wrote a Http Module that you can switch on/off easily in your application’s web.config file. Here’s the code:

public class MiniProfilerHttpModule: IHttpModule
{
	public void Init(HttpApplication context)
	{
		context.BeginRequest += delegate
		{
			if (context.Request.IsLocal)
			{
				context.Response.Filter = new MiniProfilerFilterStream(context.Response.Filter);
				MiniProfiler.Start();
			}
		};

		context.EndRequest += delegate
		{
			MiniProfiler.Stop();
		};
	}

	public void Dispose()
	{
	}
}

That’s easy, the more interesting part is the MiniProfilerFilterStream class. It acts as a filter to all the response HTML that is returned to the browser. All it does is search for the end of head tag and insert the output of MvcMiniProfiler.MiniProfiler.RenderIncludes() method just before it. Here’s the source code of the class:

public class MiniProfilerFilterStream: Stream
{
	private readonly Stream stream;
	private bool profilerHtmlRendered;

	public MiniProfilerFilterStream(Stream stream)
	{
		this.stream = stream;
	}

	public override void Flush()
	{
		stream.Flush();
	}

	public override long Seek(long offset, SeekOrigin origin)
	{
		return stream.Seek(offset, origin);
	}

	public override void SetLength(long value)
	{
		stream.SetLength(value);
	}

	public override int Read(byte[] buffer, int offset, int count)
	{
		return stream.Read(buffer, offset, count);
	}

	public override void Write(byte[] buffer, int offset, int count)
	{
		if (!profilerHtmlRendered)
		{
			var responseText = Encoding.UTF8.GetString(buffer, offset, count);

			if (responseText.Contains("</head>"))
			{
				var miniProfilerHtml = MiniProfiler.RenderIncludes().ToHtmlString();
				int index = responseText.IndexOf("</head>");
				var newOutput = responseText.Insert(index, miniProfilerHtml);
				var newBytes = Encoding.UTF8.GetBytes(newOutput);

				stream.Write(newBytes, 0, newBytes.Length);
				profilerHtmlRendered = true;
				return;
			}
		}

		stream.Write(buffer, offset, count);
	}

	public override bool CanRead
	{
		get { return stream.CanRead; }
	}

	public override bool CanSeek
	{
		get { return stream.CanSeek; }
	}

	public override bool CanWrite
	{
		get { return stream.CanWrite; }
	}

	public override long Length
	{
		get { return stream.Length; }
	}

	public override long Position
	{
		get { return stream.Position; }
		set { stream.Position = value; }
	}
}

The magic happens in Write method, others just act as a proxy to the original stream.

Switching MVC Mini Profiler on in your application is now as easy as adding the Http Module to the web.config:

<system.web>
	<httpModules>
		<add name="MiniProfiler" type="Management.Web.Infrastructure.Monitoring.MiniProfilerHttpModule"/>
	</httpModules>
</system.web>

Telerik MVC Grid ActionLink column

The problem

Working with Telerik MVC Grid component, I ran into an issue where I wanted to add a column with an “Open” link. Clicking that link takes you to item’s editing form. It seems, however, that there’s no method to render a link columns by default.

You can achieve it, however, using template columns, something like this:

columns.Template(
	@<text>
		@Html.ActionLink("Open", "Edit", new { controller = "Items", id = item.ItemId })
	</text>
).ClientTemplate(@"<a href=""/Items/Edit?id=<#= ItemId #>"">Open</a>")

Note, that if you’re using AJAX binding in your grid, you have to specify a client template, that will be used by JavaScript. That template must be a constant string, but you can get bound item property values inserted in the template using ‘<#= PropertyName #>’ syntax.

It’s not very clean, however, because you have to supply two different templates to get the same HTML. It can lead you to stupid bugs if the generated HTML differs for server side and client side binding. That’s why I decided to write an extension method.
Read more of this post

Mapping custom lists with Fluent NHibernate

NHibernate supports mapping to a few collection types by default, like IList of ISet, but they must be interfaces. To support other types of collections, including concrete classes, you should implement IUserCollectionType inteface. Being lazy as I am, however, I found a way to map custom collections as components using Fluent NHibernate. Here’s how it looks like:

Component(x => x.ChildUsers,
					  m => m.HasMany<User>(Reveal.Member<BindingList<User>>("innerList")).KeyColumn("parent_user_id").Access.Field());

The custom collection in this case is BindingList(T), a generic implementation of IBindingList interface for my own use. The trick is that it has to have a innerList field of any supported NHibernate collection type.

There are other variations of such mappings on the net, but other didn’t work for me with SQLite, throwing exceptions about generated DDL for tables.

Software that works

Last Sunday I finally had a decent programming session working on a tool that I use for my own purposes. Such sessions became pretty rare for me, because at work I’m mostly dealing with bug fixing, so I spend most of the day debugging and reading code.

So the tool I was working on is an old project of mine – a plugin container application that has no user interface apart from a context menu that you get after right clicking the system tray icon and an options form:
desktools
The thing is that sometimes I need to write some small application for my own use, but I don’t ever start it, mostly because I’m too lazy to create a user interface for it. For example, I needed a small app once to switch between different MAC addresses for my network card. I didn’t write it, because of the user interface part. Writing user interfaces is boring. That’s why I decided to go with plugin approach and a very minimalistic UI.

Anyways, that was like two years ago and I had the first version of the app ready in a day. It was great and working, but things got worse as I learned about different programming patterns, architectures, principles of OOP and similar things. Yes, it’s a great knowledge, so I ended up rewriting my application to make it decoupled. The levels of abstraction increased and increased and increased… and I dropped it. A simple application has became over-architectured and impossible to implement new features to.

What was once a simple working tool now became a pile of interfaces and half-finished implementations that did not work. So I decided to revive it again and what I did was remove some unnecessary abstractions and doing things in the easiest possible way. This saved me tons of thinking and what’s more important – my tool was working again. I even implemented new features into it easily within minutes.

So the lesson learned is: you can have the smartest architecture in the world, but it doesn’t matter at all if the application is not working.

Yes, I still try to follow all the principles and good practices, but it’s obvious that sometimes you need to be pragmatic and choose working software over ‘good’ design. Especially in pet-projects :)

Avoiding useless checks

All of us are trying to write code that is safe. It’s not uncommon to come across something like that:

var accountRepository = GetAccountRepository();
if(accountRepository != null)
{
	var account = accountRepository.Get("username");
	if(account != null)
	{
		if(account.Roles != null && account.Roles.Contains("Admin"))
		{
			if(logger != null)
				logger.WriteLine("User is an administrator");
			Console.Write("User is in administrator role");
		}
	}
}

All is well, but wouldn’t it be cleaner if there weren’t so many checks for null? Something like this:
var accountRepository = GetAccountRepository();
if(accountRepository.Contains("username"))
{
	var account = accountRepository.Get("username");
	if(account.Roles.Contains("Admin"))
	{
		logger.WriteLine("User is an administrator");
		Console.Write("User is in administrator role");
	}
}

We’ve removed three checks for null and reduced the level of indentation by two. Not much, but still makes the code cleaner. But how do we ensure that we don’t get a NullReferenceException in the refactored piece of code?
Read more of this post

Bringing the IN clause from SQL to C#

Since I have to work with T-SQL (MS SQL Server SQL dialect) a lot, I tend to miss the IN clause in C# sometimes. Checking if a value is equal to a list of possible values in SQL is quite elegant:

IF(1 IN(1,2,3))
	PRINT '1 is in the list'

That’s not the case in C#, where the above example would traditionally be reqritten like this:
if(1 == 1 || 1 == 2 || 1 == 3)
	Console.WriteLine("1 is in the list");

Read more of this post

Follow

Get every new post delivered to your Inbox.