Archive for category NHibernate
NHibernate Validator 1.2 Beta3 released
Posted by Dario in NHibernate, NHibernate.Contrib, NHibernate.Validator on October 26th, 2009
NHibernate Validator 1.2 Beta2 released
Posted by Dario in NHibernate, NHibernate.Validator on October 10th, 2009

Download NHibernate Validator 1.2 beta2 with sources, binaries and example here here
For use it with NHibernate 2.1 GA.
Enjoy it !
NHibernate Validator Quickstart
Posted by Dario in Asp.Net MVC, NHibernate.Validator, Quickstart, Web on May 18th, 2009

The NHibernate Validator Team had prepared examples to you be able to use this validation framework in a easy way. With four examples we are covering the following topics:
1) Winforms
In this example you will how you can easily integrate NHibernate Validator and some helper clases with System.Windows.Forms.
2) NHibernate Integration
Trying to integrate NHibernate Validator with NHibernate? Not a problem. In this example you will how really get these 2 great frameworks working together. NHibernate Validator let you intercept Saves and Updates from NHibernate validating your entities before these changes take place. Note you have to create a database based on the configured connection string.
3) Asp.Net MVC
Asp.Net MVC has a cool way to add validation errors from model and display them all into the View. This example cover the easy integration between these frameworks. Note, you need Asp.Net MVC installed into your machine.Download Asp.net MVC
4) Entity Validator
Sometimes you need to validate a property which depends of another(s) property(ies). The most common example is when you have to validate a range of dates. This example cover this funcionality and show to us how to configurate it using attributes, xml and fluent.
Download it here
NHibernate Validator and Asp.Net MVC
Posted by Dario in Asp.Net MVC, NHibernate.Validator on April 2nd, 2009
Download the example here.
Asp.Net MVC has a cool way to add validation errors from the model and display them all into the View. It?s actually using the ModelState. As you may know NHibernate Validator (NHV) is a framework to validate entities, so what about if we let the validation to the framework that can manage it? So the integration of NHV to Asp.Net MVC is easy. I created a new Asp.Net MVC project and added some files to my solution to make they look like this: 
First I added the libraries needed to NHV (this libraries we need in case to use NHibernate too, otherwise you don?t need Linfu stuff to get proxies working). The libraries are:

Once the libraries are referenced, NHV need to be initialized, actually in this example that initialization will consist in a Validator Engine provider, capable to be accessed from everywhere into our web-application. A good point do this, is in the Global.asax. The next method InitializeValidator it?s called from the Application_Start.

Then I created a new View Manage.aspx, actually the view is a copy, with modifications, of Register.aspx View. Such View should looks like this one. As you may see, seems like there are some messages of validation, means, a validation that didn?t pass. Now let?s see the code to explore the minimal code to introduce NHibernate Validator as a Framework to Validate our MVC application.
First of all, our entity Customer, which reflex the view with a Name and a Email properties, should looks like this with the NHV attributes. Remember that NHV can be configured using Attributes (default), Xml or Fluent-Interfaces, and accept mix of configurations too.

Second, we need the integration point between NHibernate Validator and Asp.Net MVC, and that point consist just in a little piece of code that make the validation and modifies the current state of the model. We need just a few lines:

The picture shows an extension method which first of all, get a new ValidatorEngine instance, which is a singleton in whole web application. Actually, to use a ValidatorEngine we need just one instance, because NHV make a lot of useful caching and it configure itself in the way we are using it. Then we validate the entity and get all the InvalidValues of the object. If the entity is in invalid state (break one rule defined), NHV we well generate a InvalidValue array with all errors we should show to the user. Iterate through all the items and we add them all to the ModelState. Once we add one model error, the model is no longer valid.
Once we have our extension, let?s use it.

Validate Method is the extension we made before, and that method is going to modify the ModelState if it?s needed.
And that?s all folks, hope this helps.
NHibernate Validator 1.2 alpha3
Posted by Dario in NHibernate, NHibernate.Validator on March 30th, 2009

