Unit testing your data access layer with SQLite and NHibernate

After too much reasearch I finally got this up and running, so I thought I would share some of the paint with you.

I started up with this article (http://ayende.com/Blog/archive/2006/10/14/UnitTest ingWithNHibernateActiveRecord.aspx) explaing how to do unit testing with NHibernate and in memory SQLite. My first problem was "installing" SQLite on my computer. After some research I found out the only thing you have to do is to add this dll to your project (http://sqlite.phxsoftware.com/). It includes both SQLite and the .NET 2.0 ADO provider.

After some configuration I finally got the example from ayende.com up and running. You should think this was it. But it wasn't. Trying to add multiple items to the database and then query them failed. It took me alot of googeling and debugging to finally figure out that NHibernate actually kills my connection when I call session.flush(). This causes the entire in-memory database to reset to nothing.

I now tried to figure out how to configure NHIbernate so that it does not reset my connection on flush. I finally figured it out (http://ayende.com/Blog/archive/2007/01/06/Note ChangesInNHibernateConnectionProvider.aspx).  You need to set "connection.release_mode" to "on_close".

FINALLY ! I have the test code up and running.

I have included a stripped version of my project with all the required configuration and dll's to get this up and running:

SqliteNHibernate.zip (1.58 mb)


Posted by: bjartn
Posted on: 10/12/2008 at 6:12 AM
Tags: ,
Categories: Projects
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Reasons why Script# (ScriptSharp) won't build

Sometimes Script# projects gives you a "build failed" message without giving you any reasons. Don't know if there is any way to produce some error messages. Anyway, here are some things that can cause this little problem:
  • You have added refrences to other dll's than the Script# dll's: Fix: Remove the refrences. (PS: This happens if you select "Add class" and do not select Script# as the project type)
  • You have defined a auto property. Fix: Use .NET 1.1 syntax for properties
Have you felt it in any other way, send me a message ;)

Posted by: bjartn
Posted on: 9/4/2008 at 8:03 AM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

JQuery for Script#

Update: I have created a new project on codeplex has all this stuff and some more: JquerySharp

Old blog post


Posted by: bjartn
Posted on: 8/14/2008 at 5:55 AM
Tags: , , ,
Categories: Projects
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

Validating forms in MVC Part

Update: Of course all this is not so exciting now that the preview 5 of MVC framework has been releasted.. Just read about it at "The Gu" and you get the picture.

This stuff is probably implemented somewhere in the ASP.Net MVC framework, but I couldn't resist the challenge. The goal is to make some code that automatically populates my POCO object with values from the submitted form. In addition I need to do some validation on the posted values. The goal is to get this done with a realtive small amount of code. In my examples I have used a simple Student object and a form where the id's of the controls matches the property names in my object. The student object looks like this:

public class Student
{
    public DateTime DateOfBirth{ get;set;}
    public int Height{get;set;} 
    public string Name { get; set; }
}

After some fiddeling back and forth I ended up with a ValidationHelper object that is responsible for populating the student object and doing validation. I also made a little extention method to the controller. This is how to use the extention method and the ValidationHelper object:

 //SETTING: User has submitted a form with some keys 
 //   mathcing the properties in the Student object
 //   and we are now in the controller: 
 //   apply some rules to the student object and 
 //   get a ValidationHelper object
 ValidationHelper vh= this.Request( 
        s => s.DateOfBirth < DateTime.Now,                    
        s => s.Height<240,     
        s => s.Name== "Bjarte" ||  s.Name== "Rambo"); 

if (vh.Validates()){      
    //if the request variables validates    
    //get populated student object and return view    
    Student s = vh.GetPoco();    
    return View("FormOk",s);}
else{ 
    //create list or error messages    
    List errors  = new List();    

    //Use vh.GetFailedRules() and vh.GetFailedConversions() to find out why the validaiton failed      
    //and create appropriate error messages    
    //[code goes here]   
    //finally return error message        
    return View("Form", errors);
}

If the validation fails I have implemented some methods to determine which rules caused the validation to fail. The validation will also fail if the format of the string does not match the type of the property in the POCO object. You might be wondering about the implementation and of the ValidationHelper object and the extention method to the Controller. You'll find the code in the files.

I've added a test project inculding all the files I have used: Download

I got the inspiration for this article from Seth


Posted by: bjartn
Posted on: 8/12/2008 at 8:16 AM
Tags: ,
Categories: Projects
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Custom resource provider

I recently found this article about implementing a custom resource provider

http://msdn2.microsoft.com/en-us/library/aa905797.aspx#exaspnet20rpm_topic2

I have used the database version for one of my projects and found one error when using this project on a top level domain. In the file DBResourceProviderFactory.cs the code below will not work if the application is not in a subfolder like so: mydomain.com/subfolder

classKey = virtualPath.Remove(0, virtualPath.IndexOf('/') + 1);

So to get the code working properly you need to do some kind of fix. I just made a quick workaround and will not post it here :p 

I also created some code to copy resources from the .resx files to the database. The code assumes you are using  LINQ  to connect to the database and you have created the table StringResources from the MSDN example. You probably have to do some minor changes to get this working. Just run the code once in your web application. Well well. I have attached the file.

 

CopyResources.zip (1.54 kb)


Posted by: bjartn
Posted on: 4/27/2008 at 2:26 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

This error message is just annoying

Funny error message:

ScriptManager.GetCurrent(Page) The type 'System.Web.UI.ScriptManager' exists in both 'System.Web.Extensions.dll' and 'System.Web.Extensions.dll' 

Could you be more spesific please? Yell

 -Well.. I figured it out. It seems I had commeted out to many sections in the web.config file.. Well well.. I won't do that again.

Note to self: This error occurs if the application pool isn't cleared out. Typically when you omit the PrecompiledApp.config

Posted by: bjartn
Posted on: 2/19/2008 at 8:36 AM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

BDN.ServerControls.Thumbnail

I just created a server control on CodePlex. It inherits from the asp:Image control. It takes the image found at the property ImageUrl and converts it to a thumbnail and saves it to the disk. Then it returns the thumbnail.

To use it:

1) Put the runtime binary in the bin folder of your asp.net application.

2) Register it in web.config (or in the page if you feel like doint it that way)

