Click here to Skip to main content
15,891,204 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 87K   493   87  
Implementing multi-tier architecture in a web application using ASP.NET 2.0
using System;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Text.RegularExpressions;
using System.ComponentModel;             //instead of System.Reflection
using MVC.Factories;





/// <summary>
/// Summary description for RewriteUrl
/// </summary>


public class RewriteUrlClass
{
    //Class responsible for a routing process for given a URL
    // Except routing a proper controller (inferred from Url) is also created here and
    // stored in the Factory.  


    //Private fields shared among "RewriteToCustomUrl" and "InitalizeController" methods

   
    private String WhichController;           //name  of a  Controller inferred from Url
                                              // is set in  RewriteToCustomUrl
                                              // needed by InitalizeController

    private String ViewToRender = null;       // name of a view to render needed by  
                                              //RewriteToCustomUrl method
                                              // is set in InitalizeController   method

    
    private Type TypeOfController;            //type of a Controller determined in 
                                              // RewriteToCustomUrl method
                                              // needed by InitalizeController method

    private PropertyDescriptor PropertyGet;   //used to determine a view, is set in    
                                              // RewriteToCustomUrl method
                                              // needed by InitalizeController method
            

    public RewriteUrlClass() //contructor
    {
    }

    public void RewriteToCustomUrl()
    {
        //this method does the routing process.
        // First URL is disected  piece by piece and
        // controller,method and so on are determined and
        // stored in Items collection (for use by views)
        //Once controller and a method are determined 
        // InitalizeController method is called
        // This methods creates controller, stores it 
        // in Factory 
              
        String MatchedMethod;            //name  of the method infered from Url
        String Url;                      //self-explanatory
        PropertyDescriptorCollection PropsOfController;  //self-explanatory

        Url = HttpContext.Current.Request.Path;
        //comment below line on shared hosting
        Url = Url.Replace(HostingEnvironment.ApplicationVirtualPath, "");
        Url = Url.ToLower().Replace(".aspx", "");
        String ReqUrlVar = Utils.Utils.ReqUrlVar;

        Regex ReqUrlVarRegex = new Regex(ReqUrlVar, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
        Match UrlMatched = ReqUrlVarRegex.Match(Url.ToLower());


        if (UrlMatched.Success)
        {
            // UrlMatched.Result("$1/$2/$3");  you can restore original url from captured groups

            String[] GetGrNames = ReqUrlVarRegex.GetGroupNames(); // get  array of named capturing groups
                                                                  // skip unuseful zero element  
            try
            {
                //cannot really refactor anything here
                if (UrlMatched.Groups["method"].Value != "") //if  method supllied
                {
                    WhichController = Utils.Utils.UCFLetter(UrlMatched.Groups["action"].Value);
                    TypeOfController = Type.GetType("MVC.Controllers." + WhichController + "Controller");
                    PropsOfController = TypeDescriptor.GetProperties(TypeOfController, Utils.Utils.ActionProperties); 
                    MatchedMethod = UrlMatched.Groups["method"].Value;
                    PropertyGet = PropsOfController[MatchedMethod]; 
                }
                else  //no method but the right controller or index
                {
                    if (UrlMatched.Groups["action"].Value == "index") //index
                    {
                        WhichController = Utils.Utils.UCFLetter(Utils.Utils.Controller);
                        TypeOfController = Type.GetType("MVC.Controllers." + WhichController + "Controller");
                        PropsOfController = TypeDescriptor.GetProperties(TypeOfController,Utils.Utils.ActionProperties); 
                        PropertyGet = PropsOfController[Utils.Utils.Controller]; 
                        HttpContext.Current.Items["action"] = WhichController.ToLower(); //store controller
                        HttpContext.Current.Items["method"] = Utils.Utils.Method;        //store method 
                    }
                    else //right controller
                    {
                        WhichController = Utils.Utils.UCFLetter(UrlMatched.Groups["action"].Value);
                        TypeOfController = Type.GetType("MVC.Controllers." + WhichController + "Controller");
                        PropsOfController = TypeDescriptor.GetProperties(TypeOfController,Utils.Utils.ActionProperties); 
                        PropertyGet = PropsOfController[WhichController.ToLower()]; 
                    }
                }


                //here we fill Context.Items with the parsed Url
                // needed for views

                if (UrlMatched.Groups["action"].Value != "index") // for index it was done above
                    foreach (String SingleGroup in GetGrNames)
                    {
                        HttpContext.Current.Items[SingleGroup] = (String)UrlMatched.Groups[SingleGroup].Value;
                    }

                InitalizeController(); // creates and stores controller, determines view
                                      

                //All that for this one line that translates pretty url into
                // physical location of a *.aspx file

                HttpContext.Current.RewritePath("~/WebPages/" + WhichController + "/" +
                                                     ViewToRender + ".aspx", false);
                

            }
            catch (Exception) // if something goes wrong 
            {

                HttpContext.Current.Response.Write("Am error occured while routing!");

            }


        }
        else //if there is no match show index.aspx
        {
            HttpContext.Current.RewritePath("~/index.aspx", false);
        }

    }

    private void InitalizeController()
    {

        //This methods creates controller, stores it 
        // in Factory 


        Factory FactoryInstance;         //self-explanatory  
        Type TypeOfFactory;              //type of a Factory
        PropertyDescriptorCollection PropsOfFactory; 

        object o = Activator.CreateInstance(TypeOfController);           //controller was created
        ViewToRender = PropertyGet.GetValue(o).ToString();      // view was determined from a controller
                                                                // for a given controller and method
                                                                // is needed by RewriteToCustomUrl method

        //here we  store the instance of the contoller in the Factory
        

        //below code  block needs  WhichController field  - was determined above

        FactoryInstance = new Factory();   //create a factory instance
        Factory.PointerToFactory = FactoryInstance; //store Factory instance in its static field
                                                    //same approach as in  Singleton pattern 

        TypeOfFactory = Type.GetType("MVC.Factories.Factory");
        PropsOfFactory = TypeDescriptor.GetProperties(TypeOfFactory,Utils.Utils.ControllerInstanceProperties); //get props of the Factory
        PropertyGet = PropsOfFactory[WhichController + "Controller"]; //get property which stores controller
        PropertyGet.SetValue(FactoryInstance, o);                     // store controller instance in Factory 

      
    }
}    





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