Sunday, September 19, 2010

NHibernate

This article is about using the OR-Mapper NHibernate which is mapping a data representation from an object model to a relational data model in a .NET-environment. The article contains the main steps to get started with NHibernate by a short example-project. It is the first part of a planned series of NHibernate-tutorials.

Getting started

First of all you need to download NHibernate from

www.sourceforge.net/nibernate

In the example I used Nhibernate 1.0.4. After unzipping you will find the Assemblies NHibernate.dll and log4net.dll. These you'll have to reference in your VS-Project. In our example we will create an ASP.NET-Application with C# in VS 2005 and MSSql-Server 2000.

After creating the Project/WebSite and referencing the Assemblies mentioned above, the configuration-part will follow.



Configuration

In this step you have to tell NHibernate where to find your datastore and which kind of database you use. Add the configuration to your Web.config-File like in this sample configuration for MSSql2000-Server. In the connect_string-property add your database and hostname.



name="nhibernate"
type="System.Configuration.NameValueSectionHandler, System,
Version=1.0.5000.0,Culture=neutral,
PublicKeyToken=b77a5c561934e089" />



value="NHibernate.Connection.DriverConnectionProvider"
/>
value="NHibernate.Dialect.MsSql2000Dialect"
/>
value="NHibernate.Driver.SqlClientDriver"
/>
value="User ID=sa;Password=admin;Data Source=MyServer;Initial Catalog=MyDB"/>





To access the database with NHibernate we need an NHibernate-Session-object. In an ASP.NET-application we want one session per Request. How can this be achieved? ASP.NET offers a nice feature for this: IHttpModules. You have to implement the interface IHttpModule to use the methods BeginRequest and EndRequest. In the beginning of a request you open the session and when the request ends you close it:


public class NHibernateHttpModule : IHttpModule
{
public const string KEY = "_TheSession_";
private static ISession _session;

private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
context.Items[KEY] = SessionHelper.OpenSession();
}







private void context_EndRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;

ISession session = context.Items[KEY] as ISession;
if (session != null)
{
try
{
session.Flush();
session.Close();
}
catch {}
}
context.Items[KEY] = null;
}

public static ISession CurrentSession
{
get
{
if (HttpContext.Current == null)
{
if (_session != null)
return _session;

_session = SessionHelper.OpenSession();
return _session;
}
else
{
HttpContext currentContext = HttpContext.Current;
ISession session = currentContext.Items[KEY] as ISession;
if (session == null)
{
session = SessionHelper.OpenSession();
currentContext.Items[KEY] = session;
}
return session;
}
}
}
}





The class SessionHelper is an own implementation you can find in the attached project. You can use the class NHibernateHttpModule to obtain your session object which you need to create queries or run inserts, updates or deletes in the database. Examples on how to do this will be shown later in this article.




What's the mapping...?

NHibernate maps between .NET-Classes (Objects) and relational data (Database-Tables). These mappings are defined in XML-Documents.
Add a new dll for your domain-objects to the solution and name it NHibernateASPSample.Domain. After that add an XML-File to this project and name it like {MyTableName}.hbm.xml. In the example we will use the file DbUser.hbm.xml that maps to a class and Db-table named DbUser.
Note: In the properties for the file set the Build action to Embedded resource:





namespace="NHibernateASPSample.Domain"
assembly="NHibernateASPSample.Domain">















The class DbUser that corresponds to that declaration looks like this:




namespace NHibernateASPSample.Domain
{
///
/// Class that holds the data of the table DbUser
///

public class DbUser
{
#region Members

private int _idUser;
private string _login;
private string _password;
private string _userData;

#endregion

///
/// A standard-constructor is needed!
///

public DbUser()
{
}

public int IdUser
{
get { return _idUser; }
set { _idUser = value; }
}

public string Login
{
get { return _login; }
set { _login = value; }
}

public string Password
{
get { return _password; }
set { _password = value; }
}

public string UserData
{
get { return _userData; }
set { _userData = value; }
}
}
}


The properties in your class have to match the properties you defined in your configuration.

Monday, September 6, 2010

ASP.NET MVC

The ASP.NET MVC Framework is a web application framework that implements the model-view-controller pattern. Based on ASP.NET, it allows software developers to build a Web application as a composition of three roles: Model, View and Controller. A model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the application. A controller handles interactions and updates the model to reflect a change in state of the application, and then passes information to the view. A view accepts necessary information from the controller and renders a user interface to display that.

In April 2009, the ASP.NET MVC source code was released under the Microsoft Public License

The ASP.NET MVC Framework couples the models, views, and controllers using interface-based contracts, thereby allowing each component to be easily tested independently.