NHibernate in Dec MSDN

Published 12/7/2009 by Dave in alt.net | Database

Ayende never ceases to amaze me, I just wonder where he finds the free time (must be cloning). Anyway, he has written a simple TODO list article which uses

  • Object Relational Mapper
  • Presenter View View-Model
  • Number of Design Patterns

By the looks of this, Ayende has tried to use a minimal number of 3rd party tools, to try and show principals.

Well worth a look!

(Thank you Ayende)

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Active Record

Published 4/23/2009 by Dave in alt.net | Database

if you are writing any data layer code in .Net, please have a look at this presentation by Ayende

Oredev 2008 - ALT.NET - Using Active Record to write less code

its an hour long, but it can save you lots of time

Active Record is built ontop of NHibernate, and its free... wahey for open source

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Here are some links for developer Joe, whom wants to get started in NHibernate.

Sites

Official site: Contains great reference material, read the Quick guide too.

Community: Wiki, Blogs and downloads. become a member today, and start adding to the KB.

Video Training, (Big thanks to Unhandled Exception) Excellent, 14 videos to get you started.

Fluent Nhibernate - write code instead of XML for your mapping files.

Tools

http://www.nconstruct.com/ - NConstruct Lite is free, so give it a go, Generate you classes and mapping files from your DB.

NH Prof - a Profiler, yep see what is going on, well worth your time!

Articles, publications:

Best Practices (has a basic example and then a Enterprise example), aimed at version 1.2, however extremely good. I like this as you have the sample project layout.

The foundations of programming ebook mentioned previously in this post. As it covers NHibernate and other patterns you will most likely use with it. Fantastic read.

 

If any one knows of any good material please add a comment linking to it. 

 

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Quick info

Very quick guide, ORM stands for Object Relational Mapper, its a tool which takes the data from a database and populates this data into Business Objects.. Nice and simple... basically using an ORM should save you as a coder from having to write the Data Access Layer code. (I'm not saying this is the best way to do things, that boils down to what you need to do.) For this code example i will be using WilsonORM there is a free download which will allow you to create a debug only project (other than that you have to pay a one off charge).

Back to the sample code.

1.Table

Lets start with the database, I will use one that came with this blog (a little change from northwind, I may do it with step 2).

CategoryId = GUID
CategoryName = Varchar(50)

I will only concentrate on this single table (keep it simple)

2. .Net Code

Now we will have to create a console application which will be extremely simple, it will contain the business object class for the above table, and a simple script which will list all the Categories in this table.

  1. Create a new console project all this "TestOfORM"
  2. Add a reference to the WilsonORMapper.dll (I'm using the .net 2 version, but the 1.1 will do)
  3. Now add a BO sub folder in your project.

Now lets review what is required to get this to work:

  • Corresponding Business Object Class
  • Manager Class, basically is use to initiate the Object Space
  • Mapping File (contains meta data of how the table relates to the Business Object Class)
  • Actual Application code.

3. The Business Object Class

This class will be used to store the information for an instance of data in the table. Here is what my Class will look like

Things to note, you need a parameterless constructor, also there is s field which will relate to the columns in the table.

4. Manager Class

This will create an instance of the ORM manger (object Space), this will be used in your app code to load data from the database.

using System;
using Wilson.ORMapper;

namespace TestOfORM
{
    sealed public class Manager
 {
  private static ObjectSpace engine;

  public static ObjectSpace Engine {
   get { return Manager.engine; }
  }

  static Manager() {
   string mappingFile = AppDomain.CurrentDomain.BaseDirectory
                + "Mappings.xml";
   string connectString = @"Server=.\sqlexpress;DataBase=theBlogDB;UID=user;PWD=passsword;";
   string providerType = "MsSql";

   Provider provider;
   try { provider = (Provider) System.Enum.Parse(typeof(Provider), providerType, true); }
   catch { provider = Provider.MsSql; }

   // Note: Non-Zero Session may be desirable for Server Applications
   engine = new ObjectSpace(mappingFile, connectString, provider);
  }

  private Manager() {
   // Note: Static Class -- All Members are Static
  }
 }
}

this code i just copied off Wilson's site, and changed the mappingFile and connectionString varibles.. now you are almost there.

5. Mapping file

This file will contain all the entity mappings, the easiest way to build this file is to copy one off a sample which comes with the OEM and change it to your requirements. One cool thing is Paul Wilson included the .XSD file, so you can set this to validate your shema.

<?xml version="1.0" encoding="utf-8" ?>
<mappings version="4.2">
  <entity type ="TestOfORM.BO.be_Categories" table ="be_Categories" keyMember ="_CategoryID" keyType="Auto">
    <attribute  field ="CategoryID" member ="_CategoryID" alias ="CategoryID" />
    <attribute field ="CategoryName" member ="_CategoryName" alias ="CategoryName"/>
  </entity>
</mappings>

as you can see there is only 1 entity, with 2 attributes.. this is mapping the be_Categories table to the  be_Categories class, things to notes:

  • keyType - is how the Primary key is generated
  • KeyMember - is the tables primary key

6. Your App Code

finally you can code your app, it may seem like a lot of work, but the larger the project the more likely you would find this faster to code, plus some of the you can generate using tools

class Program
{
    static void Main(string[] args)
    {
        ObjectSet allCat = Manager.Engine.GetObjectSet(typeof (be_Categories), string.Empty);
       
        foreach (object o in allCat)
        {
            be_Categories cat = (be_Categories) o;
            Console.WriteLine(cat.CategoryName );
        }
        Console.ReadLine();
    }
}

as you can see I call the managers get all of that type, which returns an ObjectSet, then i just list all the entries. Nice and simple. The following screen shot shows the final layout of my project:

and here is the result for my test DB

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

It can be helpful to know how and what ports your application connects to the MS SQL server. Ok maybe not, but i was in a pickle and needed to find this information out. What I was looking for was all the connections I had open to a SQL server from a certain connection pool. I came up with the following script...

Declare  @dave_sp_who3 table
(
    SPID INT,
    [Status] VARCHAR(100) NULL,
    [Login] SYSNAME NULL,
    HostName SYSNAME NULL,
    BlkBy SYSNAME NULL,
    DBName SYSNAME NULL,
    Command VARCHAR(100) NULL,
    CPUTime INT NULL,
    DiskIO INT NULL,
    LastBatch VARCHAR(100) NULL,
    ProgramName VARCHAR(100) NULL,
    SPID2 INT,
      RequestID int
)
 
INSERT @dave_sp_who3 EXEC sp_who2
 
SELECT distinct * --client_tcp_port, local_tcp_port
FROM sys.dm_exec_connections
WHERE session_id in (
      SELECT SPID FROM @dave_sp_who3
    WHERE [Login] = 'loginName')
 order by client_tcp_port

Replcace the login name with the user ID or the connection ID, and this will now list all open connections you have and will show how they are connected. IE

You can glem the following great information

Connection type: [Named Pipes, TCP, Shared Memory]
IP address of the Client
TCP port number of both the client and SQL server

 How does this script work?

 I use the sp_who2, to list all the active connections, which is inturn stored in a temp table  (@dave_sp_who3 table). This table is filtered on the application pool im interested with and used with the sys.dm_exec_connections to gain the rest of the information.

 nice and simple :)

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5