Click here to Skip to main content
15,892,839 members
Articles / Web Development / ASP.NET

NHibernate Best Practices with ASP.NET, 1.2nd Ed.

Rate me:
Please Sign up or sign in to vote.
4.96/5 (322 votes)
11 Jun 2008CPOL60 min read 8.6M   35.9K   1.1K  
This article describes best practices for leveraging the benefits of NHibernate 1.2, ASP.NET, generics and unit testing together.
using System;
using EnterpriseSample.Core.DataInterfaces;
using EnterpriseSample.Core.Domain;
using EnterpriseSample.Web;
using NHibernate;

/// <summary>
/// This could alternatively be hooked up via MVP; for simplicity of the sample, it's not.  See EditCustomer.aspx for a good example of MVP.
/// </summary>
public partial class AddCustomer : BasePage
{
    protected override void PageLoad() {
        if (!IsPostBack) {
            lblMessage.Text = "Use this form to add a new customer.";
        }
    }

    protected void btnAdd_OnClick(object sender, EventArgs e) {
        if (txtCustomerID.Text.Trim().Length == 5) {
            Customer newCustomer = new Customer(txtCompanyName.Text);
            newCustomer.SetAssignedIdTo(txtCustomerID.Text);
            newCustomer.ContactName = txtContactName.Text;

            ICustomerDao customerDao = DaoFactory.GetCustomerDao();

            if (!IsDuplicateOfExisting(newCustomer, customerDao)) {
                customerDao.Save(newCustomer);
                Response.Redirect("ListCustomers.aspx?action=added");
            }
            else {
                lblMessage.Text =
                    "<span style=\"color:red\">The ID you provided is already in use.</span><br />Please change the ID and try again.";
            }
        }
        else {
            lblMessage.Text =
                "<span style=\"color:red\">The ID you provide must be exactly 5 characters long.</span><br />Please change the ID and try again.";
        }
    }

    /// <summary>
    /// Checks if a customer already exists with the same customer ID.
    /// </summary>
    private bool IsDuplicateOfExisting(Customer newCustomer, ICustomerDao customerDao) {
        // Whenever possible, I *really* don't like using assigned IDs.  I think they 
        // should only be used when working with a legacy database.  Among other ugliness, 
        // assigned IDs force us to try/catch when checking for duplicates because NHibernate 
        // will throw an ObjectNotFoundException if no entity with the provided ID is found.
        // Consequently, we also have to have a reference to the NHibernate assembly from within
        // our business object.
        // To overcome these drawbacks, I'd recommend adding a DoesEntityExist(string assignedId) 
        // method to the DAO to check for the existence of entities by its assigned ID.  This would remove the
        // ugly try/catch from this method and it would also remove the local dependency on the NHibernate
        // assembly.  I've chosen not to go ahead and do this because my assumption is that
        // the use of assigned IDs will be the exception rather than the norm...so I want to keep
        // the generic DAO as clean as possible for the example demo.
        try {
            Customer duplicateCustomer = customerDao.GetById(newCustomer.ID, false);
            return duplicateCustomer != null;
        }
        // Only catch ObjectNotFoundException, throw everything else.
        catch (ObjectNotFoundException) {
            // Since the duplicate we were looking for wasn't found, then, through difficult 
            // logical deduction, this object isn't a duplicat
            return false;
        }
    }

    protected void btnCancel_OnClick(object sender, EventArgs e) {
        Response.Redirect("ListCustomers.aspx");
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions