Friday, May 09, 2008

The Problem

For the last few days I've been trying to figure out how to do this SQL in linq:

   1: select from customers where substring(customers.Name, 1, 1) IN ('a', 'b', 'c', 'd');
The problem is the list (a, b, c, d) is variable, on one page I need all the results where foo.Name starts with a or b, on another it could be b, c, d, e and f.  This is trivial to do in SQL, you just break out a little dynamic sql and your done.  But being a noob to LINQ, I'm not so sure how to go about doing this.

I had a lot of failed queries, and failed code, before giving up and just looping through the letters for that particular page and manually building up what I wanted.

But that's kind of a hack. OK, its not kind of a hack, its a big hack.

The Solution

This LINQ goodness (using the Customers db in LINQPad) will pull back all the customers who's names begin with a t, d, or j (note the .ToList() on line 4, I'll discuss it next).

   1: string[] letters = { "t", "d", "j" }; 
   2:  
   3: var customers = (from c in Customers
   4:     select c).ToList(); 
   5:  
   6: var results = from c in customers
   7:     join letter in letters on c.Name.First().ToString().ToUpper() equals letter.ToUpper()
   8:     select c; 
   9:  
  10: customers.Dump("Customers");
  11: results.Dump("Filtered by first letter");

And LINQPad renders this for us:

image

Limitations

LINQ to SQL doesn't support querying a SQL database with if one of your sources is an in-memory store, except if you use the Contains operator.  So, to work around that, you have to pull back ALL the results from the db, and then convert it to a List before you use it in the above query.

I'm my opinion, this is kind of a painful limitation, but for my particular purpose, I'm willing to live with it because my particular database will only ever have around 100 or so rows, so pulling everything back in memory isn't such a big deal...

P.S. if you are reading this in a feed reader, let me know how it renders, I've updated my code snippet plugin to try and fix the previous rendering problems.

posted on Friday, May 09, 2008 12:13:08 AM (Alaskan Standard Time, UTC-09:00)  #    Comments [0]
 Sunday, November 25, 2007

Background Information

Aspect Oriented Programming has been on my list of things to read up on for almost a year now.  It likely would have stayed on my list of things to do well into the future if it hadn't been for a recent .NET Rocks episode.  I can't recall if it was the Pablo Castro on Astoria, or the Tim Sneath and Ian Ellison show, but one of them off-hand mentioned PostSharp.  As I usually do when links are thrown about on the show, I scribbled it on my hand for later review. Update DNR just released a show with Gael Fraiteur of PostSharp fame!

Once I got to the PostSharp site, I found their sample video on creating a trace AOP attribute.  They had me hooked.  I wasn't so much interested in doing a logging or trace attribute, but was more interested in doing a few validation attributes.  More specifically a NotNullAttribute.

The Problem

What got me interested in doing the NotNullAttribute was thinking back to how many times in our code base we would have something like this:

1 public void AddUser(Organization org, User user) 2 { 3 if (org == null) 4 throw new ArgumentNullException("org"); 5 if (user == null) 6 throw new ArgumentNullException("user"); 7 8 org.AddUser(user); 9 _ordDal.Save(org); 10 }

Granted this is a somewhat short method, but we have methods which take 6 parameters, and only 2 actual lines of code.  That's 12 lines of code taken up for argument checking, and 2 lines of code.  That would put our crap to code ratio at 6/1.

The Solution

Wouldn't it be much nicer if you could do something like this:

1 public void AddUser([NotNull] Organization org, [NotNull] User user) 2 { 3 org.AddUser(user); 4 _ordDal.Save(org); 5 }

 

PostSharp is almost there to let you write code just like that.  Currently, there is no support for an OnParameterAspectBoundaryAttribute in PostSharp, so we have to do things just slightly differently:

[NotNullHelper] public void AddUser([NotNull] Organization org, [NotNull] User user) { org.AddUser(user); _ordDal.Save(org); }

We have to have a helper class were all the actual code lives.

How PostSharp Works

PostSharp works by weaving all your AOP attributes with your source code after the compiler compiles your code.  This article by Gael Fraiteur describes in more detail how the PostSharp process works.  After the code is post-compiled by PostSharp, you end up with something very ugly that looks like this:

