dotNetChris @ Marisic.Net

June 25, 2009

It’s been a while!

Filed under: Off Topic — dotnetchris @ 2:10 pm

It’s definitely been a while since I updated my blog with a new post that’s going to change starting again today. While this one really won’t have any new content I just felt like adding some personal thoughts. After my last blog post my software development contract ended unexpectedly which left me with alot of free time other than searching for a new contract to work on. My first thoughts were great, a vacation! Which I used to enjoy a few weeks of my time without having to do anything specific which I haven’t had in my life since probably high school during the summer.  After stepping back for a few weeks I did some casual development on StructuredWeb at home for a little while then started slacking on that. It really is hard to stay focused on the technology world when you’re not exposed to it every day at work especially since software development (especially when done well) isn’t easy and takes alot of will and drive to accomplish, well that ends today.

This Monday I started a new position at a small Insurance company / marketing firm to be their lead architect to drive their technology usage and provide them strategic applications far above their previous piecemeal approach with using some outside contracts for their website. I’m really looking forward to this because finally I don’t have to answer or justify using new technology or different technology (to an extent atleast) for solving software problems. Nothing has ever bothered me more in previous jobs at larger companies where most developers just choose mediocrity at best, or to be abysmal at worst and just don’t care to learn anything new as developers and to just apply bad practices to problems because that’s what they’re familiar with.

February 16, 2009

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: Wikipedia]

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 constrainted that

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();

February 11, 2009

Creating a generic validation framework

Filed under: Architecture, Programming, StructuredWeb — dotnetchris @ 10:25 pm

Recently in a few discussions of system architecture I have brought up adamant complaints about coupling validation logic to your domain objects. This weekend Thomas Mayfield contacted me on how I would go about implementing this in a domain driven designed system. Initially I got sidetracked over what tool I would use for my rules engine and I’ve still not concluded which would be best so I went about creating my Validation layer and decided to leave the specific details of creating validation logic for later.

As always I start with an interface. In this case it ends up being a very simple interface.

public interface IValidator<T>
{
    ValidationResult Validate(T obj);
    ValidationResult Validate(T obj, bool suppressWarnings);
}

Basically I want this service to take in an object and validate it, and then return to me whether it’s valid and any warnings or error messages associated with the validation. Which lead me to creating a ValidationResult class (in lieu of the similarly named class in the Enterprise Library validation block).

First I created a very simple ValidationMessage class:

public sealed class ValidationMessage
{
    public string Message { get; internal set; }
    public bool Warning { get; internal set; }

    //Only allow creation internally or by ValidationResult class.
    internal ValidationMessage()
    {
    }
}

The ValidationResult class is a little more complex:

public sealed class ValidationResult
{
    private bool _dirty = true;
    private bool _valid;

    public bool Valid
    {
        get
        {
            //theoretically O(n) time but in pratice will be constant time
            //Still, no need for multiple traversals, Traverse only if it's changed
            if (_dirty)
            {
                _valid = Messages.FirstOrDefault(msg => msg.Warning == false) == null;
                _dirty = false;
            }

            return _valid;
        }
    }

    public ValidationResult()
    {
        Messages = new List<ValidationMessage>();
    }

    public IList<ValidationMessage> Messages { get; internal set; }

    /// <summary>
    /// Adds the error. 
    /// </summary>
    /// <param name="errorMessage">The error message.</param>
    public void AddError(string errorMessage)
    {
        _dirty = true;
        Messages.Add(new ValidationMessage {Message = errorMessage});
    }

    /// <summary>
    /// Adds the warning. 
    /// </summary>
    /// <param name="warningMessage">The warning message.</param>
    public void AddWarning(string warningMessage)
    {
        //No need to mark collection dirty since warnings never generate validation changes
        Messages.Add(new ValidationMessage {Message = warningMessage, Warning = true});
    }
}

