1. NH basic concepts part 1- Unit of Work and NHibernate Session

20 Dec

I will try and keep this short and I’ll start at a very high level in order to keep things very simple.

Concept: Unit of Work (UoW)

UoW is a general design pattern but rather than providing the generic (if I may say confusing) definition, I’ll just refer to the best definition I’ve come across for UoW as it relates to NH, which can be found here. I’ve reproduced the relevant content below:

Martin Fowler writes:

“When you’re pulling data in and out of a database, it’s important to keep track of what you’ve changed; otherwise, that data won’t be written back into the database. Similarly you have to insert new objects you create and remove any objects you delete.”

and

“A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work.”

In this definition of work, the term “business transaction” can seem a bit vague and before addressing what it means, one needs to understand how the UoW pattern is implemented in NH.

Concept: NH Session

The UoW pattern is implemented using an NH Session, which incidententally does not have anything to do with a web session. As explained here,

In NHibernate we have the Session object which is a Unit of Work (UoW) container.

In simplistic terms, to “implement” a UoW of work in NH, you

  1. “Open” an NH Session
  2. Do some business transaction
  3. “Close” the NH Session

In the next post, I’ll detail how to actually use the NH Session object and implement a basic UoW.



Tags: ,

Learning NHibernate

20 Dec

The past year has been very hectic and hence why this blog hasn’t been updated as much as I would have liked it to be. One of the things that I have had to learn is NHibernate and it certainly hasn’t been easy but hopefully now that I have a bit more free time, I hope to be able to contribute something back to anyone who might be starting out on this journey.

This post and the related series of posts, that I intend to write, will not be fully comprehensive but rather are useful notes for myself and hopefully others. Were I to start learning NHibernate today, here are the resources I’d tackle in the following order:

  • NHibernate in Action – This is really a loaded book and I have only been able to read upto chapter 7. Despite covering NHibernate 1.2, this book is a must in my opinion as it provides the foundations of NHibernate.
  • Summer of NHibernate – This is an excellent series of video tutorials on how to actually “use” NHibernate. Moreover, the source code that he uses in the tutorial is available for download.

My series on NHibernate will be based on the Summer of NHibernate series which only covers version 1.2. Since then there have been various changes and enhancements to NHibernate (NH) and effectively my series on NH will aim be to “rewrite” some of the code from these tutorials and use technologies such as Loquacious NH.

So here are the technologies and their versions that I’ll be basing my series upon:

  • NH 3.2 – This will include things such as Loquacious NH and the QueryOver API
  • NUnit – I am using this simply because I am more familiar with NUnit. Please note that this will NOT be following best practices of unit testing simply because the initial code wasn’t, from my understanding, following best practices.

The links to the tutorials in this series will appear below and if you would like to follow it then bookmark this page.

1. NH basic concepts part 1- Unit of Work and NHibernate Session

Tags: ,

Getting started with Castle Windsor tutorial – Part 1

21 Dec

This tutorial will show you how to set up Castler Windsor for a very simple project. I am basing this tutorial on the one that Simone Busoli wrote a few years ago.

Before proceeding, you should read his tutorial as he explains what Inversion of Control (IoC) means and why you should be using some form of IoC framework, of which Castle.Windsor is one. After you’ve grasped the concepts, come back to this tutorial which will walk you through how to update his sample project using the latest incarnation of Castle.Windsor (2.5.2).

Now that you understand what IoC is, and how Castle.Windsor can help you to use that design pattern, open up Simone Busoli’s sample project and reference the latest versions (2.5.2 as of this writing) of Castle.Core and Castle.Windsor.

Before delving into the code, I’d like to refer you to Castle Windsor’s documentation on “Using the container – how and where to call it“. It is important that you read this because I’ll be making use of “The Three Container Calls Pattern”, which really is not as complicated as it sounds.

The salient features of the three container calls pattern are:

  1. Register – This means telling Castle.Windsor the services and the respective components implementing these services.
  2. Resolve – i.e. specify the root service and Castle.Windsor will load all the related dependencies.
  3. Release – i.e. release the container.

Now to use Castle.Windsor there are in fact two other steps that need to be added to this pattern.

  1. Instantiate your IWindsor container
  2. Register
  3. Resolve
  4. “Execute” the actual code to do the work
  5. Release

In order to update Simone’s console application, replace the Program.Main method with the following:

————————————————-

