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

Pretty URLs, Separation of Layers and O/R Mapping in Web Forms ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
4.47/5 (14 votes)
12 Sep 200732 min read 86.8K   493   87  
Implementing multi-tier architecture in a web application using ASP.NET 2.0
using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using System.IO;
using System.ComponentModel;




namespace Routing.Module
{
    /// <summary> 
    ///      
    /// </summary> 
    public sealed class RoutingClass : IHttpModule
    {
        public static readonly string KEY = "NHibernateSession";
       
        
        public void Dispose() { }

        public void Init(HttpApplication context)
        {            
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.PostAcquireRequestState += new EventHandler(context_PostAcquireRequestState);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        private void context_BeginRequest(object sender, EventArgs e)
        {
            string ext = Path.GetExtension(HttpContext.Current.Request.FilePath).ToLower();

            if (Utils.Utils.IsNotStaticContent(ext) && Utils.Utils.IsNotWebResource(ext))                             // to speed up loading
            {
                HttpApplication application = (HttpApplication)sender;
                HttpContext context = HttpContext.Current;   
                context.Items[KEY] = getFactory().OpenSession(); 
                //Rewrites Url 
                RewriteUrlClass RewriteUrl = new RewriteUrlClass();
                RewriteUrl.RewriteToCustomUrl();
                //  log4net.Config.XmlConfigurator.Configure(); //initalize log4net
            }
        }
           

        private void context_PostAcquireRequestState(object sender, EventArgs e)
        {
            /// <summary> 
            /// On PostAcquireRequestState session state is available
            /// therefore controller can access session data !!!
            /// On BeginRequest we called RewriteToCustomUrl  method which:
            /// rewrote url,created and stored controller instance in the Factory.
            /// Here we do one more thing: we call a setter (in PrefetchData method)
            /// of the Controller which
            /// fetches the data for the view (when Viewstate is disabled)
            /// We also attach Page_Prerender event handler to the PreRender
            /// event of the current page being executed. This way a message can 
            /// be displayed by a view on GET request coming  from a controller 
            
            /// </summary> 
            
            string Ext = Path.GetExtension(HttpContext.Current.Request.FilePath).ToLower();

            if (Utils.Utils.IsNotStaticContent(Ext) && Utils.Utils.IsNotWebResource(Ext)) // to speed up loading, if  static content do not enter
            {
                PrefetchData();

                if (Utils.Utils.IsGetRequest)
                {
                    System.Web.UI.Page CurrentPage = (System.Web.UI.Page)HttpContext.Current.Handler;
                    CurrentPage.PreRender += new EventHandler(Page_PreRender);
                }
            }
        }

        private void Page_PreRender(object sender, EventArgs e)
        {
            //on this event a message is posted on the current page if any
            //message is stored in the Factory in an instance variable

            MVC.Views.IGeneralView InvokeMethod = sender as MVC.Views.IGeneralView;
            if (InvokeMethod != null)
            {
                InvokeMethod.Alert(MVC.Factories.Factory.PointerToFactory.Message); //message stored in  the Factory
                MVC.Factories.Factory.PointerToFactory.Message = "";                 //clear a message so other pages do not display it
            }
        }

        private  void PrefetchData()
        {
            //this  methods pre-fetches the data for a view when 
            // a viewstate is disabled
            // we do it  by  calling a setter 
            // of the Controller. Setter is empty when viewstate is on
            // or contains code when viestate is off. 
            // We call setter regardless.
            

            PropertyDescriptorCollection PropsOfController;

            PropertyDescriptorCollection PropsOfFactory;
            PropertyDescriptor PropertyGet,
                              PropStoresController;
            System.Type TypeOfController;

            System.Type TypeOfFactory;

            String WhichController = (String)HttpContext.Current.Items["action"];

            TypeOfController = System.Type.GetType(@"MVC.Controllers." +
                                        Utils.Utils.UCFLetter(WhichController) + "Controller");

            PropsOfController = TypeDescriptor.GetProperties(TypeOfController,Utils.Utils.ActionProperties);  

            if ((string)HttpContext.Current.Items["method"] == "")
            {
                PropertyGet = PropsOfController[WhichController];  //determine property of Controllrt
            }                                                      //based on Url
            else
            {
                String WhichMethod = (String)HttpContext.Current.Items["method"];
                PropertyGet = PropsOfController[WhichMethod];
            }

            TypeOfFactory = System.Type.GetType("MVC.Factories.Factory");    //get type of Factory
            PropsOfFactory = TypeDescriptor.GetProperties(TypeOfFactory,Utils.Utils.ControllerInstanceProperties);   ////get props of Factory
            PropStoresController = PropsOfFactory[Utils.Utils.UCFLetter(WhichController)
                                                 + "Controller"];   //get the property which stores  controller
            
            //Call the setter of property (value does not matter=null is fine) determined  from Url.
            //This is instance property of Factory which we can access with ComponentModel.
            
            PropertyGet.SetValue(PropStoresController.GetValue(MVC.Factories.Factory.PointerToFactory), null);

        }

                       
        private void context_EndRequest(object sender, EventArgs e)
        {
            //  closes a session at the end of a request

            string ext = Path.GetExtension(HttpContext.Current.Request.FilePath).ToLower();

            if (Utils.Utils.IsNotStaticContent(ext))                                // to speed up loading
            {                                                              // do not go through this 
                // in case of any of these exts.
            
                HttpContext context = HttpContext.Current;  

                ISession TempSession = context.Items[KEY] as ISession; 
                if (TempSession != null)  
                {
                    try
                    {
                       TempSession.Flush();  
                       TempSession.Close();  
                    }
                    catch { }
                }
                context.Items[KEY] = null;
            }
        }





        private static ISessionFactory factory = null;  //is static that is fine, all users can share it
        private static ISessionFactory getFactory() // asigns factory and returns it after
        {
            if (factory == null)
            {
                Configuration config;
                config = new Configuration();

                string ResXmlLocation = @"~/App_Data/Resources/";
                string basePath = System.Web.HttpContext.Current.Server.MapPath(ResXmlLocation);
                string[] GetResourcesFiles = Directory.GetFileSystemEntries(basePath);

                // cfg.AddXmlFile(basePath + "YourObject.hbm.xml");
                foreach (string SingleXml in GetResourcesFiles)
                {
                    config.AddXmlFile(SingleXml);
                }



                if (config == null)
                {
                    throw new InvalidOperationException("NHibernate configuration is null.");
                }
                config.AddAssembly("App_Code");
                factory = config.BuildSessionFactory();
                if (factory == null)
                {
                    throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
                }
            }
            return factory;

        }

        public static ISession NHibernateCurrentSession
        {
          
            get
            {
                if (HttpContext.Current == null)
                {
                    HttpContext.Current.Items[KEY] = getFactory().OpenSession();
                    return HttpContext.Current.Items[KEY] as ISession;

                }
                else
                {
                    HttpContext currentContext = HttpContext.Current;
                    ISession TempSession = currentContext.Items[KEY] as ISession;
                    if (TempSession == null)
                    {
                        TempSession = getFactory().OpenSession();
                        currentContext.Items[KEY] = TempSession;
                    }
                    return TempSession;
                }
            }
        }

    }
}   
 

       

        
    

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer iPay, Elizabethtown,Ky
United States United States
After defending his PhD thesis in 2005 (computational nuclear physics) at Vanderbilt in Nashville, the author decided to pursue a career in software development. As a long time open source advocate, he started with writing web applications using Linux-Apache-MySql-P (LAMP) framework. After that experience, he decided to embrace Microsoft technologies.
Currently working as a web developer in .NET platform in the online payments company.

Comments and Discussions