Basically the only tricks to this class is that I only allow the creation of the internal list of ValidationMessages to be handled by the same assembly. I also appended factory methods to allow manual insertion of errors or warnings. The reason for this is in my workings with EntLib VAB was that the results were inflexible in letting me append some messages myself and then roll the results down to the screen. This resulted in me having to create marshaling classes to just transfer the messages from the results to a collection that I could add more information to.

Implementing a concrete validator, the EmployeeValidator:

public class EmployeeValidator : IValidator<Employee>
{
    #region Implementation of IValidation<Employee>

    public ValidationResult Validate(Employee employee)
    {
        return Validate(employee, false);
    }

    public ValidationResult Validate(Employee employee, bool suppressWarnings)
    {
        var result = new ValidationResult();

        //This code here would be replaced with a validation rules engine later

        if (employee != null)
        {
            if (!suppressWarnings && employee.HireDate > DateTime.Now)
                result.Messages.Add(new ValidationMessage {
                    Message = string.Format("Employee hire date: {0} is set in the future.", employee.HireDate),
                    Warning = true});

            if (employee.Person != null)
            {
                if (string.IsNullOrEmpty(employee.Person.FirstName))
                    result.Messages.Add(new ValidationMessage {Message = "Employee FirstName is required."});
                if (string.IsNullOrEmpty(employee.Person.LastName))
                    result.Messages.Add(new ValidationMessage {Message = "Employee LastName is required."});
            }
            else
                result.Messages.Add(new ValidationMessage {Message = "Employee person data is missing."});
        }
        else
            result.Messages.Add(new ValidationMessage {Message = "Employee data is missing."});

        return result;
    }

    #endregion
}

Nothing really complicated goes on here just simple very basic validation code that rolls in error messages if needed. This area here would be replaced by a ruleset engine later on, for myself atleast. Otherwise you could do any validation you wanted here.

Now to actually validate your objects I created a ValidationFactory method also simliar to the VAB.

public static class ValidationFactory
{
    public static ValidationResult Validate<T>(T obj)
    {
        try
        {
            var validator = ObjectFactory.GetInstance<IValidator<T>>();
            return validator.Validate(obj);
        }
        catch (Exception ex)
        {
            var messages = new List<ValidationMessage> {new ValidationMessage {
                Message = string.Format("Error validating {0}", obj)}};

            messages.AddRange(FlattenError(ex));

            var result = new ValidationResult {Messages = messages};
            return result;
        }
    }

    private static IEnumerable<ValidationMessage> FlattenError(Exception exception)
    {
        var messages = new List<ValidationMessage>();
        var currentException = exception;

        do
        {
            messages.Add(new ValidationMessage {Message = exception.Message});
            currentException = currentException.InnerException;
        } while (currentException != null);

        return messages;
    }
}

Once again beauty comes with simplicity I take advantage of StructureMap to handle my dependency injection with the GetInstance method. Then just call Validate. I added a helper method that will allow me to roll out a complex exception message (most likely it’d only ever be you forgot to register a validator for some type) if any occur.

Registering this for StructureMap is extremely simple inside you registry setup for SM you would just add

ForRequestedType<IValidator<Employee>>().TheDefaultIsConcreteType<EmployeeValidator>();

And then onto a quick usage example

[Test]
public void InvalidEmployeeTest()
{
    var employee = new Employee {Person = new Person {FirstName = string.Empty, LastName = string.Empty}};

    var results = ValidationFactory.Validate(employee);

    Assert.IsNotNull(results);
    Assert.IsFalse(results.Valid);
    Assert.IsTrue(results.Messages.Count > 0);
}

At this point you have en entirely decoupled validation framework that will allow you to validate your objects with any kit, ruleset engine, or static validation you wish. Now if you wondered where I would put this in my architecture I would have it validate at the presenter level right after the screen scrape of data.

public bool SaveEmployee()
{
    var employee = View.Employee;

    var results = ValidationFactory.Validate(employee);

    if (results.Valid)
        _controller.SaveEmployee(employee);
    else
        View.Errors = results.Messages;
}

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

February 3, 2009

20,000 views!

