Author Archives: David Rankin

About David Rankin

Originating from Zimbabwe, I have finally landed up in Wales, (next door to England). I moved to the UK to pursue studies, as I could not afford to study in South Africa. I was working on the mines out in the bush, and quickly began to realise the importance of computers. On the mines I started learning everything I could about computers, and got my first computer when I was 19, it was a Pentium 166Mhz with MMX. Since then I have had a variety of jobs, from cleaning chicken farms to teaching. Right now I’m in the crazy uncertain world of Start ups. Hope to make something big (and good) happen.

3 Easy steps to scanning files for viruses in MVC (and for free)

Well it’s been a while since I wrote something here, but now I came across something useful and worth sharing. In a few projects I work on, users upload content to share online. Now while we have virus scanners running, they only scan files saved on disk. I needed to figure out a better way of keeping my system virus free, and not write dangerous files to disk, to check if its dangerous!

After a scan on Google, I really struggled to find a good (complete) example for my needs. So I thought I’d share how I got a solution set up which may be helpful for a few others who are trying to do the same thing.(And also help remind me how I did it in a few months’ time.)

Step 1 Install ClamAv

Clam AV logo

Firstly, you need to download and install clamAv. You can get a copy from here and follow the step by step instructions below:

  1. Extract or install ClamAV, I have put mine in d:\clamAV
  2. Create a directory “db” for the virus definitions etc.
  3. Start command prompt as administrator and run freshclam, this will start the ClamAV update process
  4. Run clamd –install to set up clamAV as a service.
  5. Start this ClamAV service (called ClamWin Free Antivirus Scanner Service) and also set it up to automatically start when your system starts up

 Step 2 – Create your test cases and classes

I find it a lot easier to start by creating some basic unit tests, and then work on integrating the bits I need to later on. I have included some snippets from my github project here, just to give an overview of the main areas. In our test cases, we will use a VirusScannerFactory to give us an implementation of IScanViruses. I think the most useful objects to scan are memory streams, byte arrays and files. I have created the interface for this below.

  1. /// Interface for us to implement for each Virus scanner
  2. public interface IScanViruses {
  3.  
  4.     /// Scans a file for a virus
  5.     ScanResult ScanFile(string fullPath);
  6.  
  7.     /// Scans some bytes for a virus
  8.     ScanResult ScanBytes(byte[] bytes);
  9.  
  10.     /// Scans a stream for a virus
  11.     ScanResult ScanStream(Stream stream);
  12. }