public void AddUser([NotNull] Organization org, [NotNull] User user) { MethodExecutionEventArgs ~laosEventArgs~2; try { object[] ~arguments~1 = new object[] { org, user }; ~laosEventArgs~2 = new MethodExecutionEventArgs(methodof(OrgManager.AddUser, OrgManager), this, ~arguments~1); ~PostSharp~Laos~Implementation.NotNullHelperAttribute~3.OnEntry(~laosEventArgs~2); if (~laosEventArgs~2.FlowBehavior != FlowBehavior.Return) { org.AddUser(user); _orgDal.Save(org); ~PostSharp~Laos~Implementation.NotNullHelperAttribute~3.OnSuccess(~laosEventArgs~2); } } catch (Exception ~exception~0) { ~laosEventArgs~2.Exception = ~exception~0; ~PostSharp~Laos~Implementation.NotNullHelperAttribute~3.OnException(~laosEventArgs~2); switch (~laosEventArgs~2.FlowBehavior) { case FlowBehavior.Continue: case FlowBehavior.Return: return; } throw; } finally { ~PostSharp~Laos~Implementation.NotNullHelperAttribute~3.OnExit(~laosEventArgs~2); } }

I don't know about you, but I would have one HELL of a time trying to debug this, thankfully PostSharp touches up the PDB files, so when your debugging, you only see and debug the source code you've written, both your attribute, and your business logic.

The Drawbacks

PostSharp modifies your code! Well, not directly, but it is still modifying your code (as seen above), but thankfully it touches up the PDB files so all the mess under the hood is hidden from you.

Conclusion

This is but one of the many things you can do with AOP and PostSharp.  Next up, I plan to write some validation attributes.  Look for those in the next few weeks.  In the mean time, download the source code for the NotNullAttribute.

I'm sorry if this post looks terrible in your feed reader, I still haven't been able to figure out why the code looks terrible.  If anyone has any suggestions, let me know.  I'm using DasBlogCE as my blog engine.

kick it on DotNetKicks.com
posted on Sunday, November 25, 2007 8:37:23 PM (Alaskan Standard Time, UTC-09:00)  #    Comments [3]
 Thursday, September 13, 2007

Usually I post solutions I've discovered or created to problems I've encountered.  Now, I've run into a problem with the XmlSerializer and I need your help solving it.  Scroll to the bottom for an update.

The Problem

I have a class called Foobar.  Foobar inherits from List<string>, and contains one member Title.  When I use the XmlSerializer to serialize and deserialize Foobar, all the items in the List are make it through safely, but the member Title does not.

The Code

using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; internal class Program { private static void Main() { Foobar f = new Foobar(); f.Add("1"); f.Add("2"); f.Title = "Title"; MemoryStream mem = new MemoryStream(); XmlSerializer xs = new XmlSerializer(typeof(Foobar)); xs.Serialize(mem, f); mem.Seek(0, 0); mem.Seek(0, 0); Foobar deser = (Foobar)xs.Deserialize(mem); Console.WriteLine(deser); } } [Serializable] public class Foobar : List<string> { public string Title; }

The Solution

One way I came up with to solve this problem is make Foobar not inherit from List<string>, and make a member called Items that is a List<string>, but that's kind of hokey.  I've searched Google and can't find a solution.  So I'm appealing to my dear readers for a better solution.

Update

Looks like I was being way to specific in my Google search, searching on "XmlSerializer List" gives us this http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=566175&SiteID=1 as the first item.  In the post,

Elena Kharitidi says "XmlSerializer does not serialize any members if a collection. Only collection items get serialized. This is by design, basically a decision was made to handle collections as arrays not as classes with multiple properties, so collections should look like arrays on the wire, therefore they do not have any members other then collection items, and can be “flattened” by adding the [XmlElement] to the member of the ICollection type."

Long and short, I need to use the hokey solution I came up with (or something like it), or write my own serializer.

posted on Thursday, September 13, 2007 6:22:29 AM (Alaskan Standard Time, UTC-09:00)  #    Comments [0]
 Sunday, August 26, 2007