Filed under: Off Topic — Tags: — dotnetchris @ 1:49 pm

Wow, I honestly feel pride. A year ago when I started my blog I never imagined this is where it would be at today. At first I started it to share the information I learned about the problems I faced with Oracle since I spent over 3 days trying to accomplish a simple task of writing an xml string to oracle over 2,000 characters! When I initially wrote that post, my blog had the only conclusive answer that I could find as I had to spend lots of time searching both java and microsoft forums related to oracle to get any information.

Since then I’ve watched my blog grow from a handful of visitors and a few comments to 20,000 views and over 100 comments. I want to thank everyone of you that’s taken the time to read any of rantings or design ideas and I especially want to thank every person that has taken the time to offer input on anything I’ve wrote. See you all again at 50,000!

BloggingContext.ApplicationInstance.CompleteRequest();

StructuredWeb Alpha 1

After my long road down the rabbit hole of object orientated design, inversion of control, NHibernate, Fluent NHibernate I’ve finally reached a point where I feel my codebase is stable enough to almost warrant my beta 1 release. I switched from Unity as my DI container to StructureMap and definitely feel this was a good call especially the timing of the 2.5.3 release of StructureMap where it natively includes the BuildUp method and natively includes the functionality I had to add with custom lifetime managers for wrapping my objects into the HttpContext and HtttpSession.

Just recently I published my implementation of Business Conversation per Transaction session management along with my repository pattern I followed for StructuredWeb. I still haven’t gotten my second level caching for NHibernate running yet but that will on slate for Beta 2.

See my StructuredWeb Installation page for details for setting it up.

This still needs a little bit of work for me to qualify it as a beta but since I checked everything into Assembla I figured I’d announce it’s alpha release since the code is already available online.

BloggingContext.ApplicationInstance.CompleteRequest();

January 28, 2009

Creating a common generic and extensible NHiberate Repository

In my previous post Conversation Per Business Transaction using PostSharp and IoC I dealt with the session management aspect of NHiberate however by the end of my development of the business conversation aspect I realized that my current data provider scheme created a lot of duplicate code. As we all know any code that is duplicated becomes a nightmare to maintain so I went through and refactored first a truly generic repository.

public interface IRepository<T>
{
    ICriteria GetAll();
    T Get<U>(U id);
    void Save(T obj);
    ICriteria GetRange(int resultSet, int rangeSize);
}

This is a rather basic interface that will handle the most common operations to my data providers, currently it can handle getting all of the items in my database for a type, a page collection into the list of items in my database, get a specific item and save a new item (or update an existing item). The only minorly unsightly part is the Get<U> method this just allows passing any type of ID instead of declaring it as int statically.

On to implementing the interface:

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

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

    #region IRepository<T> Members

    ICriteria IRepository<T>.GetAll()
    {
        return _conversation.Session.CreateCriteria(typeof (T))
            //.SetCacheable(true)
            //.SetCacheMode(CacheMode.Normal)
            ;
    }

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

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

    ICriteria IRepository<T>.GetRange(int resultSet, int rangeSize)
    {
        return _conversation.Session.CreateCriteria(typeof (T))
            //.SetCacheable(true)
            //.SetCacheMode(CacheMode.Normal)
            .SetFirstResult(resultSet*rangeSize)
            .SetMaxResults(rangeSize - 1)
            ;
    }

    #endregion
}

This class contains rather basic interactions with NHiberate, if you’re not familiar with the CreateCriteria querying method in NHibernate take a look at Chapter 12. Criteria Queries. Other than that I can at an application level enable or disable output caching for my generic repository, currently I’m still working on getting my second level caching implementation working so right now I have it disabled as you can see it’s commented out.

By returning the ICriteria from the repository it allows us to pass on the full power of NHibernate and allow us to create further data provider specific queries.

Next I created an abstract base class for my actual data providers:

public abstract class DataProviderBase<T>
{
    protected readonly IConversation _conversation;
    protected readonly IRepository<T> _repoistory;