In MVC the HttpPostedFileBase is used to represent the uploaded file. We will pass the HttpPostedFileBase.InputStream to our IScanViruses.ScanStream Method to make sure the stream is virus free. So in the example test cases, we will pass a clean string and read this into a memory stream. This can then be scanned for viruses. We also use the EICAR test string to make sure our virus scanner implementation works correctly too!

  1. /// Test scanning a memory stream, typically what we get from a MVC http file base
  2. [TestCase("Here is another nice clean string to scan for viruses", true)]
  3. [TestCase(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*", false)]
  4. public void Can_scan_memory_stream_for_virus(string stringData, bool expectedToBeVirusFree) {
  5.     var stream = new MemoryStream(Encoding.ASCII.GetBytes(stringData));
  6.     var scanner = VirusScannerFactory.GetVirusScanner();
  7.     var result = scanner.ScanStream(stream);
  8.     Assert.That(result.IsVirusFree, Is.EqualTo(expectedToBeVirusFree), result.Message);
  9. }

We now need to implement the IScanViruses using ClamAV. For this we will use nClam. You can install it from nuget. This little library gives us access to ClamClient which wraps ClamAv functionality in a neat little API. Our ClamAvScanner class can then be used to scan for viruses.

  1. /// Implmemntation of Clam AV to scan viruses
  2. public class ClamAvScanner : IScanViruses {
  3.  
  4.     /// Scans a file for viruses
  5.     public ScanResult ScanFile(string pathToFile) {
  6.         var clam = new ClamClient("localhost", 3310);
  7.         return MapScanResult(clam.ScanFileOnServer(pathToFile));
  8.     }
  9.  
  10.     /// Scans some bytes for virus
  11.     public ScanResult ScanBytes(byte[] data) {
  12.         var clam = new ClamClient("localhost", 3310);
  13.         return MapScanResult(clam.SendAndScanFile(data));
  14.     }
  15.  
  16.     /// Scans your data stream for virus
  17.     public ScanResult ScanStream(Stream stream) {
  18.         var clam = new ClamClient("localhost", 3310);
  19.         return MapScanResult(clam.SendAndScanFile(stream));
  20.     }
  21.  
  22.     /// helper method to map scan result
  23.     private ScanResult MapScanResult(ClamScanResult scanResult) {
  24.         var result = new ScanResult();
  25.         switch (scanResult.Result) {
  26.             case ClamScanResults.Unknown:
  27.                 result.Message = "Could not scan file";
  28.                 result.IsVirusFree = false;
  29.                 break;
  30.            case ClamScanResults.Clean:
  31.                 result.Message = "No Virus found";
  32.                 result.IsVirusFree = true;
  33.                 break;
  34.            case ClamScanResults.VirusDetected:
  35.                 result.Message = "Virus found: " + scanResult.InfectedFiles.First().VirusName;
  36.                 result.IsVirusFree = false;
  37.                 break;
  38.            case ClamScanResults.Error:
  39.                 result.Message = string.Format("VIRUS SCAN ERROR! {0}", scanResult.RawResult);
  40.                 result.IsVirusFree = false;
  41.                 break;
  42.           }
  43.        return result;
  44.     }
  45. }

Step 3 – Integrating it with MVC

Now that we have got some test cases passing, we can look at how we hook this up into our MVC Application. In this example, we have a simple page that allows users to upload a file. In the [HttpPost] Index method, we expect a HttpPostedFileBase parameter which we will pass directly to our Virus scanner. The result of the scan is then stored in temp data, so the user knows if it is virus free.

  1. /// Main controller
  2. public class HomeController : Controller {
  3.  
  4.     /// Get the upload view
  5.     [HttpGet]
  6.     public ActionResult Index() {
  7.         return View();
  8.     }
  9.  
  10.     /// Handle the file upload
  11.     [HttpPost]
  12.     public ActionResult Index(UploadViewModel model, HttpPostedFileBase file) {
  13.         var scanner = VirusScannerFactory.GetVirusScanner();
  14.         var result = scanner.ScanStream(file.InputStream);
  15.         ViewBag.Message = result.Message;
  16.         return View(model);
  17.     }
  18. }

It’s quite tricky to test this on a real virus. I have used the test EICAR virus file, which is probably a safe way to test it out. A more robust solution may be to try it out some real viruses. This is another post on its own!
Here are some tips for a solution like this:

  1. Make sure that you have a scheduled task to keep ClamAV up to date
  2. Just in case, have a second virus scanner, that scans your uploads directory for viruses every now and then
  3.  more tips to come…

A full copy of this project can be found on Github.

A special thanks to:
Ryan Hoffman, with some of this code influenced by his examples
The guys at ClamAV for their great work and keeping the software up to date

 

Cardiff NHS hack day or (weekend) and Bcon.cc

I have finally got a little time to sit down and talk about my experience of the NHS hack day in Cardiff last month, organised by Anne Marie Cunningham. Hack days are brilliant for putting Developers, Designers and Domain Experts together in one space to come up with solutions to solve real world problems.

I initially had a few ideas I wanted to work on, but my family encouraged me to go with an idea we had come up with over Christmas.

My brother-in-law had told us an horrific story of how he and his friends  had found an unconscious mountain biker in the Welsh valleys, somewhere near Cwmcarn. Even though my brother-in-law is a doctor, he still had problems. He had no idea who this person was or if he had any pre-existing medical conditions. He did not know exactly where they were and that’s also why  the ambulance services took a while to find them.

Ambulance services arrived with Gas and Air

Picture of the mountain biker who suffered a few serious injuries

After hearing this story, I knew there must be a way that technology can make these situations easier. I thought of my skiing jacket, which has a RFID chip to help locate me if I ever get stuck under deep snow in an avalanche. Why don’t we do something similar for mountain bikers, cyclists or even motorcyclists? This is when the idea for a QR sticker containing basic medical details was born.

Well, the NHS hack day seemed like the perfect place to pitch this idea. I first posted a question on the forum to get some feedback from the group, which was very encouraging.

On the day, I think that David Miller was surprised to see so many people have ideas they wanted to pitch, and after hearing some of these ideas, I was already thinking of which  team I could join to try make some really cool stuff!

My one minute pitch went well, with some practice and help beforehand. I got a little team together, which is what is great about these hack days! You have really motivated dynamic team of experts who are able to apply their knowledge and make amazing things happen. We created our solution, called bcon.cc, then worked on designs and  the system process flow, trying to get the user experience right. We then set about acquiring user feedback and applying our expert knowledge. Unfortunately I was the only developer in my team, so I did have quite a lot of work to do. I must admit, I did not get to bed that night until midnight, and I was also up really early on Sunday morning hacking away, bug fixing and configuring servers and getting the system to work.

Team Bcon in action

Team Bcon Hard at Work – Alan, Steve, Alistar, Claude, RobynDavid(me) and Ben

When it came to the last day, we were determined to have a functional product, and after overcoming some technical difficulties with DNS servers overly optimistic caching, things started going smoother. After our two minute Bcon presentation and a nervous live demonstration, we were delighted to hear we had won best for improving patients’ lives! What a surprising result for such a simple idea. Let me also mention the other inspiring ideas that were turned into reality, many of which will have a positive impact on people’s lives today.

bcon logoAfter our success at the NHS hack day, we started to develop Bcon.cc into a fully functional product, which will soon allow you to get high quality stickers online. We have been working closely with a few local businesses, and have also been getting help from the great community at the techhub, thanks Ben, Matt, Tim, Steve and Adam. You can follow bcon on twitter which will keep you up to date. We have also been regularly updating our website, https://www.bcon.cc, and are planning a significant update next week.

ASP.Net MVC, Fluent Validation and testing

I am finally coming to the end of a project, and I thought it would be good to write a little post on how we have managed to set up our fluent validation for our MVC project. In the start we did some research into how to go about performing validation, and found a number of recommendations. But all involved using data annotations. In this post, I will show you how I set up fluent validation, to work smoothly with my MVC 2 project. I create a custom model binder to validate view models and show how to validate a registration using fluent validation. Finally I show how to unit test the validation rules I needed for registration.

To start with, there are some problems I have with data annotations

1 – Too many annotations make your model s look ugly. Take this example .

public class Product {

      public int Id { get ; set ; }


      [Required]
      [StringLength(10)]
      public string Name { get; set; }

      [Required]
      public string Description { get; set; }

      [DisplayName("Price")]
      [Required]
      [RegularExpression(@"^$?d+(.(d{2}))?$")]
      public decimal UnitPrice { get; set; }
     }

Now wouldn’t it be nice to have your model/entity just look like this.

public class Product
{
      public int Id { get; set; }
      public string Name { get; set; }
      public string Description { get; set; }
      public decimal UnitPrice { get;set; }
}

2 – Complex data validation with attributes makes your code get even more ugly. Take a lot at this example showing how to achieve slightly more complexity with data annotations. Now trying to reuse and share attributes seem to make things more and more complex….

3- I think there may be a performance issue, as we need to extract the validation attributes using reflection. Now, while these are simple models, with simple validation rules, we may not notice the performance degrading, but I am sure that with numerous complex attributes, things might run a little slow. (I need to prove this though – maybe when I get time, I will write some tests – I could be wrong here, things might change in MVC 3)

So after looking at some examples, such as xVal –dead now, Entity validation with visitors and extension methods these all did the job, but I would need to write lots of helpers, what I needed was some kind of framework for validation. Then I found fluent validation.

Linking MVC with Fluent Validation

So let us look at how we set our MVC project . Firstly, I want to automate the validation, so that any errors are automically added to the models state. With some help from Jeremy I set up an customised BindAndValidate attribute. Here is a simplified attribute we started with.

    1     public class BindAndValidateAttribute : CustomModelBinderAttributeIModelBinder {

    2         AttributedValidatorFactory validatorFactory = new AttributedValidatorFactory();

    3 

    4         public override IModelBinder GetBinder() {

    5             return this;

    6         }

    7 

    8         public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

    9 

   10             var innerBinder = new DefaultModelBinder();

   11             var boundInstance = innerBinder.BindModel(controllerContext, bindingContext);

   12             if (boundInstance != null)

   13                 ValidateInstance(boundInstance, bindingContext);

   14 

   15             return boundInstance;

   16         }

   17 

   18         void ValidateInstance(object instance, ModelBindingContext context) {

   19             var validator = validatorFactory.GetValidator(context.ModelType);

   20             if (validator != null)

   21             {

   22                 var result = validator.Validate(instance);

   23                 result.AddToModelState(context.ModelState, "");

   24             }

   25         }

   26     }

Now all I need to do is hook this up with my controller method. In the Sign in method, I add the attribute [BindAndValidatiate] and all I need to do is check that the model state is valid. If so, I perform the log in.

    1     public class AccountController : BaseController {

    2         public ActionResult Signin() {

    3             return View();

    4         }

    5 

    6         [HttpPost]

    7         public ActionResult Signin([BindAndValidate] ChangeEmailModel model) {

    8 

    9             if (ModelState.IsValid)

   10                 PerformSignIn();

   11 

   12             return View();

   13         }

   14     }

Linking MVC View Models with Fluent Validation

Lets look at how all this works. What we need to do is create out model, then create our validator. We then hook our validator to our model by adding the validator atrribute to our model. I am using a simple Register View Model here as an example.

    1     [Validator(typeof(RegisterViewModelValidator))]

    2     public class RegisterViewModel

    3     {

    4         public string Email { get; set; }

    5         public string Password { get; set; }

    6         public string ConfirmPassword { get; set; }

    7     }

Now for the model validator. Here we have some simple rules. The password must not be empty, and it must also be a good password. The password confirmation must be the same as the password, and finally the Email must be a valid email address, and also not already exisit in our site.

    1     public class RegisterViewModelValidator : AbstractValidator<RegisterViewModel> {

    2         public RegisterViewModelValidator() {

    3             RuleFor(reg => reg.Password)

    4                     .NotEmpty()

    5                     .WithMessage("Please provide a password")

    6                     .Must(BeGoodPassword)

    7                     .WithMessage("Password must be at least 8 characters long, and contain numbers and letters");

    8 

    9             RuleFor(reg => reg.ConfirmPassword)

   10                     .Equal(reg => reg.Password)

   11                     .WithMessage("Passwords do not match");

   12 

   13             RuleFor(reg => reg.Email)

   14                    .EmailAddress()

   15                    .WithMessage("Invalid Email")

   16                    .Must(BeUniqueEmail)

   17                    .WithMessage("Account already Registered");

   18         }

   19 

   20         public bool BeGoodPassword(string password) {

   21             Regex regex = new Regex(@"^(?=.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).*");

   22             return regex.IsMatch(password);

   23         }

   24 

   25         public bool BeUniqueEmail(string email) {

   26             int count = Repository.GetInstance().CountOccurrencesOfEmail(email);

   27             return (count == 0);

   28         }

   29     }

Test your validation

Now, finally for the testing, whcih is really useful, when I want to make sure that things work 100%! To keep it simepl, I am just going to test the password rule, because testing the email requires a lot more of an explination. So working from some simple examples Here: I have written three tests. Thfirst is to make sure that the password can not be null. The second is to catch a week password. The third makes sure that a strong password does not cause an error.

    1         [Test]

    2         public void Should_have_error_when_Password_is_null() {

    3             validator.ShouldHaveValidationErrorFor(reg => reg.Password, null as string);

    4         }

    5 

    6         [Test]

    7         public void Should_have_error_when_Password_is_weak() {

    8             validator.ShouldHaveValidationErrorFor(reg => reg.Password, "weakpass");

    9         }

   10 

   11         [Test]

   12         public void Should_not_have_error_when_Password_is_strong() {

   13             Validator.ShouldNotHaveValidationErrorFor(reg => reg.Password, "SecretPassword123");

   14         }

And that is it! There is quite a lot you can achieve with fluent validation, such as reusing validators on complex properties and also some useful conditions like when or unless! The reasons I like this are that it uses generics to help build clean code. There is now no need to attributes on every property I have. Also, Jeremy was also very quick to help with any questions I had. Thanks for the help Jeremy.

Nhibernate returns duplicate results on paged data sets – work around

Recently, while implementing a page-able data grid with nHibernate and MVC Contrib Grid, I came across a strange problem. My result set had duplicates, and the strange thing was that it would only happen when paging my record set. Anyway, I thought I would write a little post about how I solved the problem, just in case someone else comes across it.

Firstly, lets look at simplified description of the problem. Those using MySQL have the luxury of limit, which makes paging data sets a breeze, but in SQL Server(and Oracle) things get a bit more “tricky”. The trick is to count the rows on the result set, using RowCount over something, and mix that in with a sub query, but there is a problem with nHibernate T-SQL 2005 Dialect. The RowCount was being used on the sub-query, and not the parent query. Now that I had discovered the problem.

“ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP) as __hibernate_sort_row” is in the wrong place!