public static void Main()
{
// 1. Instantiate the IWindsor container object
var container = new WindsorContainer();

// 2. Register the services and the respective components that implement them
container.Register(
Component.For( typeof( IHtmlTitleRetriever ) ).ImplementedBy( typeof(HtmlTitleRetriever) ) ,
Component.For( typeof( IFileDownloader ) ).ImplementedBy( typeof( HttpFileDownloader ) ),
Component.For( typeof( ITitleScraper ) ).ImplementedBy( typeof( StringParsingTitleScraper ) )
);

// 3. ”Resolve” the root service
var retriever = container.Resolve<IHtmlTitleRetriever>();

// 4. ”Execute” the actual code to do the work
Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));
Console.Read();

// 5. Release the container
container.Dispose();
}

————————————————-

I believe that the code is pretty much self explanatory but should there be any questions or comments, then please don’t hesitate to drop me a line. You can find the updated files here.

I hope that you will have found this tutorial useful and that you are now more confident in using Castle.Windsor. In the next post in this series, I’ll show you how to set up Castle.Windsor so that it can “automatically” register the classes.

Before ending this post, a big thanks to Simone Busoli, whose code I’ve “lifted” and adapted, Krzysztof Koźmic of Castle.Windsor for answering my questions and to Maikel Lehtveer for getting me over the line.

Tags:

Start writing MSpec specifications (tests) for ASP.NET MVC 2

11 Dec

This article is a follow up to my previous post and it will show you how to get started with writing MSpec specifications (tests) for ASP.NET MVC2.

  • Create the ASP.NET MVC 2 application. I’ve named the application MSpecMvcApplication and I made sure that it’s using the same .NET Framework version as my “Machine.Specifications.dll” was built against.
Create MVC 2 project

Create MVC 2 project menu

  • Upon clicking OK, you’ll be asked if you want to create a unit test project, to which you should answer “Yes”. Note that there will be some irrelevant dlls referenced but this is for a quick demo on how to get up and running with writing MSpec tests.
  • You should end up with two projects
  • Add the “Machine.Specifications.dll” to the references.
  • Open up “HomeControllerTest.cs” and replace the code with:
using Machine.Specifications;

namespace MSpecMvcApplication.Tests.Controllers
{
    [Subject("Home Page")]
    public class when_the_home_page_is_requested
    {
        It should_return_the_home_page;
    }

}
  • Build the solution and run the test as follows:

Run test using Resharper – Unit test – Run all tests from solution

  • If all goes well you should see:

  • This is not a “real” test, because there is no context or test condition. So a proper test would be something like:
using System.Web.Mvc;
using FakeItEasy;
using Machine.Specifications;
using Machine.Specifications.Mvc;
using MSpecMvcApplication.Controllers;
 
namespace MSpecMvcApplication.Tests.Controllers
{
    [Subject(typeof(HomeController))]
    public class when_the_home_controller_is_told_to_display_the_default_view
    {
        //static string key;
        //static string message;
        static ActionResult result;
 
        static HomeController home_controller;
 
        Establish context = () =>
        {
            //key = "Message";
            //message = "Welcome to ASP.NET MVC!";
            home_controller = new HomeController
            {
                ControllerContext = A.Fake<ControllerContext>()
            };
        };
 
        Because of = () =>
        {
            result = home_controller.Index();
        };
 
        It should_return_the_home_view = () =>
            result.ShouldBeAView();
    }
}

In my next post I’ll try and explain what this code is doing but if you can run it, you’ll see

which is the result of a “real” test.

Tags: , ,

Running MSpec with Resharper

11 Dec

I have just started developing using Behaviour Driven Development and I thought I’d start a new post detailing how I went about doing it. There is in fact a similar titled post available here but it is a bit out of date. So here goes.

  • Get the source code from GitHub

I used GitExtensions to clone the source code from MSpec’s code repository. If you don’t know how to clone a repository, I believe that the GitExtensions site has video tutorials on how to do just that.

  • Generate the dll

There is no need to open the project in Visual Studio and compiling the project in order to get the dll. Instead, go to the folder where you cloned the code to and you will see the following 4 command files:

  • build-3.5-debug.cmd
  • build-3.5-release.cmd
  • build-4.0-debug.cmd
  • build-4.0-release.cmd

Simply run the version of what applies to you i.e. if you want to get the debug dll for .NET 4.0, then pick “build-4.0-debug.cmd”, which I’ve used for this example.

  • Set up Resharper