    protected DataProviderBase(IConversation conversation)
    {
        _conversation = conversation;
        _repository = new Repository<T>(_conversation);
    }
}

This base class just holds the fields for the business conversation (or ISession) and my newly created generic repository. Now on to my true concrete implementation of my data provider:

public class EmployeeDataProvider : DataProviderBase<Employee>, IEmployeeDataProvider
{
    [InjectionConstructor]
    public EmployeeDataProvider(IConversation conversation) : base(conversation)
    {
    }

    #region IEmployeeDataProvider Members

    IList<Employee> IEmployeeDataProvider.GetAll()
    {
        return _repository.GetAll().List<Employee>();
    }

    IList<Employee> IEmployeeDataProvider.GetRange(int resultSet, int rangeSize)
    {
        return _repository.GetRange(resultSet, rangeSize).List<Employee>();
    }

    Employee IEmployeeDataProvider.Get(int employeeId)
    {
        return _repository.Get(employeeId);
    }

    void IEmployeeDataProvider.Save(Employee employee)
    {
        _repository.Save(employee);
    }

    IList<Territory> IEmployeeDataProvider.GetTerritories()
    {
        return _conversation.Session.CreateCriteria(typeof (Territory)).List<Territory>();
    }

    #endregion
}

In this class we have the delegation of the IRepository (sitting in the abstract base) and we also have direct access to the NHibernate Session so we can add further methods of any kind. This also allows us the flexibility if you’d rather the EmployeeDataProvider had GetEmpoyees() instead of GetAll() it would allow that easily.

Since the repository itself is not exposed at the provider level this allows us to return the actual results in anyway we want. It allows us to further modify the basic queries by adding NHibernate where clauses to the Criteria if we so choose. Since the actual ICriteria won’t be exposed outside of the data provider we don’t need to worry about client interactions causing database usage. This would also allow us if we added NHibernate LINQ to not be concerned with returning the Queryable results for the same reason.

This pattern would also work directly with LINQ2SQL / LINQ2Entities / DLINQ by changing where the NHibernate session is dealt with and using your entity provider. I feel this is a perfect to the data access patern as it protects the code from becoming too unweilding by basing all communication directly through the ICriteria and giving our data providers concrete result lists.

Let me know what you think!

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

January 27, 2009

Conversation Per Business Transaction using PostSharp and IoC

Earlier this month I encountered the notion of the Conversation per Business transaction paradigm for NHibernate session management as the overrall successor to the session per request pattern. With my exploration on this topic I found it quite confusing to implement in the only existing examples of it. Which is why I wrote a simple version for myself leveraging inversion of control and PostSharp.

Firstly,  everything drives off an IConversation:

public interface IConversation
{
    void Start();
    void Pause();
    void Resume();
    void End();
    void Abort();
    ISession Session { get; }
}

The conversation is a fairly simple idea, just as in a real life conversation you have a start to it, you can pause the conversation (which is how to commit the conversations), resume the conversation, end the conversation and abort the conversation. Imagine the scenario of a school class and students who have learning commited to their memory. A day could follow a similar context as this:

8:00 Class starts
Math is taught, Science is taught
12:00 Class is paused for recess (all information is committed)
13:00 Class is resumed
Creationism is taught, but realized to be made up and Class is aborted
14:00 Class is started again
More subjects are taught
15:00 Class is ended and all information flushed to students long term memory.

This example is fairly contrived but if you replace students with the database and act of class being taught with the conversation it should be pretty clear a flow that could occur over a single session for a conversation.

Next is the actual implementation of the Conversation class.

public class Conversation : IConversation, IDisposable
{
    private readonly INHibernateSessionManager _sessionManager;

    public ISession Session { private set; get; }

    [InjectionConstructor]
    public Conversation(INHibernateSessionManager sessionManager)
    {
        _sessionManager = sessionManager;
    }

    /// <summary>
    /// Starts this instance.
    /// </summary>
    public void Start()
    {
        if (Session != null && (Session.IsOpen || Session.IsConnected))
        {
            Abort();
        }
        Session = _sessionManager.GetSession(FlushMode.Never);
        Resume();
    }