After some research, I found that other people were having this problem too. Marcin Daczkowski has an excellent work-around, that he blogged about, he also describes the problem with some NH generated SQL examples, I won’t repeat myself here, so have a look at his post if you are not sure and check his bug report here.

I found a another solution here too- not sure this one works though, ultimately I had to come up with a solution that suited my project.

There are some reasons why I can’t use Marcin Daczkowski solution.

– Firstly, it does not look like the guys at nHibernate be able to release the patched version of nHibernate any time soon,I guess they are very busy working hard on version 3.0! Can’t wait for that realease! see the comments here.

– Secondly, if I build my own version of nHibernate, I will need to also rebuild all my dependencies, linking them with Marcins patched version. That means FluentNHibernate needs to be rebuilt, NHibernate.Caches.SysCache needs to be rebuilt, NHibernate.ByteCode.Castle needs to be rebuilt, you get the picture?

So after some thought and source code investigation, I came up with the idea of making a customised Dialect, and just use Darcins patched files. Now, I don’t need to build a patched version of my all my open source dependencies, as I have my own SQL dialect set up in the fluent configuration.


_sessionFactory = Fluently.Configure()
      .Database(MsSqlConfiguration
      .MsSql2008
      .ConnectionString(connectionString)
      .CurrentSessionContext("web")
      .Dialect(CustomSQL2008Dialect)
)

