Creating a common generic and extensible NHiberate Repository version 2

This is a follow up to my original post on this topic Creating a common generic and extensible NHiberate Repository and further progression of it taking advantage of DetachedCriterias and Future queries.

I’m going to start with my interface as a jumping off point.

public interface IRepository<T> { 
/// <summary>
/// Adds the specified <see cref="T"/>. 
/// </summary> 
/// <param name="obj">The obj.</param> 
void Add(T obj);  
/// <summary>  
/// Deletes the specified <see cref="T"/>. 
/// </summary> 
/// <param name="obj">The obj.</param> 
void Delete(T obj);  
/// <summary> 
/// Defers the detached crteria execution which will return a result set that is an <see cref="IEnumerable{T}"/>. 
/// </summary> 
/// <param name="detachedCriteria">The detached criteria.</param> 
/// <returns></returns> 
IEnumerable<T> FutureList(DetachedCriteria detachedCriteria); 
/// <summary> 
/// Executes the detached crteria immediately returning a single item <see cref="T"/>
/// This will also cause the execution of any defered queries to be executed. 
/// </summary> /// <param name="detachedCriteria">The detached criteria.</param> 
/// <returns></returns> 
T FutureSingle(DetachedCriteria detachedCriteria); 
/// <summary> 
/// Gets the specified <see cref="T"/>. 
/// </summary> 
/// <typeparam name="U"></typeparam> 
/// <param name="id">The id.</param>
 /// <returns></returns> 
T Get<U>(U id); 
/// <summary> 
/// Executes the detached crteria immediately returning a result set that is an <see cref="IList{T}"/>. 
/// This will also cause the execution of any defered queries to be executed. 
/// </summary> 
/// <param name="detachedCriteria">The detached criteria.</param> 
/// <returns></returns> 
IList<T> QueryList(DetachedCriteria detachedCriteria); 
/// <summary> 
/// Executes the detached crteria immediately returning a single item <see cref="T"/> 
/// </summary> 
/// <param name="detachedCriteria">The detached criteria.</param> 
/// <returns></returns> 
T QuerySingle(DetachedCriteria detachedCriteria); 
/// <summary> 
/// Inserts or updates the specified <see cref="T"/>. 
/// </summary>
/// <param name="obj">The obj.</param> 
void SaveOrUpdate(T obj); 
/// <summary> 
/// Updates the specified <see cref="T"/>. 
/// </summary> 
/// <param name="obj">The obj.</param>
 void Update(T obj); } 

I think my interface is very well defined and with the XMLDoc comments easy to follow what will be implemented. The most notable changes from my original post is the removal of the GetAll and GetRange methods that returned an ICriteria, these always felt like a kludge to me as they clearly bleed concern by allowing the raw ICriteria to be exposed however back then I didn’t have the tools and knowledge available to create a better solution.

The new methods are related to the DetachedCriterias QuerySingle, QueryList and to the Future based queries FutureSingle and FutureList. Future is a newer construct in NHibernate that allows you to specify a query that you want NHibernate to understand and know at some point in the Future it will need this execution so you can batch more than 1 query together and reduce the number of calls to a database. This is a great bonus as the database is usually always the biggest slow down in an application.

On to the actual implementation of the interface

public class Repository<T> : IRepository<T> { 
private readonly IBusinessConversation _conversation;

public Repository(IBusinessConversation conversation) { _conversation = conversation; } 

IList<T> IRepository<T>.QueryList(DetachedCriteria detachedCriteria) {  
 return detachedCriteria.GetExecutableCriteria(_conversation.Session).List<T>(); 
} 

T IRepository<T>.QuerySingle(DetachedCriteria detachedCriteria) {  
 return detachedCriteria.GetExecutableCriteria(_conversation.Session).UniqueResult<T>(); 
} 

T IRepository<T>.FutureSingle(DetachedCriteria detachedCriteria) {  
 return detachedCriteria.GetExecutableCriteria(_conversation.Session).FutureValue<T>().Value; 
} 

IEnumerable<T> IRepository<T>.FutureList(DetachedCriteria detachedCriteria) {  
 return detachedCriteria.GetExecutableCriteria(_conversation.Session).Future<T>(); 
} 

T IRepository<T>.Get<U>(U id) { return _conversation.Session.Get<T>(id); } 

void IRepository<T>.SaveOrUpdate(T obj) { _conversation.Session.SaveOrUpdate(obj); } 

void IRepository<T>.Add(T obj) { _conversation.Session.Save(obj); } 

void IRepository<T>.Update(T obj) { _conversation.Session.Update(obj); } 

void IRepository<T>.Delete(T businessObj) { _conversation.Session.Delete(businessObj); } } 

The one that might be confusing is the _conversation dependency this relates to another post Implementing NHibernate Long Conversation with no HttpModules or AOP build time weaving. You can take a look at this if you haven’t and are curious however it’s not needed to understand my code here as you can really view _conversation to be the raw NHibernate ISession and understand what is going on here.

This class houses the generic CRUD operations that are made generic to allow you to handle any custom object easily. The methods that are once again of interest are the ones I discussed as new additions to my Repository. The beauty of all them regardless is in their simplicity that they can all be written in 1 concise line yet offer immense flexibility.

With the QuerySingle and QueryList methods these allow you to take in a DetachedCriteria and get back either a single object or a IList collection which should be pretty self explanatory from both the code and method names.

The FutureList and FutureSingle are not so much as obvious. As I stated before these allow you to make these happen in the future. In my implementation only the FutureList will really allow you to relegate multiple events into the future but it also makes the most sense since individual lookups are frequently done by indexed columns that should be quick even done in multiple seperate calls. For each call you make to FutureList it will have NHibernate queue up the specified DetachedQuery and wait for one of the following either code causes any of IEnumerables returned to be enumerated which will fire off 1 mulit-query to get all of the result sets or you call FutureSingle.

FutureSingle is some what of a more unusual animal because a regular object doesn’t have the lazy access method that IEnumerables do either it exists, or it doesn’t. There is no transient stage as there is with IEnumerables. To overcome this fact the developers of NHibernate created this transient stage by wrapping object with a generic interface for IFutureValue<T> this gives a construct to have a 3rd stage that you need to call .Value to invoke the actual execution which will process all future queries. In my repository I actually call .Value immediately on a DetachedCriteria being passed into this, why? Because I’d need to return a IFutureValue<T> instead of just T as the result from the method. This in my opinion would be just as much of a kludge as returning ICriteria was from my previous implementation as it bleeds NHibernate understanding logic outside of the repository. This purely a subjective point and if you disagree with my sentiment you could easily return IFutureValue<T> and have a wider range of flexibility with the Future support.

Now on to actual usage of this in a real world scenario. I am going to be taking advantage of a framework I recently learned about called NHibernate Lambda Expressions this allows you to write Criteria and DetachedCriteria queries without the need to rely on magic strings. The point of this post won’t be to cover the usage of this as it should be mostly understandable for my example.

 public class DataProvider : IDataProvider {  
private readonly IRepository<Person> _personRepository;  

public DataProvider(IRepository<Person> personRepository) { _personRepository = personRepository; } 

public IList<Person> GetPersons(State state) { 
  var query = DetachedCriteria.For<Person>() 
 .CreateCriteria<Person>(x => x.PrimaryZip) 
 .CreateCriteria<Zip>(x => x.State) 
 .Add<State>(x => x.StateCode == state.StateCode);  
 return _personRepository.FutureList(query); 
} 

public Person GetPerson(Guid personID) {  return _personRepository.Get(personID); } } 

If you look at my GetPersons method you should see I have a somewhat deep object graph that is realistic, I have a collection of Persons in my database where I assign them a zip code object that contains among other things the zip code and the state that zip code lives in. I create a DetachedCriteria that lets me find all persons that exist in a state and I pass that down to my generic IRepository by delegation instead of inheritance. Many examples similar to my post use inheritance where you will inherit from Repository<Person> instead of having a delegate inside of a non generic class I feel this is the wrong way because it then limits you to having 1 repository per data object instead of being able to drop multiple IRepositorys inside of a single DataProvider.

Taking this a step further I can even remove the need to ever create a physical implementation of Repository<Person> through the use of an inversion of control / dependency injection framework in this case specifically StructureMap. In literally 1 line I can create an infinite amount of IRepositories for any application I need.

For(typeof (IRepository<>)).LifecycleIs(new HybridLifecycle()).Use(typeof (Repository<>)); 

This instructs StructureMap that anytime I need a IRepository<Person> or any other data object that it’s to give it a usage of Repository
completely absolving me of the responsibility of defining a Repository<Person> combining the functionality I’ve outlined in this post it offers a broad range of usage that allows you to interact with NHibernate without ever needing to write a single line of code again except the specific DetachedCriterias which will need written in one shape or form irregardless because they will have custom sql be the end result of them and to just wire up Methods to allow access to the underlying CRUD methods. You could actually expose the generic methods themselves however I feel that is exposing too much logic to be available to an API and prefer to shroud my generic repositories in the classes I call DataProviders as it also lets me group repositories in meaningful ways.

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

Creating a generic Model-View-Presenter framework

With all of the current talk about ASP.NET MVC it seem dated to bring up the model view presenter architecture but I still believe it’s a very strong pattern in separating UI logic from application design. This post is meant to offer a successor to the Web Client Software Factory (WCSF) framework provided by Microsoft. In last usage of WCSF I encountered numerous errors stemming from ObjectBuilder during the dependency injection of WCSF which is what lead me down the road of creating UnityWeb which has evolved into StructuredWeb. The rest of this post will include no specific dependencies except 1 to StructureMap to handle the actual resolution of objects through dependency injection. This could be very easily replaced by Unity or any other inversion of control framework that supports the BuildUp() method. For a framework that does not support a BuildUp operation it will make things more complicated and that will need to be solved by your case basis.

Firstly, what is the model-view-presenter (MVP) pattern? The View is defined as an interface that the Presenter will use for getting and setting data to and from the Model. The View implementation will instantiate the Presenter object and provide a reference to itself (the formal constructor parameter is the View interface while the actual parameter is a concrete View class). When the event methods of the View are triggered, they will do nothing but invoke a method of the Presenter which has no parameters and no return value. The Presenter will then get data from the View, through the View interface variable that the Presenter stored when the constructor was called. The Presenter then invokes methods of the Model, and sets data from the Model into the View through the View interface.

From a layering point of view, the Presenter class might be considered as belonging to the application layer in a multilayered architectured object-oriented system with common layers but it can also be seen as a Presenter layer of its own between the Application layer and the User Interface layer.

[/source]

Now if you’re at all like me you will have almost no more of an idea what the MVP pattern is supposed to do after that explanation. To generalize on that statement it’s basically taking the interaction of the UI and the application logic which usually is coupled together and separating it into 3 areas.

The model – this is the application logic which will be housed in controller classes.

The view – which is an interface which abstracts the UI away, all data sent and retrieved from the UI is done through this interface

The presenter – this is a mediator that negotiates how the UI and application logic interact. The view is also a composition of this class.

Starting with the view:

public interface IView
{
}

This is the most basic of the basic of interfaces, for my needs it’s purely a marker interface. If every single one of your pages shares a common property perhaps an event message collection this would be a good place to define a property for it.

The presenter class:

public abstract class Presenter<TView> where TView : IView
{
    public TView View { get; set; }

    public virtual void OnViewInitialized()
    {
    }

    public virtual void OnViewLoaded()
    {
    }
}

The OnViewInitialized method is to represent any operations you would execute in Page_Load if(Page.IsPostback == false) so only on the initial page load. The OnViewLoaded method represents all page loads whether or not they are post backs. Currently I have no global page operations since I have no global view properties. This class is also constrained that each TView for a presenter is also an IView, this will be important later.

Next creating a view:

public interface IEmployeeView: IView
{
    IList<Employee> Employees { get; set; }
    IList<Employee> EmployeesListDatasource { set; }
}

As you can see my view will have 2 properties one for getting or setting a collection and another for setting only the same type. The view also implements the marker interface IView.

Creating the presenter:

public class EmployeePresenter : Presenter<IEmployeeView>
{
    private readonly IEmployeeController _controller;

    public EmployeePresenter(IEmployeeController controller)
    {
        _controller = controller;
    }

    public override void OnViewInitialized()
    {
        View.Employees = _controller.GetEmployees();
    }

    public override void OnViewLoaded()
    {
        View.EmployeesListDatasource = View.Employees;
    }
}

I’m not going to go into the details of the IEmployeeController this is the “model” where actual application code is ran there is nothing special about this class or it’s interface and only contains logic specific to getting my set of employees. As you can see the EmployeePresenter implements Presenter. I overrided both of the methods provided by the Presenter base where the Initialize method gets list from the model and the loaded method binds the list to a datasource.

Now before I move onto implementing the IEmployeeView inside a page I’m going to create an abstract base page that will handle the dependency injection build up for my MVP framework.

public abstract class ViewBasePage<TPresenter, TView> : Page
    where TPresenter : Presenter<TView>
    where TView : IView
{
    protected TPresenter _presenter;

    public TPresenter Presenter
    {
        set
        {
            _presenter = value;
            _presenter.View = GetView();
        }
    }

    /// <summary>
    /// Gets the view. This will get the page during the ASP.NET
    /// life cycle where the physical page inherits the view
    /// </summary>
    /// <returns></returns>
    private static TView GetView()
    {
        return (TView) HttpContext.Current.Handler;
    }

    protected override void OnPreInit(EventArgs e)
    {
        ObjectFactory.BuildUp(this);
        base.OnPreInit(e);
    }
}

This class might look quite a bit strange, the majority of it is from the class definition it’s setup to only allow you to inherit it in a valid way such as: ViewBasePage<EmployeePresenter,IEmployeeView>. On the Presenter set method this is where the page actually becomes part of the composition of the Presenter (the description from Wikipedia said this).

The GetView method also probably looks strange what this is doing is getting the physical page that’s being instantiated by ASP.NET. The reason I’m doing this is it makes it easier to reference the page generically otherwise I would be required to do something smilar to

return (TView) (object) this

Which is borderline wrong since THIS technically refers to the ViewBasePage which does not implement the interface that TView consists of but at runtime eventually resolves correctly since a Page will implement the interface that makes up TView and not cause a runtime error.

This class overrides Page’s OnPreInit method to call ObjectFactory.BuildUp() which will cause all the dependency resolution to take place. In my specific usage of StructureMap I have it identify all Presenter properties as targets for dependency injection, in your case you may be required to use the [Setter] attribute from SturctureMap or the [Dependency] attribute from Unity or some other similar convention in other inversion of control frameworks.

Now finally onto the actual page.

public partial class _Default :
    ViewBasePage<EmployeePresenter, IEmployeeView>, IEmployeeView
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            _presenter.OnViewInitialized();
        }

        _presenter.OnViewLoaded();
        Page.DataBind();
    }

    #region Implementation of IEmployeeView

    IList<Employee> IEmployeeView.Employees
    {
        get { return ViewState["IEmployeeView.Employees"] as IList<Employee>; }
        set { ViewState["IEmployeeView.Employees"] = value; }
    }

    IList<Employee> IEmployeeView.EmployeesListDatasource
    {
        set { lstEmployees.DataSource = value; }
    }

    #endregion
}

This class inherits the ViewBasePage class and implements the IEmployeeView. The _presenter field is in the ViewBasePage and contains the fully resolved dependency to EmployeePresenter. As I stated in the portion of the presenter code you can see where OnViewInitialized() and OnViewLoaded() are called inside the page life cycle.

Implementing the IEmployeeView you have the properties target actual controls on the page or the ViewState / QueryString etc that is available to the page. Now if you remember the code in my actual EmployeePresenter it should make sense why in ViewInitialized the Employees property is set by the controller and on the ViewLoaded the Employees property is assigned to the EmployeesListDatasource since it’s just refreshing the data source to the view state collection on subsequent page post backs.

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

Working with List in .Net 3.5

In this post I will be going over some of the features that were added or expanded upon in the release of .NET 3.5 and the usage of the lambda operator. I will start my tutorial off with the Exists() method which has a parameter of Predict<t> match. This is basically a really fancy way of saying this method does not want an object, it wants a method!

Now C# has even more flexibility in the way you choose to style your code design always remember all 3 of these solutions are the same.

public void LambaUsage()
{
    var intList = new List<int> {1, 2, 3, 4, 5, 10, 40, 50};

    bool exists = intList.Exists(Predicate);
}

private bool Predicate(int x)
{
    return x > 25;
}

This is the first way of calling Exists which is using a named method for the fact it has a physical name and declaration of method Predicate with a parameter of int and a return type of bool. Predicate will check if x > 25 returning true if it is, making Exists parameter the method Predicate will have it iterate through the list and try the Predicate over every object if it returns true for any case Exists will return true.

In C# 2.0 along with the inclusion of List and Generics that were added, they created anonymous methods. Personally I’ve always had issues remembering the syntax to write anonymous methods and without the help of Resharper I’d have been very frequently checking google for the usage of them. I’m sure you’ll be able to see why.

bool exists = intList.Exists(delegate(int x) { return x > 25; });

That sure is a lot of syntax to achieve the same thing that is defined in the named method, don’t you agree? The developers inside Microsoft obviously did too, that’s why they created the Lambda operator in C# 3.0. The Lambda operator makes writing anonymous methods for parameters much simpler and concise.

bool exists = intList.Exists(intVar => intVar > 25);

Always remember these 3 methods are interchangeable and no one way is better than another, it’s all semantical candy but personally and I feel most .NET developers willl agree the Lambda operator makes the most sense. In this statement intVar is an implicitly typed variable (in this case int), the Lambda operator => is saying to use intVar foreach object inside the list to do the method over => there.

So the Lambda operator has a variable and a method and operator creates an arrow towards the method that will use the variable. Not really the most scientific description but I think it’s very easy to remember that way.

More to come later today.

Working with Collections – Generic IList

I am writing this article directly in response to Working with Collections – ArrayList which obviously about the array list class. Now I’m going to make a blanket statement that includes the word NEVER, generally a statement using never or always tends to be factually inaccurate for how absolute those 2 words are, however I am going to make the statement anyway.

You should NEVER use the ArrayList class.

This class should even be as far as marked deprecated since the introductions of generics a long way back with the release of 2.0 framework. Now I’m sure there’s been many articles that have beat the usage of generics into the ground but here I will make one to explain how to use List<type> class instead of the ArrayList class.

Firstly, what are generics?

Generics were added to the framework as a way to create classes that can contain any type of object while working with it strongly typed and not down casting it to System.Object the way that ArrayList does. Classes that follow patterns like ArrayList will cause objects to be repeatedly boxed and unboxed.

int i = 123;
object o = (object)i;  // boxing

o = 123;
i = (int)o;  // unboxing

Boxing

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Performance

In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.

For further information on boxing see the MSDN.

Now that you have a clearer understanding of what boxing is if you think about the ArrayList class since you can insert any type of object into the list with reckless abandon every single addition and read from the list will cause un/boxing to occur. With the statements above it’s clear to see why in usage this is a very poor class to use.

Adding

The List class also supports the inserting of strings in the same way that ArrayList does both with the Add() and AddRange() methods. I will show examples of both the .NET 2.0 usage and new conventions for the 3.5 usages.

List<string> strings20 = new List<string>();
const string dotnetchris = "dotNetChris";

strings20.Add("Marisic.Net");
strings20.Add(dotnetchris);

//Build error: Argument Type 'object' is not assignable to parameter type 'string'
strings20.Add((object)dotnetchris);

//.Net 3.5 added the var keyword and the ability to initialize a list easily.
var strings35 = new List<string> {"initial", "strings", "loaded"};

As you can see in 3.5 creating a collection with initial data much easier. It also doesn’t allow boxing to occur as you can not even add a string object if you down cast it to Object.

var stringsCombined = new List<string>();
stringsCombined.AddRange(strings20);
stringsCombined.AddRange(new[] {"string1", "string2"});

With the AddRange() method you can add any class that implements ICollection which is an interface defining a common usage of a list structure so List<> and arrays are the most common implementers of ICollection.

Now lets add in some LINQ!

strings35.AddRange(from stringval in stringsCombined
                   where stringval.StartsWith("s")
                   select stringval);
//strings35 now has: "inital", "strings", "loaded", "string1", "string2"

LINQ expressions can be used to select specific data from our lists and then make it a list itself which you could assign to it’s own declaration or use in AddRange()!

Insert

The correlary to Add and AddRange methods are the Insert and InsertRange I will move usage of these and that you can index through Lists quickly. With insert you can choose where an item is inserted into the List where as Add/Range will always place the item(s) to the end of the list.

var numbers = new List<int> {2, 2, 4};
numbers.Insert(0, 1);
numbers[2]++;
//numbers now has: 1 2 3 4

Remember that indexers are always 0 based with the Microsoft classes So Insert(0, 1) will insert on the index 0 the value of 1.

//ArgumentOutOfRangeException always remember Count - 1
numbers[numbers.Count] = 5;

Always keep indexers in mind to avoid this from occurring.

At this point I am going to hand the ball back to the article that started this post that you see the usage of Iterating through a list, removing objects and a few other helpful functions. I’ve shown some new features that were added in 3.5 that makes working with lists even greater and easier than ever. In my next post I will go over usage of some of the more complicate functions on the List class that take a paraemter of Predict<T> and the lamba operator.

BloggingContext.ApplicationInstance.CompleteRequest();