    /// <summary>
    /// Pauses this instance.
    /// </summary>
    public void Pause()
    {
        Commit(Session);

    }

    /// <summary>
    /// Resumes this instance.
    /// </summary>
    public void Resume()
    {
        if (Session == null)
            Start();

        if (Session == null)
            throw new AccessViolationException("Session could not be created");

        if (!Session.IsConnected)
        {
            Session.Reconnect();
        }
        Session.BeginTransaction();
    }

    /// <summary>
    /// Ends this instance.
    /// </summary>
    public void End()
    {
        if (Session == null || !Session.IsOpen) return;

        FlushAndCommit(Session);
        Session.Close();
    }

    /// <summary>
    /// Aborts this instance.
    /// </summary>
    public void Abort()
    {
        if (Session == null || !Session.IsOpen) return;

        if (Session.Transaction != null && Session.Transaction.IsActive)
        {
            Session.Transaction.Rollback();
        }
        Session.Close();
    }

    /// <summary>
    /// Commits the specified session.
    /// </summary>
    /// <param name="session">The session.</param>
    private static void Commit(ISession session)
    {
        if (session.Transaction != null && session.Transaction.IsActive)
        {
            session.Transaction.Commit();
        }
    }

    /// <summary>
    /// Flushes the and commit.
    /// </summary>
    /// <param name="session">The session.</param>
    private static void FlushAndCommit(ISession session)
    {
        if (session.Transaction == null || !session.Transaction.IsActive) return;

        session.Flush();
        session.Transaction.Commit();
    }

    #region Implementation of IDisposable

    public void Dispose()
    {
        End();
    }

    #endregion
}

This class is a little bit long but nothing is that complex and I think every method is very straight forward. I’m going to skip over a few things that are not needed for understanding what this class does. The INHibernateSessionManager is an interface to a class that is a basically a wrapper to NHibernate’s ISessionFactory. For all intensive purposes this class could be ISessionFactory instead and the implementation wouldn’t change other than it would be session = Factory.OpenSession(); session.FlushMode = FlushMode.Never;

The InjectionConstructor attribute is a Microsoft Unity (Inversion of Control framework) specific convention that informs Unity to inject the NHibernate SessionFactory dependency into a Conversation anytime it is created. Unity will store a singleton copy of the SessionFactory for the life of the application.

Next up is the DataProvider class that will actually use the Conversation to talk to the database physically.

public class EmployeeDataProvider : IEmployeeDataProvider
{
    private readonly IConversation _conversation;

    [InjectionConstructor]
    public EmployeeDataProvider(IConversation conversation)
    {
        _conversation = conversation;
    }

    IList<Employee> IEmployeeDataProvider.GetEmployees()
    {
        return _conversation.Session.CreateCriteria(typeof (Employee)).List<Employee>();
    }
}

This is a very basic method that is used with NHiberate, it’s the syntax to get a list of objects from the database. I have some other methods in my provider but the code is less important now onto calling the provider.

[Test]
[BusinessConversation]
public void BusinessConversationTest()
{
    const int id = 9;
    var employee = _provider.GetEmployee(id);
    Assert.IsNotNull(employee);

    var employees = _provider.GetEmployees();
    Assert.IsTrue(employees.Count > 0);

    var territories = _provider.GetTerritories();
    Assert.IsTrue(territories.Count > 0);
}

In the setup call for this test Unity will resolve the _provider and assign it a Conversation which has the SessionFactory in it for opening the session. The same session is used for each of the calls to the database and committed as a single transaction when the method exits. This is done automagically by PostSharp.

PostSharp is an aspect orientated programming framework that allows you to create attributes can trigger methods before entering a method with the attribute and after exiting. The code for the BusinesConversation attribute is