My Dialect classes are set up like this:


public class CustomSQL2008Dialect: CustomSQL2005Dialect {
      public GWMsSql2008Dialect () {
            // Duplicate of the contents of MsSsql2008Dialect constructor goes here
      }
}

public class CustomSQL2005Dialect: MsSql2000Dialect {
      // the contents Darcins MsSql2005Dialect file goes here.
      // MsSql2005Dialect at NHibernate JIRA

}

Luckily, I have unit tests set up for all my repository methods, and after seeing the green bar in NUnit, I was more than satisfied with the custom dialect. I hope the guys at NHibernate manage to get things working in their next release, keep up the good work guys! And a special thanks to
to Darcin, for writing the patch.

Here is a copy the Custom Sql 2008 Dialect.

Role Based Access Control in ASP.Net MVC

Currently I am looking at access control systems, and how best to integrate them with ASP.Net MVC framework. While this framework already provides support for role based access control (RBAC), using the membership classes. I need to implement this on a legacy database, and some how integrate the old system with asp.net forms authentication. This post is about how I realised this, and acts a potential solution. If you can think of a better way, of find any devastating flaws, let me know. ;-)

The scenario is simple, we have four roles defined for the system. They are Students, Graduates, Staff and Administrators. Some staff can be graduates, (or even Students). Administrators are, of course staff! So how you model this? We already know of one bitwise trick from Michal’s post, so let us see how we can use bitwise operations to make this a reality!

