Saturday, September 10, 2011

Generics For Dummys (re:NHibernate)

I am working on a rogue project that is not being paid for by the company for which I work. This is building something that just helps me do my job, so I have to be very quick. I am using NHibernate, and wanted to get listable data without writing even the smallest functions of my own. So I created this (not for production use):

   public IList GetAll()
        {                     
            return Session.GetSession()
            .CreateCriteria(typeof(T))
            .List();
         }


Because NHibernate uses generics, this function can act as a pass-through, requesting the List method be run, but not much more. My ASP .NET webforms application has to give it the table name of interest.

Again, just a fun way to rapidly get a "table viewer" application running but also providing some code value for potential full life cycle development later.

* Re-reading years later, I think I meant
 GetAll(T) 
as the Type would have to be passed to the function.

Text Template Transformation

My team stores some database logic in an XML file that is part of a CSharp project.
This seems to be working efficiently for the application in runtime and for developers to maintain their SQL statements at design. I don't like it because the file has gotten large and finding things is a manual process.
I am trying to keep up with innovations, so I wrote a transformation that changes that XML file into a class. That way Visual Studio can provide its drop-down navigation controls for finding statements in the file.


<#@ template language="C#" #>
<#@ output extension = "cs" #>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace = "System.Xml" #>


public class SQLConfig {
<#
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Projects\\MySolution\\MyDataLayer\\ORACLESQL.config");

foreach(XmlNode node in doc.SelectNodes("//add")) {

#>

public const string <#= node.Attributes[0].Value.Replace(".","_").Replace("-","_") #> = @"<#= node.InnerText #>";

<#
}

doc = null;
#>
}



What this does is create a Class file using the above code every time the transform template is changed, or the developer can right-click "Run Custom Tool" on it.