If all went well in the last step, you should see a bunch of files under “..\Build\Debug”

and in that folder, you’ll find the following files which are of interest to us:

  • InstallResharperRunner.5.0 – VS2008.bat
  • InstallResharperRunner.5.0 – VS2010.bat
  • InstallResharperRunner.5.1 – VS2008.bat
  • InstallResharperRunner.5.1 – VS2010.bat

Run the appropriate version and you should be good to start writing out some tests and running them using ReSharper. I will post another article on how to do just that.

Before ending this post, I’d just like to say that running the previous batch file isn’t always reliable probably due to file writing persmission issues. However, it’s simply a matter of opening the relevant batch file and understanding what it is doing and replicating the operations manually.

So for instance “InstallResharperRunner.5.1 – VS2010.bat” contains the following

mkdir “%APPDATA%\JetBrains\ReSharper\v5.1\vs10.0\Plugins”
copy Machine.Specifications.dll “%APPDATA%\JetBrains\ReSharper\v5.1\vs10.0\Plugins”
copy Machine.Specifications.pdb “%APPDATA%\JetBrains\ReSharper\v5.1\vs10.0\Plugins”
copy Machine.Specifications.ReSharperRunner.5.1.dll “%APPDATA%\JetBrains\ReSharper\v5.1\vs10.0\Plugins”
copy Machine.Specifications.ReSharperRunner.5.1.pdb “%APPDATA%\JetBrains\ReSharper\v5.1\vs10.0\Plugins”

which is simply saying:

create a folder within “%APPDATA%”

copy each of the files, Machine.Specifications.dll, Machine.Specifications.pdb, Machine.Specifications.ReSharperRunner.5.1.dll and Machine.Specifications.ReSharperRunner.5.1.pdb in the current folder, where the batch file is running, to the newly created folder.

Finally, if you can’t wait for the next post to see whether you’ve successfully set up Resharper to run with MSpec, then go to Byron Sommardahl’s blog post on just how to do that. This blog post contains a list of links which will help you get started with MSpec.

 

Tags: ,

Umbraco Content picker and what happens in the database

6 Aug

Using the Content picker to link two pieces of “content” is very easy to do in the Umbraco backend. However, what happens in the back-end, although not hard, will take you some time to figure out. Hopefully, this will save someone some time out there.

The scenario was this:

In the members section, we had a content picker which would link to a section in the content tree. What I had to do was to provide a database query on how to get the “Content” node id to which the member was linked given the loginName. Here is the query I came up with:

SELECT
 dataInt -- this is the "Content" node id
 FROM [someTable].[dbo].[cmsPropertyData] PD
 INNER JOIN cmsMember mb on PD.contentNodeId = mb.nodeId
 WHERE    LoginName = 'someLoginName'
 AND dataInt IS NOT NULL
 AND PD.propertyTypeId = the document type id of the "Content" node (see cmsPropertyType table)

In this case, we needed to get the associated content node ID given the LoginName. However, the cmsPropertyData would appear to be the linking table.

It’s not revolutionary but it’s simple when you know.

Tags:

Exception and exception handling C#

4 Aug

While studying at university, I inevitably came across the exception and exception handling but until recently, it never really made much sense. However, I now have a clearer idea on when to use it and when not to use it. Now for a definition of what an exception is.

Definition: An exception is an event, which occurs during
the execution of a program, that disrupts the normal flow
of the program's instructions.

With hindsight, this is an excellent definition but it can be hard to relate to when coming across this concept for the first time. A few of the questions that I should have asked myself then are:

  1. Why do I even need to know about exceptions?
  2. So what if an exception occurs?
  3. How do I even know that an exception has occured?
  4. What should I do when an exception occurs?

Yes I was indeed told that I needed to know about exceptions and exception handling (this will be explained further down) because then I would be able to terminate the application “gracefully”. However, as a novice back then, these were all pretty vacuous concepts and without a concrete example, exceptions can become very confusing and put developers off from using them and doings so in the correct manner.

The classic example given to illustrate an exception is the division by 0. This, in my opinion, is a good and bad example. It is a good example because we all know that the result of dividing a number by 0 is infinity and a computer is unable to process or even represent that. At the same time it is a bad example because further down the line, and after some reflection, we will find out that in most cases we can avoid this exception by ensuring that the divisor should not be zero before performing the division. So, it can become confusing because a great deal is made of exceptions but it would appear that in some circumstances and with sufficient thought, they can avoided. Hence, the next logical question is