First let us revise the results of the bitwise AND operations. You can check Wikipedia for full details.

1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
1 & 1 = 1

Converting these back to decimal 1001 is 9 and 0101 is 5. So 9 & 5 = 8. If we convert each of these bits to represent a role in our system, we can come up with a table like this.

Bit 1 0 (false) Student
Bit 2 0 (false) Graduate
Bit 3 0 (false) Staff
Bit 4 1 (true) Admin

So a user of the system with a role number of 8 is an Admin, but in our case, an Admin is also a member of staff, and in fact, a member of staff could also be a student or a graduate. This is where using bitwise operations can really help model such a situation. To get it working, a staff member who is a student will have bits 1 and 3 set to true, while a graduate who is also a staff member will have bits 2 and 3 set to true. We can represent these roles in decimal as User(Staff & Graduate) = 6, while User (Staff & Student) = 5. Get the picture?

Let’s look at a simple real world example. First we have a User class, with a Role property of the type int. The reason we use an integer, is that is can be easily stored in the database.

    1     public class User {

    2 

    3         public string Name { get; set; }

    4         public int Role { get; set; }

    5         public bool IsInRole(Role role) {

    6             //todo

    7             return false;

    8         }

    9     }

We also need to create an enumeration, with a Flags attribute. The flags attribute tells the compiler that this enumeration can be treated as a bit field. We then define a value for each role. The reason for using exponents of 2 should become clearer later.

    1     [Flags]

    2     public enum Role {

    3         Student = 1,    // 0001

    4         Employer = 2,   // 0010

    5         Staff = 4,      // 0100

    6         Admin = 8       // 1000

    7     }