I downloaded the very excellent Resource Refactoring Tool (http://www.codeplex.com/ResourceRefactoring) the other day.  It works great in code files, but I found that it didn't work at all for ASPX/HTML pages.  Seeing this as a challenge, I decided to hack something up in VBA to automatically extract the selected text, create a resx name for the text, add it to the resource file, and insert the ASP.NET literal control.

How to use it

This is split up into two different macro modules, one named Utilities, and the other named what ever you want.  Then add them to your Visual Studio tool bar so you have something convenient you can click on (Right click the tool bar, click Customize, click Commands, then Macros under categories, find what you named the macro and then drag it up to your tool bar.  You can either drag it to an existing tool strip, or create your own.  Finally right click on the item while still in customize mode and add an image).

 

Caller:

Imports System Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Public Module MoreMacros Public Sub AspTextLiteral() Dim resx as ProjectItem = DTE.ActiveWindow.Object.GetItem("solution\project\folder\ResourceFile.resx") Utilities.AspTextLiteral(resx) End Sub Public Sub InQuoteLiteral() DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate() Dim resx as ProjectItem = DTE.ActiveWindow.Object.GetItem("solution\project\folder\ResourceFile.resx") Utilities.InQuoteLiteral(resx) End Sub End Module

Utilities:

Imports System Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Imports System.Xml Public Module Utilities Public Sub AspTextLiteral(ByRef resourceFile As ProjectItem) Const literalFormat = "<asp:Literal runat=""server"" Text=""<%$ Resources:{0},{1}%>"" />" Const inQuotesFormat = "<%$ Resources:{0},{1}%>" LiteralReplacer(resourceFile, literalFormat, 4) End Sub Public Sub InQuoteLiteral(ByRef resourceFile As ProjectItem) Const inQuotesFormat = "<%$ Resources:{0},{1}%>" LiteralReplacer(resourceFile, inQuotesFormat, 3) End Sub Private Sub LiteralReplacer(ByRef resourceFile As ProjectItem, ByVal template As String, ByVal delete As Int16) Dim ts As TextSelection = DTE.ActiveDocument.Selection Dim name As String = StripNonAllowedChars(ts.Text).Trim.ToLower Dim value As String = ts.Text Dim path As String = resourceFile.Properties.Item("LocalPath").Value Dim resName As String = System.IO.Path.GetFileNameWithoutExtension(resourceFile.Name) name = AddResourceEntry(path, name, value) ts.Text = String.Format(template, resName, name) DTE.ActiveDocument.Selection.Delete(delete) End Sub 'Returns the value of the name used Public Function AddResourceEntry(ByRef resourceFilePath As String, ByVal name As String, ByVal value As String) As String Dim doc As XmlDocument = New XmlDocument doc.Load(resourceFilePath) 'See if it exists first Dim root As XmlElement = doc.DocumentElement Dim e As XmlElement = root.SelectSingleNode(String.Format("data[@name=""{0}""]", name)) If e Is Nothing Then name = CreateUniqueName(root, name) Dim elem As XmlElement = CreateResourceFileElement(doc, name, value) root.AppendChild(elem) Else If e.SelectSingleNode("value").InnerText.ToLower = value.ToLower Then Return name Else name = CreateUniqueName(root, name) Dim elem As XmlElement = CreateResourceFileElement(doc, name, value) root.AppendChild(elem) End If End If doc.Save(resourceFilePath) Return name End Function Private Function CreateUniqueName(ByRef root As XmlElement, ByVal name As String) As String If IsNumeric(name.Substring(0, 1)) Then name = "n" & name End If 'Name doesn't exist, use it If Not CheckNameExists(root, name) Then Return name End If Dim result As String 'Build a unique name For I As Int16 = 1 To 100 result = name & I If Not CheckNameExists(root, result) Then Return result End If Next Return name & Guid.NewGuid.ToString End Function Private Function CheckNameExists(ByRef root As XmlElement, ByVal name As String) As Boolean Dim e As XmlElement = root.SelectSingleNode(String.Format("data[@name=""{0}""]", name)) Return Not (e Is Nothing) End Function Private Function CreateResourceFileElement(ByRef doc As XmlDocument, ByVal name As String, ByVal value As String) As XmlElement Dim result As XmlElement = doc.CreateElement("data") SetAttribute(result, "name", name) SetAttribute(result, "xml:space", "preserve") Dim valueElem As XmlElement = doc.CreateElement("value") valueElem.InnerText = value result.AppendChild(valueElem) Return result End Function Private Function SetAttribute(ByRef element As XmlElement, ByVal attr As String, ByVal value As String) As XmlElement If element.Attributes.GetNamedItem(attr) Is Nothing Then Dim attrib As XmlAttribute = element.OwnerDocument.CreateAttribute(attr) attrib.Value = value element.Attributes.Append(attrib) Else element.Attributes.Item(attr).Value = value End If Return element End Function Private Function StripNonAllowedChars(ByVal text As String) As String Const non_allowed = """';:,<.>/?\|`~!@#$%^&*()-=+[{]} " For I As Integer = 0 To non_allowed.Length - 1 text = text.Replace(non_allowed(I).ToString, "") Next Return text End Function End Module

 

del.icio.us Tags: , , ,
posted on Sunday, August 26, 2007 7:56:04 PM (Alaskan Standard Time, UTC-09:00)  #    Comments [0]
 Tuesday, January 23, 2007

I've started work on the search piece of our application.  Searching (no pun intended) for some inspiration on how users might want to search within our application, I brought up the current WinForms version, and then the ASP.NET version.

I realized that we need to make searching easier in WinForms client, currently when searching for a patient in our WinForms client, you are presented with a separate text box for first name, last name, SSN, date of birth, and health record number.  Our ASP.NET client presents just one text box to search all of those fields.

Tying the Domain Model to the Data Access Layer

So I started thinking about all the pieces in our domain model that we might want to allow the user to search.  Then I realized that to allow searching across all the fields in an entity would tie the data access layer (DAL) to  the domain model ala something like this:

public IList<Patient> Search(string text) { ICriteria criteria = session.CreateCriteria(typeof(Patient)); Disjunction or = Expression.Disjunction(); text = string.Format("%{0}%", text); or.Add(Expression.Like("FirstName", text)); or.Add(Expression.Like("MiddleName", text)); or.Add(Expression.Like("LastName", text)); crit.Add(or); return criteria.List<Patient>(); }

Variations of this code would have to be repeated for every data access class in our DAL.  You could create a string list of the properties on the entity to search and pass them to a method that would build your criteria; but at the end of the day, your still tying your domain model to your data access layer.

Custom Attributes

I started doing some thinking about how unit testing frameworks such as  work and realized I could use .NET custom attributes and some reflection to solve the problem.

I came up with an attribute called Search, currently it takes in one boolean parameter called Enabled.

1 using System; 2 using System.Reflection; 3 4 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 5 public class SearchAttribute : System.Attribute 6 { 7 public bool Enabled; 8 9 /// <summary></summary> 10 /// </summary> 11 /// <param name="Enabled">if true, property will be included in object-level searches</param> 12 public SearchAttribute(bool Enabled) 13 { 14 this.Enabled = Enabled; 15 } 16 }

I could have written it as:

1 using System; 2 using System.Reflection; 3 4 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 5 public class SearchAttribute : System.Attribute { }

But I wanted the flexability of adding named parameters in the future.  Who knows, maybe this is a lame reason, and I should just refactor the code if I want to add parameters to it in the future.

Adding the Attribute to Your Domain Model

The interesting thing about a custom attribute, is if it ends in Attribute (i.e. SearchAttribute), its name gets changed to Search by the C# compiler(?), although you could still use SearchAttribute as the name when you add it to your properties.  If you look at the IL, its still called SearchAttribute:

.custom instance void MyNamespace.SearchAttribute::.ctor(bool) = ( bool(true) )

But if you change the attribute name to SearchAttrib, or SearchAttributes, then you have to use the full name when decorating the properties in your class.  This really isn't germane to the topic at hand, I just thought it was neat! :)

Example:

1 public class Patient 2 { 3 [Search(true)] 4 public string FirstName 5 { 6 get { return _firstName; } 7 set { _firstName = value; } 8 } 9 ... 10 }

Pulling it All Together

The custom attribute is great and all, but it doesn't inherently buy us anything.  We need to add a little bit more to make all this work.  This is a simplified version of what I ended up putting in my DAL base class:

1 private IList<Patient> Search(string text) 2 { 3 Type type = typeof(Patient); 4 ICriteria criteria = _session.CreateCriteria(type); 5 6 Disjunction or = Expression.Disjunction(); 7 foreach (PropertyInfo propInfo in type.GetProperties()) 8 { 9 //SearchableAttribute is AllowMultiple = false, so we only need the first item 10 Attribute[] attribs = Attribute.GetCustomAttributes(propInfo, typeof(SearchAttribute)); 11 if (attribs.Length == 0) 12 continue; 13 14 if (((SearchAttribute)attribs[0]).Enabled) 15 or.Add(Expression.InsensitiveLike(propInfo.Name, string.Format("%{0}%", text))); 16 } 17 criteria.Add(or); 18 return criteria.List<T>(); 19 } 20

Again, this is a simplified version of what's in our DAL base class, the actual signature looks more like this: private IList<T> Search<T>(string text) so that I don't have to write a version of this for each class in our domain model I want to enable searching for.

Everything above should be pretty self-explanatory unless you aren't familiar with the NHibernate Criteria API; in which case the Expression.Disjunction bit on line 6 is how you do an OR (a OR b OR c)when searching.  You can also do Expression.Conjunction if you want AND searching (a AND b AND c).

The original version of this code had a second foreach loop which spun through all the attributes on each property looking for the SearchAttribute.  I thought to myself that their had to be a better way and did a little bit of poking around, and discovered much to my delight that the static method Attribute.GetCustomAttributes allows you to specify what kind of attribute you are searching for!

Limitations

In the code above, you'll get an Exception if you try to search against non-text columns in your database so you will need to that into account when putting the Search attribute in your Domain Model; or add some more smarts to the Search method to take into account different data types.

Comments

If you've read down this far, then I'd love to get a comment from you.  Is there anything you think I could do a better job of explaining, am I an awesome guy?  Or do I suck, either way, I'd like to know, so please leave me a comment!

If you like my article, please kick it at .NET Kicks (I have no idea why the kick counter says I have zero kicks btw)!

posted on Tuesday, January 23, 2007 11:02:42 AM (Alaskan Standard Time, UTC-09:00)  #    Comments [2]
 Thursday, January 18, 2007

We are in the midst of doing a total rewrite of our Software, and one of the things that has come up is date and time.  How do we do it, how do we store it, and how do we ensure that we can compare DateTime from one timezone to DateTime in another timezone.  After a lot of research, we settled on using UTC (or UCT depending on your preference).  FxCop will take care of ensuring we use UTC (for the most part).

That solves the problem, or so we thought.  Turns out, when you create a DateTime object either through the constructor, or through DateTime.Parse, its Kind defaults to DateTimeKind.Unspecified.  We need a way to ensure that all DateTime objects are always set to UTC.

What are our options?

Because we are using NHibernate, we have a few options.  The three NHibernate specific ones that immediately come to mind are using an Interceptor, a custom UserType with a SQL datetime column, and a custom UserType with a SQL varchar column; and the non-NHibernate specific one is creating our own DateTime container.  What are the pros and cons of each of these?

NHibernate Interceptor

Pro: very cross-cutting, can touch every object as it comes in and goes out to the database; if there are other data types we need to monkey with, we already have a framework in place.

Con: Very cross-cutting, can be expensive because it's touching every property on every entity as the entities are loaded and persisted

UserType with SQL datetime column

Pro: Only touching the DateTime objects that we want it to

Con: The type has to be specified for every DateTime object in every mapping file; no meta-data along with the date to stamp in the timezone it was created in

UserType with SQL varchar column

Pro: Only touching the DateTime objects that we want it to; can store the timezone and offset along with the date in the db

Con: Same as above UserType; abusing SQL data types; datetimes created at the same (relative) time in two different timezones won't be sorted correctly

Custom DateTime container

Pro: We can do anything we want

Con: Yuck! - I could write a whole paragraph on why this is yucky, but I'll leave that to your imagination

 

After some thought, I decided on the Interceptor!  Here is the class I came up with (you can also download the complete UtcDateTimeInterceptor class):

1 class UtcDateTimeInterceptor : IInterceptor 2 { 3 public bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types) 4 { 5 ConvertDatabaseDateTimeToUtc(state, types); 6 return true; 7 } 8 9 public bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types) 10 { 11 ConvertLocalDateToUtc(state, types); 12 return true; 13 } 14 15 public bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, 16 IType[] types) 17 { 18 ConvertLocalDateToUtc(currentState, types); 19 return true; 20 } 21 22 private void ConvertLocalDateToUtc(object[] state, IType[] types) 23 { 24 int index = 0; 25 foreach (IType type in types) 26 { 27 if ((type.ReturnedClass == typeof(DateTime)) && state[index] != null && (((DateTime)state[index]).Kind == DateTimeKind.Utc)) 28 { 29 state[index] = ((DateTime)state[index]).ToUniversalTime(); 30 } 31 32 ++index; 33 } 34 } 35 36 private void ConvertDatabaseDateTimeToUtc(object[] state, IType[] types) 37 { 38 int index = 0; 39 foreach (IType type in types) 40 { 41 if ((type.ReturnedClass == typeof(DateTime)) && state[index] != null && (((DateTime)state[index]).Kind == DateTimeKind.Unspecified)) 42 { 43 //Create a new date and assume the value stored in the database is Utc 44 DateTime cur = (DateTime)state[index]; 45 DateTime result = DateTime.SpecifyKind(cur, DateTimeKind.Local); 46 state[index] = result; 47 } 48 49 ++index; 50 } 51 } 52 }

Loading The Entities

For the sake of brevity, I'm going to exclude the bits of the Interceptor interface that aren't relevant to my posting.  With that said, the OnLoad event (line 3) gets fired every time an entity is loaded from the database.  We can count on the fact that all dates are stored as UTC in the database because of stuff we'll do later, so we need to convert the DateTime that NHibernate generates (which has a DateTimeKind of Unspecified) to a UTC date (line 36 - 48).  The types array holds the CLR data type of each property in the entity, and each type in the array contains both the internal NHibernate type, and the CLR type. But we don't really care about how NHibernate maps the data types internally, so we are only interested in type.ReturnedClass.

The first thing we need to do is see if the ReturnedClass is of type DateTime (line 41), if its a DateTime, then we need to see if its null, and finally double check that the Kind on the DateTime object coming back from the database is Unspecified.  This last check is a sanity check, in case this behavior changes in the future.

After all these checks are passed, we need to create a new DateTime object from the old one, and set its Kind to Utc (lines 44 and 45).  Thankfully, DateTime has the built-in method SpecifyKind which will take care of building a DateTime of the specified kind for us. And finally replace the existing DateTime object with our new one (line 46).  Shampoo, rinse, repeat for all the DateTime values in the entity.

Persisting The Entities

Now we can move on to the save and update NHibernate events (line 9, and 15 respectively).  In these, we want to make sure the values being persisted to the datastore are UTC, and that no Local times have slipped through the cracks.  If one were so inclined, they could throw an error instead of converting the DateTime to UTC...

The basic code for converting Local DateTime's to Utc (line 22- 34) is much the same as above, but with a few exceptions.  When we do all our checks (line 27), this time we make sure the DateTimeKind is Local before we perform a conversion operation on it.  It is pointless to check if the Kind is Unspecified, because there is no conversion operation we can really perform on it.  On line 29, we can use the built in DateTime method ToUniversalTime() to convert a LocalTime to UTC.

Finishing Up

How do we wire this all up?  When you open a session on your session factory, you can pass in an Interceptor, this is where you would pass in the UtcDateTimeInterceptor.  eg:

ISession openSession = ourSessionFactory.OpenSession(new UtcDateTimeInterceptor());

I want to give credit where credit is due, I got the actual idea of using an Interceptor from  where he grappled with DateTime, null, messages and web services.  If anyone using NHibernate doesn't read , I would highly encourage you to.  He is a very, very sharp fellow; and prolific blogger.

posted on Thursday, January 18, 2007 3:36:52 PM (Alaskan Standard Time, UTC-09:00)  #    Comments [0]
 Saturday, December 30, 2006

Often times when you're developing an application, there is a one-to-one mapping between your domain model (object model) and your database schema.  Doing it this way often times makes it easier to wrap your head around everything going on in your app.

 

But this isn’t always the right way to do things.  For example, take the highlighted columns in the UserCredential table:


 

In the UserCredential class, do you really want to have HashedPassword, HashType, and PasswordSalt properties?  Probably not...  So, how can we still do our mapping with NHibernate and avoid creating a clunky UserCredential class?  Enter NHibernates CompositeUserTypes!

 

First, let’s create our domain objects:

Notice that the UserCredential class contains a property called Password, which maps to the class Password.

 

Now, let’s create our CompositeUserType, in our case, we’ll call it PasswordCompositeUserType, and this class will implement the NHibernate.IUserType interface:

public class PasswordCompositeUserType : IUserType { public new bool Equals(object x, object y) { if (x == y) return true; if (x == null || y == null) return false; return x.Equals(y); } public object DeepCopy(object value) { if (value == null) return null; else return ((Password)value).Copy(); } public int GetHashCode(object x) { return x.GetHashCode(); } public bool IsMutable { get { return false; } } public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner) { if (rs.IsDBNull(rs.GetOrdinal(names[0])) || rs.GetOrdinal(names[0]) == string.Empty) return null; string hashedPassword = (string)rs[names[0]]; long salt = (long)rs[names[1]]; HashType hashType = (HashType)Enum.Parse(typeof(HashType), (string)rs[names[2]]); Password result =