[Serializable]
public sealed class BusinessConversation : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        var container = HttpContext.Current != null ?
            HttpContext.Current.Application.GetContainer() : UnityTestContainer.Instance;
        var conversation = container.Resolve<IConversation>();
        conversation.Resume();
    }

    public override void OnExit(MethodExecutionEventArgs eventArgs)
    {
        var container = HttpContext.Current != null ?
            HttpContext.Current.Application.GetContainer() : UnityTestContainer.Instance;
        var conversation = container.Resolve<IConversation>();
        conversation.Pause();
    }
}

Now this has some Unity specific code in it where it calls to the container to resolve the Conversation but the important part is that OnEntry to a method with the BusinessConversation attribute the conversation is resumed. This will either resume an existing conversation that’s stored in the session or it will create a new one. When it exits the method the conversation is paused which commits the transaction to the database.

The other code where it does resolution checking on HttpContext or reads from my UntityTestContainer does not really make me happy and eventually will be refactored to be cleaner in one way or another. But this code would be specific to how you interact with your container that would store the Conversations.

The only other issue I have with any of this is exposing the Session from the Conversation, I couldn’t figure out a simplier way for allowing my data providers to actually interact with the session to physically hit the database otherwise. I considered instead of a Conversation containing a session to actually make it implement ISession and assign it to itself during the creation but that didn’t sound right to me even more so.

I’d be grateful for any feedback on my implementation here: good, bad or indifferent. I feel I’ve finally put together a clean simple to understand post on how to correctly manage NHibernate’s session that doesn’t require implementing the UnitOfWork pattern and leverages dependency injection to keep the code seperated and decoupled as much as possible. The full source to my project as always can be found on my Assembla page.

kick it on DotNetKicks.com

Shout it

BloggingContext.ApplicationInstance.CompleteRequest();

January 16, 2009

Working with DataTables/Datarows

Filed under: Programming — Tags: , , , , , , , — dotnetchris @ 6:21 pm

Sadly the project I am on at work is all circa 2005 standards where everything is DataTables and Data Adapters etc. These classes are an incredibly annoying “feature” to work with and are just brutal since it’s impossible to ever have a good domain design with them. But I wrote this class to make life easier to deal with them. It uses .net 3.5 extension methods but with a few minor changes it will run on .net 2.0. Some of the basis of this code for the ChangeType method came from QueryString Candy – Could Rot Your Teeth however I’ve added my own touches to it.

Here’s my extension method class:

///<summary>
/// Extension methods for manipulating DataRows
///</summary>
public static class DataRowUserExtensions
{
    /// <summary>
    /// Determines whether [is empty string] [the specified data row].
    /// </summary>
    /// <param name="dataRow">The data row.</param>
    /// <param name="key">The key.</param>
    /// <returns>
    ///   <c>true</c> if [is empty string] [the specified data row]; otherwise, including DBNull, <c>false</c>.
    /// </returns>
    public static bool IsEmptyString(this DataRow dataRow, string key)
    {
        if (dataRow.Table.Columns.Contains(key))
            return !dataRow.IsNull(key) && dataRow[key].ToString() == string.Empty;

        throw new ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    /// <summary>
    /// Determines whether the specified data row is null.
    /// </summary>
    /// <param name="dataRow">The data row.</param>
    /// <param name="key">The key.</param>
    /// <returns>
    ///   <c>true</c> if the specified data row is null; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNull(this DataRow dataRow, string key)
    {
        if (dataRow.Table.Columns.Contains(key))
            return dataRow[key] == null || dataRow[key] == DBNull.Value;

        throw new ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    /// <summary>
    /// Determines whether [is null or empty string] [the specified data row].
    /// </summary>
    /// <param name="dataRow">The data row.</param>
    /// <param name="key">The key.</param>
    /// <returns>
    ///   <c>true</c> if [is null or empty string] [the specified data row]; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNullOrEmptyString(this DataRow dataRow, string key)
    {
        if (dataRow.Table.Columns.Contains(key))
            return dataRow.IsNull(key) && dataRow.IsEmptyString(key);

        throw new ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    /// <summary>
    /// Gets the specified data row.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataRow">The data row.</param>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static T Get<T>(this DataRow dataRow, string key)
    {
        if (dataRow.Table.Columns.Contains(key))
        {
            // If we're trying to convert an empty string to string return the string instead
            // default(string) which is null, otherwise return null if dataRow IsNullOrEmptyString
            // else convert
            return typeof (T) == typeof (string) && dataRow.IsEmptyString(key)
                ? (T) dataRow[key] : (dataRow.IsNullOrEmptyString(key)
                ? default(T) : (T) ChangeTypeTo<T>(dataRow[key]));
        }

        throw new ArgumentOutOfRangeException(key, dataRow, "does not contain column");
    }

    /// <summary>
    /// Changes the type to.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    private static object ChangeTypeTo<T>(this object value)
    {
        if (value == null)
            return null;

        Type underlyingType = typeof (T);
        if (underlyingType == null)
            throw new ArgumentNullException("value");

        if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
        {
            var converter = new NullableConverter(underlyingType);
            underlyingType = converter.UnderlyingType;
        }

        // Guid convert
        if (underlyingType == typeof (Guid))
        {
            return new Guid(value.ToString());
        }

        // Check for straight conversion or value.ToString conversion
        var objType = value.GetType();

        // If this is false, lets hope value.ToString can convert otherwise exception
        bool objTypeAssignable2typeT = underlyingType.IsAssignableFrom(objType);

        // Do conversion
        return objTypeAssignable2typeT ? Convert.ChangeType(value, underlyingType)
                                                        : Convert.ChangeType(value.ToString(), underlyingType);
    }
}

Usage example:

ds.Tables[0].Rows[0].Get<DateTime?>("SomeDate")

Basically what is going first it checks to make sure that “SomeDate” is an actual column inside the DataRow, then it checks to make sure dr["SomeDate"] isn’t null, DBNull or an empty string.

Inside of the ChangeType method it will then resolve whether <T> is an object or a nullable object. If it’s a nullable object it will find the actual object type.

Next we do an outside check to see if it’s a Guid (since Convert.ChangeType can’t handle guids) and if it is to return the guid or it will bubble up an exception of underlyingType == typeof(Guid) and value is not a valid guid.

After that the actual conversion occurs first it checks if the type of value is Assignable To underlyingtype, if it is then it will do the Convert.ChangeType. If it’s not assignable we’re going to hope the string representation of value can be converted to type T otherwise it will fail. This second case is useful if you want to get the string representation of a number or date. As with the previous example:

ds.Tables[0].Rows[0].Get<string>("SomeDate")

Will return the string value of the SomeDate value instead of raising an exception if we didn’t have the second condition of the return statement there.

Hope this helps some of you out as much as it does me!

BloggingContext.ApplicationInstance.CompleteRequest();

January 14, 2009

Method to determine if data range contains a leap year

Filed under: Programming — Tags: , , — dotnetchris @ 7:17 pm

Update 1/14/2008: I pulled a Microsoft zune! My leap check was actually off by 1. Corrected algorithm

As I was going through some of code I previously worked on today I came across this method I wrote a while ago. I’m not too sure  if it will help anyone else but I figured I’d throw it up here. Basically I had a need to figure out if a date entered was inside a period of time in the future (in my case specifically 2.5 years and 3.0 years in the future). My original plan was to just check if number of days fit in between 365*2.5  and 365*3 but I realized as rare of a possiblity as it was a potential leap year could have foiled my plans.

So basically I wrote this method for me to be able to calculate if I need to add another day to my range to make sure they weren’t short changed a day because leap year occurred.

I’d love to hear your opinions on this code if there is anything you’d do differently.

/// <summary>
/// Determines if the DateRange contains a leap year.
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <returns></returns>
private static bool DateRangeContainsLeapYear(DateTime startDate, DateTime endDate)
{
  if (startDate > endDate)
    throw new InvalidDataException("startDate must be less than or equal to endDate.");

  //Bounds check Feb will exist either in start of the first time span date
  //or at the end of the last date potentially
  if (startDate.Month < 3 && DateTime.IsLeapYear(startDate.Year))
    return true;
  if ((endDate.Month > 3 || (endDate.Month == 2 && endDate.Day == 29))
&& DateTime.IsLeapYear(endDate.Year))
    return true;

  //Start year can't be leap year otherwise we're done
  int startYear = startDate.Year + 1;

//Upper bounds will be handled by i < endYear
  int endYear = endDate.Year;

  for (int year = startYear; year < endYear; year++)
  {
    if(!DateTime.IsLeapYear(year)) continue;
    return true;
  }

  return false;
}

BloggingContext.ApplicationInstance.CompleteRequest();

January 13, 2009

Adding Inflector to UnityWeb

Filed under: UnityWeb — Tags: , , , — dotnetchris @ 8:20 pm

Today as I was browsing the Fluent NHibernate discussion boards I was reading the post regarding features that the creators of the S#arp Architecture were interested in seeing.

One of the things that was pointed out was that FH doesn’t include a pluralizer which can make convention mapping problem matic.

Take my current AutoPersistanceModel

var persistenceModel = AutoPersistenceModel.MapEntitiesFromAssemblyOf<Employee>()
.WithConvention(c => c.DefaultLazyLoad = false)
.WithConvention(convention =>   convention.GetTableName = type => type.Name + "s")
.WithConvention(convention => convention.GetPrimaryKeyNameFromType = type => type.Name + "ID")
.WithConvention(convention => convention.GetForeignKeyName = prop => prop.Name + "ID")
.WithConvention(convention=>convention.DefaultCache = cache => cache.AsReadWrite())
.WithConvention(c => c.OneToManyConvention = m =>
                                                 {
                                                     m.Cascade.All();
                                                     m.LazyLoad();
                                                 })
.ForTypesThatDeriveFrom<Category>(autoMap =>
                                      {
                                            autoMap.WithTable("Categories");
                                          autoMap.Map(p => p.Name, "CategoryName");
                                      })
.ForTypesThatDeriveFrom<Territory>(autoMap =>
                                       {
                                             autoMap.WithTable("Territories");
                                           autoMap.Map(p => p.Description, "TerritoryDescription");
                                           autoMap.Map(p => p.Region,
 "RegionID").CustomTypeIs(typeof (Region));
                                       })
;

In more than 1 senario I need to force the autoMap to use the correct spelling of a table name instead of just being able to append S on it. With Inflector I can get a much cleaner map and only to have:

var persistenceModel = AutoPersistenceModel.MapEntitiesFromAssemblyOf<Employee>()
.WithConvention(c => c.DefaultLazyLoad = false)
.WithConvention(convention =>   convention.GetTableName = type => Inflector.Pluralize(type.Name))
.WithConvention(convention => convention.GetPrimaryKeyNameFromType = type => type.Name + "ID")
.WithConvention(convention => convention.GetForeignKeyName = prop => prop.Name + "ID")
.WithConvention(convention=>convention.DefaultCache = cache => cache.AsReadWrite())
.WithConvention(c => c.OneToManyConvention = m =>
                                                 {
                                                     m.Cascade.All();
                                                     m.LazyLoad();
                                                 })
.ForTypesThatDeriveFrom<Category>(autoMap =>
                                      {
                                          autoMap.Map(p => p.Name, "CategoryName");
                                      })
.ForTypesThatDeriveFrom<Territory>(autoMap =>
                                       {
                                           autoMap.Map(p => p.Description, "TerritoryDescription");
                                           autoMap.Map(p => p.Region,
 "RegionID").CustomTypeIs(typeof (Region));
                                       })
;

You can download Inflector and it’s source over at Andrew Peter’s blog Inflector.NET.

On a further note I believe I’ve learned how to remove the need to have the specific mappings for my enum properties, Name property and Description property which will significantly reduce the code noise of the auto mapping which will show up soon in another blog bost.

Older Posts »

Blog at WordPress.com.