The menu of our website needs to be generated depending on the user role. The menu selection code below should generate the correct menu depending on the user role.

    1     <div class="LeftMenu"> 

    2 

    3         <% if (user.IsInRole(Role.Student)) %>

    4             <% Html.RenderPartial("StudentMenu"); %>

    5 

    6         <% if (user.IsInRole(Role.Graduate)) %>

    7             <% Html.RenderPartial("GraduateMenu"); %>

    8 

    9         <% if (user.IsInRole(Role.Staff)) %>

   10             <% Html.RenderPartial("StaffMenu"); %>

   11 

   12         <% if (user.IsInRole(Role.Admin)) %>

   13             <% Html.RenderPartial("AdminMenu"); %>

   14 

   15     </div>

Ok, so let see where the magic happens! If we AND (&) the user assigned role, with the role required, and we compare this result to the role required, we can determine if a user is in the role. Summarised, the end result of the AND operation needs to equal that of the role required. In user class we have the method:

    1         public bool IsInRole(Role role) {

    2             Role userRole = (Role)this.Role;

    3             return ((userRole & role) == role);

    4         }

Looking at some binary examples, we can see how it works. In the first example, an admin user wants accesses a graduate item.

Role Required Staff(4) 0 1 0 0
User Role Admin (8) 1 0 0 0
Result of & Access Denied (0) 0 0 0 0


It is clear that we have a problem here, because we said that admin could be both staff, and staff may also be graduates. What we need to do is add up the roles, so that this user will access both admin and staff content. Assigning the user the role of Admin and Staff is easy. All we do is:

    1             User user = new User();

    2             user.Role = (int)Role.Staff;

    3             user.Role |= (int) Role.Admin;

And the resulting table is:

Role Required Staff(4) 0 1 0 0
User Role Admin + Staff (12) 1 1 0 0
Result of & Access Granted (4) 0 1 0 0