Why do I even need to know about exceptions?

Even though the previous example of an exception illustrated that exceptions can be avoided if checks and data sanitisation are put into place, there are circumstances whereby no matter what safeguards are in place, exceptions might occur. This is in no way a sleight on your abilities as a developer but refer to exceptions such as trying to connect to an unavailable SQL server. Thus, exceptions are sometimes unavoidable. This brings us to the next questions.

So what if an exception occurs?How do I even know that an exception has occured?

These two questions are related and in the context of a web application, the yellow screen of death is the result of an exception occurring. As a developer, the YSOD should be avoided because

  1. It is not a nice user experience. The user will first of all be unable to do what he wanted to do and the YSOD techno babble is of no use to him. In this case, it is said that the application did not terminate gracefully.
  2. It could be a potential security risk, if this information is exposed, since it shows technical information which could be exploited.
  3. It decreases the end user’s faith in the application because to the end user it might indicate lack of QA.

Now that we know the consequences of an exception and why it is important to avoid it, the next question is:

What should I do when an exception occurs?

The answer to that of course is to deal with the result of an exception ,or in geek speak, we need to handle the exception. Each language has its way to that but in C#, the exception strategy is implemented through the use of the try/catch block e.g.

try
{
     //Code to perform some operation which could raise an exception
}
catch
{
     //Code to handle any exception that occurred in the try block
}

You would put code that might raise (fancy word for cause) exceptions in the try block. What happens behind the scenes, is that the runtime throws the exception and that exception is caught within the catch block. It is within the latter that the exception is handled i.e. dealt with. Before proceeding with exception handling and understanding the reasons behind handling an exception in a particular way, the concept of a call stack must first be explained.

Call stack

This page explains the concept of a call stack in detail but it can be explained better in terms of an example. Say you have three methods A, B and C. Within method A, there is a call to method B and within method B there is a call to method C. These three methods are dependent and built or stacked upon each other to form the call stack.

Now let’s say that there is exception handling initially implemented only in method C i.e. at the bottom of the call stack. The options for error handling are thus:

  • Within the catch block of method C, you can handle the exception and swallow it.
  • Within the catch block of method C, you can handle the exception but throw it up.

Swallow, throw up? What? Sometimes, I wonder why people come up with such terms? These make sense only after you gain more experience but can be terribly offputting while learning about exceptions for the first time. Swallowing in this context means that after an exception occurs in method C and execution is returned to method B, the latter will not know that an exception occurred in method C. On the other hand, if the exception is thrown up by method C, method B will be notified that an exception occurred in the former. At this point, method B can either handle and swallow the exception or throw it up to method A to handle the exception.

In practical terms, the following code will swallow the exception

try
{
     //Code to perform some operation
}
catch
{
     //Code to handle any exception that occurred in the try block
     // No throw statement
}

while the following with throw it

try
{
     //Code to perform some operation
}
catch
{
     //Code to handle any exception that occurred in the try block
     throw; // the throw keyword will pass or throw the exception to the calling method
}

Handling exceptions

Now, that the code execution is within the catch block, what are you, as a developer, going to do about about it i.e. how are you going to handle the exception? In the previous section we’ve talked about swallowing and re-throwing the exception but there are other steps that can be taken to determine if you should swallow or re-throw the exception.

First, try to see if you can deal with the exception right there and then, which from experience isn’t often the case and hence why I’m struggling to come up with a concrete example at the moment. In the rare cases that  you can deal with the exception then swallow it, otherwise re-throw it. However, in either case, you should log the exception and if possible provide notification to the developer of the exception so that the latter can take the appropriate measures. This is beyond the scope of this post but look into ELMAH and log4NET which serve somewhat different but sometimes overlapping functionality.

Conclusion

This was a brief introduction to the topic of exception and exception handling and there are plenty more resources out there but I hope that at least, this subject  is making more sense. Now to recapitulate:

  • Exceptions can occur and you have to have an exception handling strategy in place in order for the application to terminate gracefully.
  • Although it was maybe not emphasised enough, exception handling should be the last line of “defence”. In other words, you should first make the appropriate checks to ensure that the exception doesn’t occur in the first place e.g. ensure the divisor is not 0 in a division operation. Exceptions should occur only in exceptional circumstances.

Tags: ,

Follow

Get every new post delivered to your Inbox.