Download NHibernate Validator 1.2 alpha3 with sources and binaries here
This release demostrate to be very stable and is an update to use it with NHibernate 2.1alpha2. For those who have NH.Validator 1.2alpha1 this is a mandatory update.
Enjoy it !
New NHibernate and NHibernate Validator releases
Posted by Dario in NHibernate, NHibernate.Contrib, NHibernate.Validator on March 16th, 2009
- NHibernate 2.1 alpha1. See official release. Download.
- NHibernate.Validator 1.2 alpha1. See official release. Download.
Registering FREETEXT or CONTAINS functions into a NHibernate dialect
Posted by Dario in NHibernate on March 13th, 2009
Ms Sql Server FREETEXT and CONTAINS functions are used into FullText search capabilities to querying. These functions are of course natives to this particular RDBMS and even comes a with particular structure: they don?t return a value. So far, till NH 2.0, you couldn?t do it because a little parser issue, but from NHibernate 2.1 in forward you?re enable register them.
First of all, we define the new dialect with the new functions in order that when we run a query, NHibernate can recognize those functions and can transform to native-sql, in this case, Transact-SQL.
using NHibernate.Dialect; using NHibernate.Dialect.Function; namespace MyCompany.Data { public class MyDialect : MsSql2008Dialect { public MyDialect() { RegisterFunction("freetext", new StandardSQLFunction("freetext", null)); RegisterFunction("contains", new StandardSQLFunction("contains", null)); } } }
Note that we are using StandardSQLFunction, we can also use SQLFunctionTemplate or implement our ISQLFunction class with all the constraints (ie: parameter number accepted) we need.
Once our new dialect is ready let?s call it from our hibernate.cfg.xml file, then NHibernate can know that this dialect will be inject. Suppose MyDialect is placed into the assembly MyCompany.Data, so the configuration file should look like this:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory name="NH"> <property name="dialect">MyCompany.Data.MyDialect, MyCompany.Data</property> <property name="connection.connection_string"> Data Source=(local)\sqlexpress;Initial Catalog=test;Integrated Security = true </property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property> </session-factory> </hibernate-configuration>
Everything is ready, you just have to do this 2 steps and the functions are ready to use it, then we can query using them.
session.CreateQuery("from Documento where freetext(Texto,:keywords)") .SetString("keywords","hey apple car") .List();
Note the above query is HQL, so NHibernate knows about freetext and can operate with it.
NHibernate and Ms Sql Server 2008: Date, Time, DateTime2 and DateTimeOffset
Posted by Dario in NHibernate, Sql Server 2008 on March 12th, 2009
Ms Sql Server 2008 come with a lot of features talking about Date/Time. Besides the already known DbType.DateTime, now we have new types:
- Date
- Time
- DateTime2
- DateTimeOffset
NHibernate 2.1 introduce changes to support this types out-of-the-box. This table show all the details about how to configurate your system: classes, mappings:
|
CLR Type |
DbType |
Sql Server Type |
NHibernate type |
|
System.DateTime |
DateTime |
datetime |
datetime |
|
System.DateTime |
DateTime2 |
datetime2 |
datetime2 |
|
System.DateTime |
Date |
date |
date |
|
System.TimeSpan |
Time |
time |
TimeAsTimeSpan |
|
System.DateTime |
Time |
time |
time |
|
System.DateTimeOffset |
DateTimeOffset |
datetimeoffset |
datetimeoffset |
A breaking change was introduced: the old TimeSpan NHibernate type was moved to TimeSpanInt64 (it uses a System.Int64).
When we talk about ?NHibernate type?, we are refering to what you?ve to put into your mappings, i.e: <property name=?OnlineMeeting? type=?datetimeoffset?/> .
To use this features and more you?ve to use the dialect NHibernate.Dialect.MsSql2008Dialect.
The dialect changes include these types and changes to Hql functions that return the current system timestamp.
- current_timestamp: Now returns the current system timestamp as a DateTime2 value. It uses sysdatetime Sql Server function at background.
- current_timestamp_offset: New function!. Returns the current system timestamp with the offset as a DateTimeOffset value. It uses sysdatetimeoffset Sql Server function at background.
The idea of this post isn?t to explain every new type and what it can do, otherwise is to show you what have to do in your classes, queries or mappings to configure your date/time types with NHibernate. Besides, to know every detail of these types you can visit this useful .NET Framework Developer’s Guide.
Future<T> Queries with HQL and Criteria
Posted by Dario in NHibernate on January 29th, 2009
A few days ago Oren Eini and Davy Brion were working in a new feature for NH 2.1 (no a release yet) called Future, in the ICriteria API. You can see and explanation of the job here. Now I?ve committed a complement to enable that use into the IQuery API, for those who prefer to use HQL.
What is Future Query anyway? Future are queries that are kept, waiting to be executed as a group in just one roundtrip, making use of an underlying NHibernate feature: MultiCriteria/MultiQuery.
Let?s have a look to this simple piece of code. You can see both queries sentences, and both are executed in that sentence point against the database producing 2 roundtrips to the database. Nothing weird about this, but what if we can just execute the queries in just one roundtrip?
And now, using Future we can hold the execution, in this case just two, but we can hold how many queries we need.
Where is the trick? Future method is returning a delayed enumerable implementation, that?s all. When you iterate the enumerable (with a foreach for example), it detects and execute all the queries using a NHibernate-MultiQuery command (could be a MultiCriteria, it depends what we are using). But we don?t need to know nothing about the underlying implementation, just the concept.
In other terms, this is what happens behind the scenes:
But what if we want to retrieve an entity or a scalar ? This is too simple for an IEnumerable. Thanks to Davy Brion we have another feature called FutureValue. The mechanism is the same as Future, but instead of expect a IEnumerable, we obtain a single value (an entity or a scalar).

NHibernate isn’t integrated to the compiler, so what?
Posted by Dario in NHibernate on September 4th, 2008
I know, this title sound like: “hmm?” Let me explain it with more detail.
NHibernate is a framework that use natively Xml in order to configure a mapping between objects and tables, is in charged of join these different worlds.
But now, what is going wrong with this? Many people can say that Xml files are evil, because you should write a lot of lines, and when you build your project, the compiler doesn’t know if its ok or not, you have none errors. And this is true, you should run your project and see what happen in runtime, and to get an error in runtime is just annoying.
But now, do we have another alternative to this? Yes of course. Lets go to details. NHibernate has a “compiler” too, and you can guess what it is: BuildSessionFactory() method. You don’t have to launch the whole application to know if your mapping is working well. A way to know if everything is ok is create a test like this:

Then you just need to build the project, and run this simple and fool test, if your code pass though this, your mappings are ok.
We should remember one thing, you can map into Xml not just entities, you can map queries too (and another stuff that isn’t part of this matter). To map queries into Xml it calls: Named Queries, and in this post we talk about this matter. But the main point is, mapping the queries you will know if them are well formed when BuildSessionFactory() is raised, besides another beauties discussed in that post.
Another thing you should remember is you MUST use the Xsd to validate the mapping file. This is mandatory if you’re using NHibernate and you want to spend time programming instead of dealing with mapping errors (and here they come even with not-well-formed xmls). But this is topic to an How to or another post.