Now we can easily draw our menu depending on the roles assigned to a user. Adding or removing roles for a user is also easy, just add it or subtract it. I wrote a little project to go with this so you can test it our your self. Thanks to Michi for introducing this, and Dan for helping work it out!

Download the Roles sample project You’ll need to use nUnit to test it.

FluentNhibernate and Stored Procedures

I am evaluating FluentNHibernate (FNH), to see if it is suitable for a project I am working on. Disappointingly, FNH does not support Store procedures of the box. Of course, FNH is under the BSD licence, so I am sure those who are confident enough can implement this for the rest of us! This post will show how I got FNH to work with stored procedures, and can hopefully be followed as a working example.

FNH extends NHibernate, and automagically generates XML mapping files for your objects. Unfortunately, to get stored procedures to work, you need to take a step backwards, and create good old fashioned hbm.xml files, doing the mappings manually.

Firstly , let us look at the results of the stored procedure that we want to map.

ID enDescription cyDescription IsActive
1 Swansea Abertawe True
2 Cardiff Caerdydd True
3 Newport Cas Newydd False

The class that will use this data is called lookup.

The code for this class is:

    1 namespace Entities {

    2     public class Lookup  {

    3         public virtual int Id { get; set; }

    4         public virtual string EnDescription { get; set; }

    5         public virtual string CyDescription { get; set; }

    6         public virtual bool IsActive { get; set; }

    7     }

    8 }

 
This object will be used to populate a simple drop down list, so that a user can select their county.

When I started using FluentHNibernate, I wanted to totally avoid using XML mappings, so I skipped chapters 3 and 6 of Hibernate in Action. My first mistake! So for those attempting this, it may be worth your while understanding Hibernate mappings before you proceed. (You may also ask why I have the Java Book and my code is in C#, that is because I am quite used to working in different programming languages, so those who prefer examples in .Net examples check NHibernate in Action.)

Let’s move on to creating the mapping file.

IMPORTANT: When you add the mapping file to your project, make sure you set the Build Action to Embedded Resource!

I have created a Lookup.hbm.xml file, and the source is below:

    1 <?xml version="1.0" encoding="utf-8" ?>

    2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

    3                    namespace="Entities">

    4     <class name="Lookup" table="dbo.sp_GetLookups" >

    5         <id name="Id" column="Id">

    6             <generator class="native" />

    7         </id>

    8         <property name="EnDescription" column="enDescription" />

    9         <property name="CyDescription" column="cyDescription" />

   10         <property name="IsActive" column="IsActive" />

   11         <loader query-ref="dbo.sp_GetLookups"/>

   12     </class>

   13 

   14     <sql-query name="dbo.sp_GetLookups" >

   15         <return alias="dbo.sp_GetLookups" class="Lookup">

   16                 <return-property name="Id" column="Id"/>

   17                 <return-property name="EnDescription" column="enDescription"/>

   18                 <return-property name="CyDescription" column="cyDescription"/>

   19                 <return-property name="IsActive" column="IsActive"/>

   20         </return>

   21         exec dbo.sp_GetLookups

   22     </sql-query>

   23 </hibernate-mapping>

 

To put it quite simply, lines 5 to 13 map my Lookup class to the columns in the stored procedure, while lines 16 to 20 map the results from the stored procedure my lookup class. Line 22 names the stored procedure. I am not sure if this is the best way to achieve the mappings, so any feedback would be appreciated.

Once your object is nicely mapped, you then need to update your fluent configuration. All you need to do is tell FNH to load hbmMappings from the current assembly. See the snippet below:

   1    .Mappings(m => {

   2            m.HbmMappings.AddFromAssembly(Assembly.GetExecutingAssembly());

   3            m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());

   4     })

 

To retrieve the list of lookups, I do the following, which populates my results variable with a list of all my lookups.

    1    var sessionfactory = CreateSessionFactory();

    2    var session = sessionfactory.OpenSession();

    3    var results = session.GetNamedQuery("dbo.sp_GetLookups").List();

 

And that is it, the results variable now contains the list of lookups that I can use to populate my list control.