<pages>
  <controls>
   <add tagPrefix="bdn" assembly="BDN.ServerControls" namespace="BDN.ServerControls"/>
   ....
  </controls>
</pages>

3) Add it to the page:

<bdn:Thumbnail
  ImageUrl="MyBigImage.jpg"
  Height="100"
  Width="150"
  ThumbHeight="100"
  ThumbWidth="150"
  ThumbFolder="~/Uploads/Thumbs"
  ErrorImage="~/Images/Spacer.gif"
  runat="server"
  ID="tb"
/>

You can find the source code and binaries at codeplex.

 http://www.codeplex.com/Thumbnail

 


Posted by: bjartn
Posted on: 2/9/2008 at 9:23 AM
Categories: Projects
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Server controls and javascript libraries

When developing ASP.net server controls with some small javascript requirements you sometimes need a javascript library to avoid the hassle of browser compability. Of course you could set up the ASP.net AJAX framework. The problem with this approach is

  • too much overhead
  • extra configuration is needed to set up the framework

These two solutions works for me 

I have found both the files for your conveinience:

Once you have settled for a client framework you can add the file content to the page by following the steps:

  1. add the file to the server control project
  2. select the properties for the file and set the build action to be a embedded resource
  3. add the contents of the file to the client by using the following code
[code:c#]
protected override void OnPreRender(EventArgs e)
{
   ///...
  string _sJsBlock = " <script type="\"text/javascript\""> {0}</script> ";
  Page.ClientScript.RegisterClientScriptBlock(
    typeof(string),
    "Prototype",
    String.Format(_sJsBlock,GetResource("Prototype.js")
  )
  );
  ///...
}
[/code]

Helper method 

[code:c#]
///<summary>Get resource by fileName</summary>
public string GetResource(string filename) {
   System.Reflection.Assembly asm =
      System.Reflection.Assembly.GetExecutingAssembly();
   string val = "";
   System.IO.Stream strm =
      asm.GetManifestResourceStream(asm.GetName().Name + "." + filename);
   reader = new System.IO.StreamReader(strm);
   val = reader.ReadToEnd();
   reader.Close();
   return val;
}
[/code]


Posted by: bjartn
Posted on: 1/16/2008 at 7:39 AM
Tags: , , ,
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Gluttony theme for BlogEngine

I just found the gluttony theme for BlogEngine. I like it, and I am currently using it in my blog. The funny thing is that the theme is called gluttony and my blog is called superbia. Both beeing deadly sins. But don't let that scare you. I'm actually a nice guy Innocent


Posted by: bjartn
Posted on: 1/16/2008 at 7:06 AM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (4) | Post RSSRSS comment feed

Silverlight selection rectangle

My Silverlight skills are improving and I have now created a Silverlight selection rectangle. You can use this in your application to select stuff. The code is located in the RectangleSelect.js file. I have added a example website, so you can see how to use it. If you don't want to look at the sample website here is basically how:

Set up a load handler in the xaml file:

[code:xml]
<Canvas ... Loaded="load">
[/code]

Implement it:

[code:js]
function load(sender,args){
  //create rectangle
  var oSelect = new SelectRectangle();
  //initialize the rectangle with the root element in the xaml file
  oSelect.initRectangle(sender.getHost().content.root);
  //handle selected event
  oSelect.addSelected(onSelected);
}
[/code]

Pick up the onSelected event after the user has selected something in the canvas:

[code:js]
function onSelected(posRect){ 
   alert("Width: " + posRect.width
    + ", height: " + posRect.height 
    + ", x:" + posRect.x
    + ", y: " + posRect.y);
}
[/code]

You can even enable/disable the selection by using

[code:js]
oSelect.enabled = true;
oSelect.enabled = false;
[/code]

The current code is actually a selection square, and not a rectangle. I just forgot to implement it. Converting the code to a selection rectangle and not a square can easily be done by replacing a single line of code. But I'll leave that up to you ;)

Sample web site (28.68 kb)


Posted by: bjartn
Posted on: 12/21/2007 at 5:02 AM
Tags:
Categories: Projects
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed