Archives

Archives / 2007 / November
  • Remove code smell with AOP

    During the last years you have probably heard about Aspect Oriented Programming (AOP). Different people like or don’t like AOP. I’m one of them who like AOP. As you may now VB.Net and C# are object orientated languages and with object oriented programming (OOP) you want to reduce code duplication, code duplications smells badly. If you need to do code duplication you are probably doing something wrong with the implementation of your domain model. With OOP you can generally eliminating code duplication, but there are some cases where we can’t avoid it, for example take a look at this code:

    public class MyClass
    {

           public void MyBusinessMethod1()
           {
                 CheckSecurity();
                 //Place your code here
           } 

           public void MyBusinessMethod2()
           {
                 CheckSecurity ();

                 //Place your code here
           } 

           public void CheckSecurity ()
           {
                //Place the code for the security check here
           }
    }

    The code above has code duplications, where CheckSecurity method is added to each business method. This code duplication is not only painful to write, it could also make the code smell bad and make the code less maintainable. With the refactoring Move Method "A method is, or will be, using or used by more features of another class than the class on which it is defined", the CheckSecurity method could be moved into the infrastructure and the new class where the method is located will be the only place where the CheckSecurity is located. Centralization of code will make it easier to maintain the code. Even if you use the Move Method, the MyClass still use code duplication. Unfortunately, OO doesn’t help us removing the code duplication. You could of course use code generation to manually avoid adding the CheckSecurity to each method where the security check needs to be done.

    AOP crosscutting can be used to address concerns such as the security checks and of course other application specific concerns too, for example, you could make Lazy Load work without needing to have a dependency to your Repository or data mapper within the domain objects. With AOP, you could remove the code duplication from the code example above, and create a method interceptor where you add the CheckSecurity method. The following is a pseudo code of an interceptor:

    public class MySecuirtyInterceptor : MethodInterceptor
    {
          public object Invoke(MethodInvocation invocation)
          {
                CheckSecurity (); 

                //Call next interceptor
                Return invocation.Proceed();
          }
    }

    By using an AOP framework where you could define a set of methods (pointcuts) that should use the security interceptor, you could easy remove the code duplication, and remove the security concern from the developer, and add it later, if it’s required. The The MyClass in the first example could look like this if we use AOP and the MySecurityInterceptor above:

    public class MyClass
    {
           public void MyBusinessMethos1()
           {
                 //Place your code here
           }

           public void MyBusinessMethos2()
           {
                 //Place your code here
           }
    }

    Developers don’t need to add the CheckSecurity method. If we need to have a security check before executing the method, you could add a pointcut later for the methods that should call the CheckSecurity. Some sophisticated AOP frameworks can use regular expression or other wildcard syntax for the pointcuts. Pointcuts is a set of Method, Fields or Throws (When a particular exception is thrown) that should invoke the interceptor method. Those pointcuts could for example be specified within a XML file.

    You can also use AOP to do some logging or other operations before or after a method has bean invoked, or a field has been set, or even when en exception was thrown. The developer who are creating the business methods, don’t need to call a method that will for example log a message, it’s something that could be specified within an XML file. By using AOP you could solve problems that could not be done with OOP. You can not only reduce the smell of bad code, you could also reduce time it takes to add the duplication of codes etc. I hope this post gave you some more information about how you can use AOP to solve some problems that can’t be easily done with OOP.

    Read more...

  • Multiple return values, I want this in C#

    I so badly want to have support for multiple return values in C# instead of using out parameters.

    Note: The following is only an example, we can use a struct or an object to create a data structure which will hold the value, but I only use this code for demonstration purpose.

    int x,y,z;
    bool isHidden;

    GetCords("MyElement", out x, out y, out z, out isHidden);


    Instead of the code above, I want to do something like this:

    Return 10,11,10,true;

    var x,y,z,isHidden = GetCords("MyElement");

    If I don’t care about the y and z return values I can instead write:

    var x,,,isHidden = GetCords("MyElement");

    Isn’t this beautiful?

    hmm,  when I’m thinking of beauty, I start to think about "The beauty is in the eye of the beholder" ;)

    To confess something, the language LUA support this and I loved it when I created an add-on for World Of Warcraft.

    Read more...

  • Defensive programming and Design by Contract on a routine level

    “When quality is pursued, productivity follows” – K. Fujino, Vice President of NEC Cooperation’s C&C Software Development Group.

    People are talking about how to create tools (Software Factories) that will increase productivity. The view of productivity has been important. With good productivity, we could build software rapidly and that will probably save us a lot of money. But will it in the end deliver software with high quality? The productivity could make the quality be left behind, in some organizations, productivity tend to be more important than quality. It’s important to know that quality on a product (or service) is its benefit to satisfy, or preferably exceed the customers’ requirements and expectations. By putting productivity before quality, will in short term goals save money, but will in long term cost more money.

    A major component of quality in software is reliability. The software will be reliable when it performs its job according to the specification (correctness) and to handle abnormal situations (robustness).

    If we look at correctness vs robustness from a developer’s perspective, correctness is met when a developer never returns an inaccurate result. It’s better to return no results than returning an inaccurate result. With robustness a developer always tries to do something that allows the software to keep operating, even if a result could be inaccurate sometimes. For safety-critical applications, correctness is more important than robustness. For example, it’s more important that software used in a chemical plant returns no results than wrong results. For a consumer application, it could be more important to flavor robustness than correctness. It’s better to return any result than shutting down a system, for example. It is better if a program closed down instead than showing a blue screen in Windows ;)

    Reliable software has no bugs (reliability is the absence of bugs), or has it? Can software be completely free from bugs? Defensive programming and Design by Contracts will be a help to create reliable software with good correctness and/or robustness.

    Defensive Programming

    Defensive programming is about protecting yourself from being hurt by something dangerous (If bad data is sent to a routine, it will not hurt the routine). By writing code that will protect yourself from bad data, unexpected events, and other programmers mistakes, will in most case reduce bugs and create a high quality software.

    Good programmers will not let bad data through. It’s important to validate input parameters to not let the garbage in. It’s also important to make sure that if garbage does come in, noting will goes out or an exception will be thrown. The following example is a result from defensive driven programming:

    public Customer GetCustomerByName(string customerName)
    {

       //validate so no garbage is getting through
       if (String.IsNullOrEmpty(customerName))
           throw new ArgumentException("The name of the customer is empty");

       try
       {

          //Get customer from data source

          Customer customer = ....
          //Make sure the customer is not null before the use

          //of its members in the compare method.            

          if (customer != null && String.Compare(customer.CustomerName, customerName) == 0)
             return customer; 
          else
             return null;
       }
       catch
       {
          throw;
       }
    }

    In the code above the input argument is first validated, if the validation failed, an exception is thrown. If the validation passes, the routine will try to get a customer from a data source by using the value from the customerName argument. If the customer was not found, nothing will out (returns null). If the routine fails to get the customer from the data source an exception will be thrown. In the example, correctness is more important than robustness. If robustness was more important, we could return an instance of an empty customer or “introducing Null object“ [Martin Fowler].

    It’s important to both validate the input data, data returned from a data source and also use error handling to make sure a routine will not return any bad data if it fails. If the try and catch block are used, make sure an exception is passed on (thrown) and not only be catch within the catch block and then ignored, it could make the code more robustness but will violet correctness.

    When using a defensive driven programming too much, it could create problems. Too much validation codes could make the code less readable and affect performance, so don’t overuse defense driven programming. Defensive programming will make error easier to find, easier to fix, and less damage to production code. The result of using defense driven programming will in return increase the quality of the software.

    Design by Contract

    Design by Contract is about is about creating a contract between the client and the supplier. The idea of the Design by Contract theory is to associate a specification with every software elements. This specification will define a contract between client and the supplier. When a supplier writes a contract with the client, it should document the obligations and benefits. When a client makes a call to the supplier, the supplier makes sure that the client follows the contract, this could be done by using precondition within a software routine (Client’s obligations to the code it calls) and postcondition (supplier’s obligations to the code that uses it). The following tabular form shows a contract between a client and its supplier, where an element is inserted into a dictionary:

                  Obligations                                        Benefits
                 (Must ensure precondition)                    (May benefit from postcondition)
    Client
                 Make sure dictionary is not full               Get the updated dictionary with the given
                 and the element is not empty and           element.
                 don’t already exists.
                 (Must ensure postcondition)                  (May assume precondition)

    Supplier
                 Add the given element to the                Throw an exception if the dictionary is full
                 dictionary.                                         or if the element is null.

    C# doesn’t have support of specifying specifications (contracts). To use Design by Contract with C# we have to simulate it. A language that uses speciation for Design By Contract, is Eiffel. The following is an example in C# where post- and precondition is used (The contract simulated in this example, is the one specified in the tabular form above):

    public void Add(object element)
    {
       //precondition (require)
       if (element==null)
          throw new ArgumentNullException("element");

       if (this.IsFull)
          throw new Exception("The dictionary is full");

       if (this[element] == element)
          throw new Exception("The element already exists within the dictionary.");

       //do
       this._dictionary.Add(element);

       //postcondition (ensure)
       If (!this._dictionary.Contains(element))
          throw new Exception("The element is not added to the dictionary.");
    }

    If a client and a supplier have agreed over a contract where the supplier promises to return a result, the supplier should ensure to fulfill its demand, and the client will know that it will have a result and don’t need to check if it’s true. If the supplier failed to fulfill its demand at the first attempt, it should retry to fulfill its demand (rescue). The following example show an example of the previous code, but where the routines will retry to add an element even if the dictionary is full (Note: this is only pseudocode used by only showing the concept, that is why the code will try to add an element to the dictionary even if each loop will probably result in the same result):

    public void Add(object element)
    {

       //precondition (require)
       if (element==null)
          throw new ArugmentNullException(element);

       if (this[element] == element)
          throw new Exception("The element already exists within the dictionary.");

       bool fail;

       //rescue and retry
       for( int i = 0; i<100; i++)
       {
          try
          {
             this._dictionary.Add(element);
             fail = false;
          }
          catch
          {
             fail = true;
          }

          //retry
       }

       if (fail)
          throw new Exception("Can’t add element because the dictionary is full");

       //postcondition (ensure)
       if (!this._dictionary.Contains(element))
          throw new Exception("The element is not added to the dictionary.");
    }

    If C# should have support of adding specification to software elements, no validation code should need to be written in the way the example shows in the previous example, instead a contract should have been written. It could look something like this, where  "requires" is the precondition and the "ensures" is the postcondition:

    public void Add(object element)
          requires element != null
               otherwise ArgumentNullException;
          requires this[element] != element
                otherwise Exception;
          requires !IsFull
                otherwise Exception;
          ensures this[element] == element
                otherwise Exception;
    {
       this._dictionary.Add(element);
    }

    The Microsoft Research has created and overview of a new language called Spec# (similar to C# but uses contract "Method Contracts"). I hope this will be added to C# in the future.

    I hope this post has given you some basic understanding about what Defense Programming and Design by Contracts is all about.

    Read more...

  • MVC - Expression Language and custom tags

    I have seen several developers that want and have no problem by using server-side code blocks in a View when they are working with the MVC pattern. But I think the server-side code block should be used only in some advanced and special occasions and instead use an Expression Language. By using a lot of server-side code block can make the View messy and the solution can be difficult to implement, form the perspective of code maintainability and extensibility. If we instead use tags similar to HTML/XML we can make the code blend into HTML in a nice way.

    Take a look at the following code:

    <% if (ViewData != null && ViewData.HasError) {%>
            ...
    <% } %>


    <% if (ViewData.ExceptionType == ExceptionType.Critical) %>
          <div class="criticalException">
              Critical Error: <%= ViewData.ExceptionMessage%>
              <% if (ViewData.InnerException != null) } %>
                 <%=ViewData.InnerException.Message%>
              <% } %>
         </div>
    <% else %>
         <div class="exception">
            Error message :<br/><%= ViewData.ExceptionMessage%>
         </div>
    <% } %>

    The above code is only used to demonstrate how messy a View can be when we have a lot of server-side code blocks. This code will not be easy for a designer or web developer to maintain. If we instead use an Expression Language (EL) and JSTL (JSP Stamdard Tag Library) for JSP in ASP.Net the View can be written like this:

    <c:if test="${ViewData!=null && ViewData.HasError}">
       ...
    </c:if>

    <c:choose>
         <c:when test="${ExceptionType == ExceptionType.Critical}">
             <div class="criticalException">
                Critical Error: <c:out value="${ViewData.ExceptionMessage}"/>
                <c:out value="${ViewData.InnerException.Message}"/>
             </div>
          <c:otherwice>
             <div class="exception">
                Error message :<br/><c:out value="${ViewData.ExceptionMessage}"/>
             </div>
           </c:otherwice>
    </c:choose>

    The best part of the ${variable} is that it can evaluate null for us, and also do the type casting, so we don’t need to write:

    <% if (ViewData.InnerException != null) } %>
            <%=ViewData.InnerException.Message%>
    <% } %>

    or:

    <%=ViewData.CustomerID.ToString()%>
     

    Instead we simply write:

    ${ViewData.InnerException.Message}

    ${ViewData.CustomerID} 

    The best part, we shouldn't event need to use the ViewData, instead directly write:

    ${CustomerID} 

    Here is an example where a property path (sub-properties) is used:

    ${Order.Rows[1].Item.Price} 

    In some cases we need some more logic to test some conditions etc, something that can’t be placed inside of a Controller. This logic can instead of being a server-code block be capsulated into an own custom tag.

    The problem with EL today is the lack of supports in tools, so we only get an error first at runt-time and some IDE don’t have support for easy handle the EL. To make it more powerful the tools need to handle it also. But I prefer this way instead of using server-side code block and I hope something similar will be added to the ASP.NET MVC Framework.

    Nikhil wrote a post about using AJAX with the ASP.Net MVC Framework (only a prototype). He uses code like this:

    <% RenderBeginAjaxForm(Url.Action("Add"),
                           new { Update="taskList, UpdateType="appendBottom
    ",
                                 Highlight="
    True
    ",
                                 Starting="
    startAddTask", Completed="endAddTask" }); %>
       <input type="text" name="name" id="nameTextBox" />
      
    <% Ajax.Watermark("nameTextBox",
                      new { watermarkText="[What do you need to do?]", watermarkCssClass="watermark"}); %>


       <input type="submit" name="addTask" value="Add Task" />
    <% RenderEndForm(); %>

    The RenderBeginAjaxForm will render a <form> element with an onClick and onSubmit attribute etc. The RenderEndForm will also add a </form> The Ajax.Watermark is a way to extend a HTML element with a WaterMarker. I think this code is kind of “messy”. I would like to see some tags instead for example:

    <ajax:Form Action="Add" Update="takstList" UpdateType="appendBottom" Hightlight="true" ...>
              <ajax:waterMarkTextBox name="name" id="nameTextBox" markerText="[What do you need to do?]".../>
    </ajax:form>

    By using this solution, tags will be nicely blended into HTML and remove server-side code and make it easy for web developers (They are used to HTML element and attribute) to simple apply it and also maintain it. We can also easy see that we have a <form> and a </form>. This looks similar to Server controls today but this should be a more light-weight control, and the runat=”server” shouldn’t be used ;) This is similar to ViewComponent shipped with MonoRail (I think ;)), but I don’t like the declaration syntax MonoRail used. I prefer to use a HTML similar way to add components (custom tags) etc.

    What kind of solution do you prefer?

    Read more...

  • ASP.Net MVC Framework - Security

    Note: This post is based on an early version of the ASP.Net MVC Framework, not the final version, so changes my happen in the future.

    When using the ASP.Net MVC Framework it will do a URL routing to route an URL to a Controller, and the Controller should execute some logic and render the Views. We can for example use an URL like /Products/Edit/1 to edit a product. By using this kind of URL we need to care about security, because we don’t want everyone to be able to edit a product. How can we prevent some users to not edit the product? We can’t use the <location> element and deny certain user for accessing the View.

    <location path="Views/Products/Edit.aspx">
       <system.web>
         <authorization>
           <deny users="*"/>
         </authorization>
       </system.web>
    </location>

    The above section will not work, well sort of; it will make sure no one can access the Edit.aspx page. But if we use the RenderView method to render a View the <location> element will not work, the View will still be rendered. So what other options do we have? When we use the MVC framework the Controllers are responsible to handle the logic and the render of Views. We can in this case add the security check into our Controllers, in this case into the Action methods. As you may know a Controller can have several actions, like Edit, Update and List etc and they can also render different Views. Maybe the List action should everyone be possible to call, but not the Edit or Update methods. So in this case we need to add the security check on the Edit and Update methods in a Controller. This can for example be done by using the Roles feature of ASP.Net:

    [ControllerAction]
    public void Edit(int? id)
    {
      if (!Roles.IsUserInRole("Admin"))
         throw new SecurityException("Access denied");
      ... 
    }

    To avoid writing this check in the Action methods we can instead use the PrincipalPermissionAttributes shipped with .Net:

    [ControllerAction]
    [PrincipalPermission(SecurityAction.Demand, Role="Admin"]
    public void Edit(int? id)
    {
       ...
    }

    If we want to make sure all Action methods in a Controller have the check, we can add the PrincipalPermissionAttribute to the Controller class:

    [PrincipalPermission(SecurityAction.Demand, Role="Admin")]
    public class HomeController : Controller

    If we want to handle the SecurityException we can use the ExceptionHandlerAttribute I wrote about in my previous post. This can catch the SecurityException and Render a View that will display the exception message.

    [ControllerAction]
    [PrincipalPermission(SecurityAction.Demand, Role="Admin"]
    [ExceptionHandler("Error", typeof(SecurityException))]
    public void Edit(int? id)
    {
       ...
    }

    If we don’t want to use the PrincipalPermissionAttribute and instead write our own Security handler, we can override the OnPreAction method and implement the security check. The OnPreAction method will be executed before any Action methods are executed.

    protected override void OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo)
    {
       if (actionName == "Edit")
       {
         if (!Roles.IsUserInRole("Admin") || !User.Identity.IsAuthenticated || !User.Identity.Name = "Administrator")
            throw SecurityException("Access denied!");
       }
    }

    Read more...

  • ASP.Net MVC Framework - Handling Exception by using an Attribute

    Note: This is based on the pre-CTP version of the ASP.Net MVC Framework and it is in an early stage.

    I got a comment on one my previous post “ASP.Net MVC Framework - Exception Handling” that the Rescue style MonoRail is a nice solution to handle Exception thrown within a Controller. In this post I have added something similar to as the Rescue feature of MonoRail (at least I think so ;)) where an attribute can be added to a Controller or on an Action. The attribute can be used to specify which View that should be rendered when an exception is thrown. We can also specify different Views based on different exceptions. Something I also added to the code is to specify something I will call an ExceptionHanlder. The ExceptionHandler is a pre handler which will be executed before the specified exception View should be rendered. The idea of the ExceptionHandler is to log exception etc.

    By using an Attribute (ExceptionHandlerAttribute) on a Controller or an Action method, we don’t need to override the OnError method of the base Controller class. I made this solution simple by only creating my own custom Controller class (N2Controller) and override the OnError method of the Controller. In this method do my exception handling process. Before I show the code I will show you how we can use the ExceptionHandlerAttribute.

    The ExceptionHandlerAttribute has three argument, exceptionHandler, viewName, exceptionType. The exceptionHandler argument is where we pass the type of the pre ExceptionHandler we want to use when an Exception is thrown. The viewName is the name of the View to render the exception information (In this sample code the view specified must be located in the Views/Exceptions folder). The exceptionType takes a type of an Exception. If we only want to make sure the Exception Handler should only handle a specific exception thrown within the Controller or Action method, we use the exceptionType argument.

    Here is an example of different use of the ExcetpionHandlerAttribute, it can be used on both the Controller’s Class and Action methods:

    1. [ExceptionHandler(“Error”);
    2. [ExceptionHandler("Error", typeof(DivideByZeroException))]
    3. [ExceptionHandler(typeof(ExceptionHandler), "Error")]
    4. [ExceptionHandler(typeof(ExceptionHandler), "Error", typeof(DividedByZeroException))
    5. [ExceptionHandler(typeof(ExceptionHandler))
    6. [ExceptionHandler(typeof(ExceptionHandler), typeof(DividedByZeroException))

    1 Will who the Error view when an exception is thrown.
    2 Will only show the Error View is the exception thrown is of type DividedByZeroException.
    3 Will Show the Error View and use a pre ExceptionHandler before the View is rendered.
    4 Will Show the Error View only if the DividedByZeroException is thrown, and use a pre ExceptionHandler before the View is rendered.
    5 Will use the ExceptionHandler when an exception is thrown.
    6 Will use the ExceptionHandler if the DividedByZeroException is thrown.

    To use ExceptionHandler we simply create a Class that implements the IExceptionHandler interface.

    public interface IExceptionHandler
    {
        void PreExceptionHandling(string actionName, Exception exception);
    }

    In the PreExceptionHandling method we could for example put logic to log an exception. The PreExceptionHandling method will be called before a View will be rendered (A View will not be rendered if it’s not specified).

    Here is an example how the ExceptionHandlerAttribute can be used:

    [ExceptionHandler("DefaultError", typeof(DivideByZeroException))]   <- Will not be used
    public class HomeController : N2Controller
    {
       [ControllerAction, ExceptionHandler("Error")]  <- Will be used
       public void Index()
       {
        
       }
    }

    The attribute specified on the action method will have more to sat than the attribute on the Controller’s class.

    [ExceptionHandler("DefaultError", typeof(DivideByZeroException))]   <- Will be used
    public class HomeController : N2Controller
    {
        [ControllerAction, ExceptionHandler("Error",typeof(IndexOutOfRangeException),typeof(ArgumentException))]  <- Will be used
        public void Index()
        {
            ...
        }
    }

    In the code above, both Exception Handler will be used. For example, if the Action method throws a DidivedByZeroException the DefaultError View will be rendered. But if the IndexOurOfRangeException or ArgumetnException is thrown the Error View will be displayed.

    Here is the implementation of my custom Controller:

    public class N2Controller : Controller
    {
        protected override bool OnError(string actionName, System.Reflection.MethodInfo methodInfo, Exception exception)
        {
            ArrayList attributes = this.GetExceptionHandlerAttribute(methodInfo);

            foreach (ExceptionHandlerAttribute attribute in attributes)
            {
               foreach (Type exceptionType in attribute.ExceptionTypes)
               {
                  if (exceptionType.IsAssignableFrom(exception.InnerException.GetType()))
                  {
                     if (attribute.ExceptionHandler != null)
                        ((IExceptionHandler)Activator.CreateInstance(attribute.ExceptionHandler)).PreExceptionHandling(actionName, exception);

                     if (!string.IsNullOrEmpty(attribute.View))
                         RenderView("~/Views/Exceptions/" + attribute.View + ".aspx", exception);
                        
                     return false;
                  }
               }
           }

           return true;
       }

       private ArrayList GetExceptionHandlerAttribute(System.Reflection.MethodInfo methodInfo)
       {
           ArrayList attributes = new ArrayList();

           attributes.AddRange(
                               methodInfo.GetCustomAttributes(
                                     typeof(ExceptionHandlerAttribute),
                                     false));

           attributes.AddRange(
                               this.GetType().GetCustomAttributes(
                               typeof(ExceptionHandlerAttribute),
                               true));
                
           return attributes;
        }
    }

    The code above is only on a prototype stage and. If no ExceptionHandlerAttribute is specified for an Action or Controller, the original ASP.Net MVC Frameowork’s OnError behavior will be used.

    Read more...

  • ASP.Net MVC Framework - Exception Handling

    Note: This post is based on an early preview version of the ASP.Net MVC Framework and much will happen until the next milestone.

    In this post I will show how we can handle errors that occur in a Controller’s Action method.
    The Controller base class has a virtual method with the name OnError, this method takes three arguments, actionName, methodInfo and exception. It also has a return type of a Boolean. The idea when using the OnError method is to return true if we have handled the exception or false to letting ASP.Net handle it for us.

    protected virtual bool OnError(string actionName, System.Reflection.MethodInfo methodInfo, Exception exception)

    When an exception is thrown within our Action method, the OnError method will be executed. In the OnError method we can for example pass information to a View.

    Here is an example of a Controller where I will Render a View called “Error” and pass the exception to the View:

    public class HomeController : Controller
    {
        protected override bool OnError(string actionName, System.Reflection.MethodInfo methodInfo, Exception exception)
        {
           RenderView("Error",exception.InnerException);
           return false;
        }

        [ControllerAction]
        public void Index()
        {
           int i = 0;
           int sum = 10 / i;

           RenderView("Index");
        }
    }

    When the Index Action method will be executed a DevidedByZero Exception will be thrown, when this happens the OnError method will be called and it will render a view and return false to specify that the error was handled.

    To make sure to have a common View for displaying the error message, we put it into the Shared subfolder of the Views folder:

    /Views
              /Shared
                    Error.aspx


    The Error View inherits the ViewData<Exception> class. To make this demo simple I just pass the Exception class to the View and show the value of the Message property:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Error.aspx.cs" Inherits="MvcApplication.Views.Error" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <div>
            <h1>Error on page</h1>
            <b><%=ViewData.Message %></b>
        </div>
    </body>
    </html>

    Read more...

  • ASP.Net MVC Framework - Creating a IRouteHandler which will support Interceptors

    I really love how extensible the ASP.Net MVC Framework is, for example the normal pipeline looks like this:

    Request -> Route (IRouteHandler) –> ControlFactory (IControllerFactory) -> Controller (IController) -> ViewFactory (IViewFactory) -> View (IView) -> Response

    By implementing my own IrouteHandler I changed the pipeline to support Interceptors before and after an action is invoked:

    Request -> Route (IRouteHandler) –> ControlFactory (IControllerFactory) -> (Pre) Interceptors (IInterceptor) -> Controller (IController) -> ViewFactory (IViewFactory) -> View (IView) -> (Post)Interceptors (Iinterceptor) -> Response

    On the Controller base class we have two methods, OnPreAction and OnPostAction, those methods will be executed before and after an Action method. But I wanted to be able to specify Interceptors for a Route which should be executed before a controller is instantiated and after a Controller’s action method is executed.

    The Interceptors has two methods, PreHandle and PostHandle. The PreHandle returns a value if the process of a request should be stopped or if it should go on with the process of an execution.  It’s possible to create a chain of Interceptors. If more than one Interceptor is specified and one of them tells to stop the process, the rest in the chain will not be executed. To specify an Interceptor or a chain of Interceptors I have override the Route class and created my own which has a List of IInterceptors. So when a Route is setup, Interceptors could be added to that route:

    RouteTable.Routes.Add(new Nsquared2.MVC.Extenstion.Route
    {
       Url = "[controller]/[action]/[id]",
       Defaults = new { action = "Index", id = (string)null },
       RouteHandler = typeof(N2MVCRouteHandler),
       Interceptors = new List<IInterceptors>()
       {
           new MyInterceptor(),
           new AnotherInterceptor()
       }
    });

    Here is an example of an Interceptor which will redirect the user to a “Not available at this time” page if the current time of the Request is not within a specified interval.

    public bool PreHandle(RequestContext context)
    {
       if (DateTime.Now.Hour > START_HOUR && DateTime.Now.Hour < END_HOUR)
               return true;
       else
           context.HttpContext.Repsonse.Redirect(“NotAvailableAtThisTime.html”);

       return false;
    }

    The following is my implementation of the MvcHandler’s ProcessRequest to add the Interceptors to the pipeline; the code is also part of my own MvcHandler written in my previous post.

    protected override void ProcessRequest(IHttpContext httpContext)
    {
       if (this.RequestContext == null)
          throw new InvalidOperationException("No RequestContext");

       if (base.RequestContext.RouteData.Route.GetType().IsAssignableFrom(typeof(Nsquared2.MVC.Exstension.Route)))
       {
           if (InterceptorHandler.ExecutePreHandler(this.RequestContext))
           {
              ControllerContext controllerContext = this.ExecuteAction();

              InterceptorHandler.ExecutePostHandler(controllerContext);
           }
       }
       else
       {
           this.ExecuteAction();
       }
    }

    Here is the ExecutePreHandler method of my InterceptorHandler:

    public static bool ExecutePreHandler(RequestContext request)
    {
       Nsquared2.MVC.Extension .Route route = request.RouteData.Route as Nsquared2.MVC.Extension.Route;

       if (route.Interceptors != null)
       {
          foreach (IInterceptors interceptor in route.Interceptors)
             if (!interceptor.PreHandle(request))
               return false;
       }

       return true;
     }

    Note: This code is only used for a Interceptor prototype.

    Read more...

  • ASP.Net MVC Framework - Create your own IRouteHandler

    In my previous post I wrote about how we can create our own IControllerFactory for the ASP.Net MVC Framework; in this post I will show you how we can create our own IRouteHandler.

    The RouteHandler in this post will replace the IControllerFactory with my own Controller Factory, and also set a default ControllerFactory and a ViewFactory specified in the web.config. This is something the current preview bits of the MVC Framework can’t.

    It’s quite easy to create our own RouteHandler, we only need to implement the IRouteHandler interface and implement the GetHttpHandler method ;)

    public class N2MVCRouteHandler : IRouteHandler
    {
       public IHttpHandler GetHttpHandler(RequestContext requestContext)
       {
           N2MVCHandler handler = new N2MVCHandler();
           handler.RequestContext = requestContext;
           return handler;
        }
    }

    The GetHttpHandler returns an IHttpHandler. I have created my own IHttpHandler (N2MVCHandler). The N2MVCHandler inherits the MvcHandler shipped with the ASP.Net MVC Framework. The reason why I inherit the MvcHandler is because I don’t want to rewrite stuff that isn’t necessarily. In my IHttpHandler I override the ProcessRequest method and added my own code to create a Controller for the current request.

    public class N2MVCHandler : MvcHandler
    {
        protected override void ProcessRequest(IHttpContext httpContext)
        {
           if (this.RequestContext == null)
              throw new InvalidOperationException("No RequestContext");

           string controllerName = this.GetRequiredString(this.RequestContext.RouteData, "controller");

           IController controller = this.CreateController(controllerName);
           ControllerContext controllerContext = new ControllerContext(base.RequestContext, controller);

           controller.Execute(controllerContext);
        }

        private IController CreateController(string controllerName)
        {
           N2MVCConfigurationHandler config = ConfigurationManager.GetSection("Nsquared2/N2MVCSection") as N2MVCConfigurationHandler;

           IN2ControllerFactory controllerFactory = N2ControllerFactoryBuilder.GetControllerFactory(config.ControllerFactory);

           IController controller = controllerFactory.CreateController(base.RequestContext, controllerName);

           return controller;
        }
    }

    In the ProcessRequest method I also create a Controller for the current request by calling the CreateController method. The CreateController method in the N2MvcHandler instantiates a ControllerFactroy which is specified in the web.config file. When the factory is instantiated I make a call to its CreateController method to create an instance of the Controller.

    In this example I have replace the IControllerFactory with my own interface, the reason is that I want to pass the name of the Controller and not the Type. The MvcHandler shipped with the MVC Framework will in the ProcessRequest method try to locate the Controller within the references assemblies and create the Type of the Controller and pass it to the IController.CreateController method. But I think it’s up to the ControllerFactory to look up the Controller. Here is my IControllerFactory interface:

    public interface IN2ControllerFactory
    {
        IController CreateController(RequestContext context, string controllerName);
    }

    Note: You can still create your own ControllerFactory, but you need to implement my interface instead of IControllerFactory, and you don’t need to make a call to the ControllerBuilder.Current.SetDefaultControllerFactory method in the Application_Start event in Global.asax to specify which ControllerFactory you want to use, instead you can do it in web.config. You will see how to do it later in this post.

    I decided to use Spring.Net in this post also to create my Controller within the ControllerFactory.

    public class N2ControllerFactory : IN2ControllerFactory
    {
        public IController CreateController(RequestContext context, string controllerName)
        {
            IResource input = new FileSystemResource(context.HttpContext.Request.MapPath("objects.xml"));
            IObjectFactory factory = new XmlObjectFactory(input);

            IController controller = (IController)factory.GetObject(controllerName, typeof(IController));

            if (typeof(Controller).IsAssignableFrom(controller.GetType()))
            {
              N2MVCConfigurationHandler config = ConfigurationManager.GetSection("Nsquared2/N2MVCSection") as N2MVCConfigurationHandler;
              ((Controller)controller).ViewFactory = N2ViewFactoryBuilder.GetViewFactory(config.ViewFactory);
            }

            return controller;
        }
    }

    It's the ControllerFactory's responsibility to create and fill the Controller with all it information it needs. In this case the ViewFactory.

    The IViewFactory is used to create a factory which has the responsibility to create a View. Because a Controller don’t need to implement the Controller base class I will in my code use a "code policy". I will check if the created Controller inherits the Controller class, if so I will create a IViewFactory and inject it to the Controller. The IController interface don’t have the ViewFactory property, it’s something we will get from the Controller base class. 

    If we take a look again at the CreateContoller method in the IHttpHandler (N2MVCHandler), we can see how I get the ControllerFactory from the web.config

    private IController CreateController(string controllerName)
    {
        N2MVCConfigurationHandler config = ConfigurationManager.GetSection("Nsquared2/N2MVCSection") as N2MVCConfigurationHandler;

        IN2ControllerFactory controllerFactory = N2ControllerFactoryBuilder.GetControllerFactory(config.ControllerFactory);

        IController controller = controllerFactory.CreateController(base.RequestContext, controllerName);

        return controller;
    }

    I use some other helper classes in my code to create an instance of the Controller- and ViewFactory specified in the web.config, the code of the helper methods is not relevant for this post. When the public CTP of the MVC Framework is released, you can drop me an e-mail and I can send you my source code.

    Here is the config section in the web.config where a conrollerFactory is specified and also a viewFactory. So we can now easy specify our ControllerFactory and ViewFactory in web.config.

    <Nsquared2>
        <N2MVCSection
            controllerFactory="MvcApplication.Models.N2ControllerFactory, MvcApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
            viewFactory="MvcApplication.Models.N2ViewFactory, MvcApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
    </Nsquared2>

    By using the Route objects’ RouteHandler, we can easy change the RouteHandler the MVC Framework should use.

    RouteTable.Routes.Add(new Route
    {
        Url = "[controller]/[action]/[id]",
        Defaults = new { action = "Index", id = (string)null },
        RouteHandler = typeof(N2MVCRouteHandler)
    });

    In this post you have seen how we can create our own IRouteHandler, and also replace the ControllerFactory with our own.

    Read more...

  • ASP.Net MVC Framework - Create your own IControllerFactory and use Spring.Net for DI

    In this post I’m going to show you how we can easy create our own IControllerFactory for the ASP.Net MVC Framework and use Spring.Net to create our Controllers. I will in this post also use the Spring.Net Dependency Injection support to pass a Repository that should be used by our Controller.

    To create a ControllerFactory we need to implement the IControllerFactory interface. This interface has one method, CreateController. This method takes two arguments a RequestContext and the Type of the controller to create. The MVC Framework will locate our Controller and passed in the Type to our IControllerFactory. This is something I don’t like; I want to be responsible to look up my own Controller in my way, not let the MVC Framework locate the type in their way, It will only creates some magic. If we want to change this behavior in the current preview of the MVC Framework we can create our own RouteHandler, but this is out of topic in this post. When we use Spring.Net to get an instance of an object we use a string, so we can use the Name property or the Type passed as an argument to our CreateController method to get the name of the Controller.

    Here is the implementation of an IControllerFactory which will use Spring.Net to instantiate a Controller:

    public class SpringControllerFactory : IControllerFactory
    {
            public IController CreateController(RequestContext context, Type controllerType)
            {
                IResource input = new FileSystemResource(context.HttpContext.Request.MapPath("objects.xml"));
                IObjectFactory factory = new XmlObjectFactory(input);

                return (IController)factory.GetObject(controllerType.Name);
            }
     }

    In this code I use the XmlObjectFactory to create objects out from a specified XML file, in this case the "objects.xml" file. Within the objects.xml file we can specify the objects we want to be instantiated when we are using the Spring.Net framework. I will later in this post show the content of the "objects.xml" file. But first we can take a look at the implementation of a Controller.

    public class HomeController : Controller
    {
            IHomeRepository _homeRepository;

            public HomeController() : this(new HomeRepository()) {}

            public HomeController(IHomeRepository homeRepository)
            {
                this._homeRepository = homeRepository;
            }

            [ControllerAction]
            public void Index()
            {
                CompanyInfo companyInfo = this._homeRepository.GetCompanyInfo();
                RenderView("Index", companyInfo);
            }

            [ControllerAction]
            public void Contact()
            {
                CompanyInfo companyInfo = this._homeRepository.GetContact();
                RenderView("Contact", companyInfo);
            }

            [ControllerAction]
            public void About()
            {
                CompanyInfo companyInfo = this._homeRepository.GetCompanyInfo();
                RenderView("About", companyInfo);
            }
     }

    I decided to modify the HomeController created by the "MVC Web Application" template. My modification of the HomeController was to remove the code to fill a CompanyInfo object, and instead put it into a Repository with the name "HomeRepostory".

    public class HomeRepository : IHomeRepository
    {
            public CompanyInfo GetCompanyInfo()
            {
                CompanyInfo companyInfo = new CompanyInfo();
                companyInfo.CompanyName = "Your company name here";
                return companyInfo;
            }

            public CompanyInfo GetContact()
            {
                CompanyInfo companyInfo = new CompanyInfo();
                companyInfo.CompanyName = "Your company name here";
                companyInfo.AddressLine1 = "Company address Line 1";
                companyInfo.AddressLine2 = "Company address Line 2";
                companyInfo.City = "City";
                companyInfo.State = "State";
                companyInfo.Zip = "00000";
                companyInfo.Email = "
    email@yourcompany.com
    ";
               
                return companyInfo;
            }
     }

    The HomeRepository implements an interface with the name IHomeRepository. I made this design decision so I can easy mock my repositories. If we take a look at the HomeController again we can see that I have added a private field with the type IHomeRepository and also created a constructor which will take an IHomeRepository as an argument. The reason to this design is because of testability. For example if I mock the HomeRepository I can in my Test project easy inject the mock object for the Repository to my Controller.

    MockHomeRepository mockHomeRepository = new MockHomeRepository();
    HomeController homeController = new HomeController(mockRepository);

    homeController.About();

    Assert.AreEqual(((CompanyInfo)homeController.ViewData).companyInfo, "Your company name here");

    By using a constructor which will take our IHomeRepository as an argument, we can also do a Constructor Injection by using the Sprin.Net framework, and that is exactly what I’m going to do in this post.

    Now when we have our Controller and Repository we need to setup the “objects.xml” file with our objects and also setup a Constructor Injection. Here is the content of the “objects.xml” file:

    <?xml version="1.0" encoding="utf-8" ?>
    <objects xmlns="
    http://www.springframework.net"
                    xmlns:xsi="
    http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="
    http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">

      <object id="HomeController" type="MvcApplication.Controllers.HomeController, MvcApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
        <constructor-arg name="homeRepository" ref="HomeRepository"/>
      </object>

      <object id="HomeRepository" type="MvcApplication.Models.Repositories.HomeRepository, MvcApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
     
    </objects>

    The Object element specifies our objects we want to create with the Spring.Net framework. The id attribute specifies the name of the object and the type specifies the type of our object. When we use the Spring.Net framework’s GetObject method we pass in the name of the object to create, the GetObject method will look for an object with the id attribute set to the name, and instantiate the specified type. By using the <constructor-arg> element we can specify what object that should be passed into our constructor when we create the object. In this case I have specified the HomeRepository object.

    When our IControllerFactory now will create our HomeController, Spring.net will create an instance of our Controller and do a constructor injection and pass in the HomeRepository object to the constructor and return our controller.

    Now when we are done with all the implementation of our IControllerFactory, Controller and Repository we need to make sure our IControllerFactory should be used. This can be done in the Global.asax’s Application_Start event by using the SetDefaultControllerFactory method:

    protected void Application_Start(object sender, EventArgs e)
    {
       ControllerBuilder.Current.SetDefaultControllerFactory(
                               typeof(MvcApplication.Models.Infrastructure.SpringControllerFactory));
       ...
    }

    When we now run our application, our IControllerFactory will be used and all the creating of our Controllers will be handled by the Spring.Net framework.

    Read more...

  • ASP.Net MVC Framework - List and Save data

    When building application today (X)HTML-based web interfaced is often used as the front-end choice today. Several companies used Microsoft SharePoint or other web-based portals solutions as intranet; we have several public applications which are web based. Enterprise applications continue to adopt web-based user interfaces, and this will unlikely change in the near future. A web-based user interface can today target almost any platform, and the deployment of web-based application is much easier than a desktop application that needs to be installed on every client.  It’s easier to brand a web application than a desktop application like a Windows Form. A web based application will not take up to much resource on the client’s computer. But there are some challenges also.

    The Request-Response paradigm can complicate interactions that would be simple in traditional UI. For example if we have a Windows application we can simply hold the state, HTTP is a stateless protocol which will complicate state management.  A web applications user interface today can also be complex, often produced by tools like DreamWeaver and “probably” FrontPage ;) The applications also often use client-side JavaScript. Some content can be hard to be edited by a .Net developer. But for a designer and of course some developers it’s easy to change the user interface, and often a web applications user interface will be changed.  This requires a clean separation of presentation from business logic.
    With the ASP.Net MVC Framework we will have separation of concerns. We separate the presentation from the business logic. The MVC is an abbreviation of Model View Controller, where the Controller objects accept user input and invoke business logic to create and update model objects. The Model object has the responsibility to provide the data to display; the model is a contract between controller and view. The View objects are responsible to display the Model, as provided by the controller that invokes it. By using the ASP.Net MVC Framework we will have more control over the HTML (a cleaner HTML page), we will have a controller separated from the View. By having this separation developers can create controllers and use unit-testing or TDD without knowing anything about how the model should be presented. The designer of the User Interface doesn’t need to know about the controller, only what data that should be displayed and sent back during a POST. The three parts in the MVC pattern, the View, Controller and Model can be implemented by three different developers and designer at the same. TDD can be applied when creating the Controllers and also the Model, this because of the separations and the possibility to create mock objects. The MVC Framework works against interface so we have interfaces for everything so we can easy create our mocks and test our controllers without needing to know about the View. We can also mock the Model.

    I will go on by showing how we can create a simple Blog application with the ASP.Net Framework and LINQ to SQL.

    To create a MVC Web Application we select File -> New Project and select the MVC Web Application template:



    Then we enter the name of the application, I will give it the name MyBlog. The “MVC Web Application” template will create some template files and folders for us:
     
    The folders and files the MVC Web Application template has created are:

    /Controllers
    /Models
    /Views
         /Common
         /Home
         /Masters

    The Controllers folder should contain the Controllers we will use in our application. In the Models folder we put our model and business objects. In a larger application we will probably use separated class libraries instead of adding the objects to the web application project, this is of course possible. In the Views folder we add the pages (Views). The Views have the responsibility to render the Model. A View is a normal .aspx page, but instead of inheriting the Page object, it inherits the ViewPage object or ViewPage<T>. We can also put MasterPages and Style Sheets into the View folder. In the Common folder we can put Style Sheets; in the Masters we put master pages. You have probably also notice the Home folder. If we create a Controller, for example <name>Controller (Controller is a suffix used for controllers), we should also create a folder under the View with the same <name> as the Controller where we add our Views. This is not necessarily; we can also add the View directly under the Views folder. The first place the MVC Framework will look for a View when we want to render a View is in the folder that has the same name as the Controller used by the View. If it can’t find a folder with the same name as the Controller, the MVC Framework will see if it can find the View in the root of the Views folder. When we create a “MVC Web Application” we will also get an empty Default.aspx page and a Global.asax file. In the Global.asax we will map a URL to a Controller.

    Explanation about Routing and how to setup a route.


     
    In the Application_Start we add a Route to the RouteTable’s Routes collection. The first Route uses an URL with the format “[controller]/[action]/[id]”. With the MVC Framework we don’t enter a URL directly to a specific file; instead we use a cleaner format. Like: /Posts/List/.Net
    The “[controller]” in the Url specifies what part of the Url has the name of the Controller that should be used. The “[action]” specifies a Controller’s method that should be executed. The last “[id]” specifies an argument that should be passed to the Controller’s action methods. So if we use the format “[controller]/[action]/[id]” and enter an Url like this: /Posts/List/.Net the MVC Framework will instantiate a Controller with the name Posts<Controller> (PostControllers) and execute the Controller’s List method and pass “.Net” as an argument to the method.
    public void List(string id)

    We can customize the format in different ways. We can use the Defaults property of the Route object to specify which Controller we should use for a specific URL and also which Action. For example for the URL /MyBlog/Posts/List the Posts<Controller> will be used and the Controller’s List method will be executed.

    Url = “MyBlog/Posts/List”
    Default = new { action=”List”, controller=”Posts” }

    If we use a format like “[controller]/[action]/[id]” we don’t need to enter an URL that must match the whole format, we can for example enter URLs like the following ones:

    /Posts
    /Posts/List
    /Products/Edit/.Net

    If our action methods should be able to take more arguments, we can simply add them by name to the URL property of the Route class:

    “[controller]/[action]/[id]/[PageIndex]”

    We can then use the Defaults property of the Route object to specify the default value for the Id and PageIndex argument:

    Defaults = new { id = 1; pageIndex = 2 }

    The Defaults property uses an anonymous type and by using reflection behind the scene the Deafults property can be dynamic. The name of the property we specify must have the same name as the action methods arguments. So in the above case our action method would look like:

    public void <Name of method>(int? id, int? pageIndex)

    As you can see a Nullable type of Int is used, the reason to this is that we can now enter an URL that executes our action method without specifying the value of the arguments.
    The RouteHandler property of the Route object specifies which class should handle the routing of an URL to a Controller.

    There is one more property of the Route object we can use and it’s the Validation property. With the Validation property we can set up a validation role for the specified action method’s arguments. For example if we want to make sure the id argument only have a maximum value of 9999 and the pageIndex a maximum value of 99 we can do the following:

    RouteTable.Routes.Add(new Route
    {
        …
       Defaults = new { Validation = new { id = @”\d{1,4}”, pageIndex = @”\d{1,2}” }
    });

    Modify the RouteTable for the Blog application we are building

    We will change the default action method to “Home” instead of ”Index”. We will also create a Controller with the name “BlogController” later so we will change the controller for the Default.aspx to “Blog”. When we enter the URL to the default.aspx, the BlogController will be instantiated and the default action method “Home” will be executed.



    Creating a Controller

    Now when we have setup the routing we can start to create the BlogController. To create a Controller we right click on our Controller folder and select “Add New item” and then select the “MVC Controller Class” template. We give the Controller the name “BlogController” and hit the Add button.
     


    A Controller inherits from the base class Controller by default. We don’t need to inherit this class if we don’t want to, but it has some nice helper methods that we can use, and the base class will also make it easier to create a Controller. “The MVC Controller Class” template will add an Index method to the Controller, We change the name to “Home”. We add three other methods also, Add, About and Contact to the BlogController:



    The ControllerAction attribute must be added to the action method, it’s because of security reason so we can’t invoke other method in a Controller by entering the method in the URL.

    Pre- and PostConditions

    The Controller base class has two methods that we can override, onPreAction and onPostAction. By using those methods we can add logic that should be executed before and after an action method is executed.

    We will not add any logic to the Controller yet, instead we will move on to the Model layer.

    Note: In normal situation I should have used Test Driven Development or Unit test, but if I should include it in this post, it should only make the post longer.

    The Model

    We can use LINQ to SQL to do the data access, so the first thing we will do is to create a DataContext class. This can be done by using the designer tool in Visual Studio 2008 and generate the DataContext classe for us. Right click on the Model folder and select “Add New Item” and select “Linq To Sql Classes”.



    Give it the name MyBlogDataContext and open a connection to MyBlog database and drag out the Post table to the designer.


     
    Note: You can easy create the MyBlog database and add one Table with the name Post, and then four complumen, ID (Integer and auto increment), Title (mvarchar), Message (nText) and Posted (DateTime).

    Now when our DataContext is genereated we create one class which should use it. So we can create a class with the name PostRepository. We add two methods, GetAll and Add. The GetAll will return a List of Post and the Add will take a Post object as an argument.

    No when our Model is created we can go back to the BlogController and implement the first action “Home”. The “Home” action should get all blog posts from the Post table in our database and then pass them to the “Home” View. This is done by making a call to our PostRepository.GetAll method.



    The RenderView method is a method on the Controller base class. The method takes the name of the View to render and the Model that should be rendered by the View as arguments. It can also take a MasterPage as an argument if we want to render a View with a specific MasterPage:

    RenderView(“View”,”MasterPage”)

    In this example we will use the MasterPageFile attribute on the @Page directive for all the pages so we don’t need to dynamically specify a MasterPage to use.

    Creating Views

    Now when the Model is created and the “Home” action for the BlogController is implemented, we can start to add Views. We will use a MasterPage for all Views and by default when we create a MVC Web Application we will get a MasterPage located in the Views/Masters folder. We can change the MasterPage to fit our needs. We can for example add a header, three links, Home, About and Contact and specify where our ContentPlaceHolder should be:



    The three Links in the MasterPage will call the Home, About or Contact action method of the BlogController. To specify which action the Links should call, we can use an ActionLink server-control which I have created. Send me an e-mail and I will send the source code. The Action attribute of the control specifies which action we should call when we press the link. The ActionLink server control is an abstraction of the Html.ActionLink helper method of the ViewPage object. Instead of using a Script block and call the ActionLink method like this:

    <%= Html.ActionLink("Home", "Home"); %>

    We can use the ActionLink control instead.

    <mvc:ActionLink ID="ActionLink3" Action="Contact" runat="server" Text="Contact"/>

    We can add any attribute to the ActionLink control and it will take the attribute and value and add it as a QueryString to the Links URL, for example:

     <mvc:ActionLink ID="ActionLink3" Action="Contact" PostId=”1” runat="server" Text="Contact"/>

    Will generate the following HTML:

    <a href=”/Blog/Contact?PostId=1”>Contact</a>

    The MasterPage will look like this:


     
    Now when the MasterPage is created we can add the first View for the blog. Because the Controller has the name Blog we first create a folder in the Views folder with the name “Blog” and then right click on the folder and “Add New Item” and select the “MVC View Content Page” template to create View as a content page.



    Name the View “Home”.  When we add the View we also point out the MasterPage page we should use.  When this is done we open the code-behind file of the View and change so the Home View inherits the ViewPage<T> instead of the ViewPage. By using the ViewPage<T>, we can specify the type of the ViewData property of the View (The ViewData property holds the data passed as an argument to the RenderView method) we will change so the Home View inherits VierwPage<List<Post>>.
     

    Then we add some inline code to the View to iterate through all posts and display them by using a table.
     



     
    Note: We can use a ListView control shipped with ASP.Net 3.5 if we want to avoid using too much inline code. We can then do the data binding from the Page_Load method of the code-behind of the View by using the ListView’s DataSource property and DataBind method.

    The ViewData property used in the code will contain a List of Posts. It’s the Home action method of the BlogController that will make sure this View will be rendered. And the Home method will get all posts from the data source and pass it to the RenderView.



    At the top of the View we add an ActionLink control to the View with the Action attribute set to “New”. We set the Text property to “Add New Post”. We will use this ActionLink control to navigate to a new View where we can add new posts to the blog.



    The “New” action method will render the “Add” View which is the next “MVC View Content Page” we will add. The “Add” View is responsible to render an input form where we can write a new blog post.



    The “Add” View will have two input field, one for the title of a blog post and one for the message body. The action attribute of the <form> element it set to the action method that should we called when we submit the page. In this case the “Add” method. When we have created our new Post, we will make a call to the PostRepositories Add method. The “Add” method will look like this:



    To get the input fields data we need to use the Controller base class’s Request property. In the future we will see some other solutions for this. When we have saved the new blog to the data source we will make a call to the RedirectToAction method to make sure our “Home” action method will be executed. We do this because we want to render all the available posts after we have added one post. The last thing to do now is to add the View for the About and Contact link, when this is done we make sure to add the action methods “About” and “Contact” to the controller and make sure they render each Views. The “About” and “Contact” View has only static information so we only make a call to the RenderView method.



    Summary

    You have now seen a simple demo where a View lists available blog posts and also how we can add a new blog post to our data source. I will add more posts about the MVC Framework, so keep watching my blog if you find it interesting.

    Read more...

  • ASP.Net MVC Framework and data binding.

    Note: The content in this blog post is based on the an early prototype of the ASP.Net MVC Framework and stuff can or will change.

    I got a question if it’s possible to use data binding with the ASP.Net MVC Framework. Sort of it’s possible, at least to display data but not to do a two-way data binding with existing controls. The reason of that is because it’s not implemented yet ;) The way the data-bound controls work today with data-binding will not work with the MVC Framework, but we will probably see a solution to solve this in the future. When we do a POST and post data a controller’s action method will be invoked. This method can take some arguments as input parameters, for example:

    /Products/Edit/1      /Products/Edit?id=1

    [ControllerAction]
    public void Edit(int? id)
    {
    }

    Note: The URL is routed to the controller, and invokes an action method.

    We can’t from the control get access to the controls by using an id as in a normal postback scenario. What we can do is to use the Request property of the base class of our controller (If we decide to inherit the Controller class). The Request property is of type IHttpRequest. The reason why it uses an interface is because we should easy mock out the Request to make sure we can simply do unit-testing without needing to run our controllers within ASP.Net. By using the Request property we can simply get the data from our input fields and map them to our model:

    <input type=”text” name=”Description” …>

    product.Description = Request[“Description”]

    In an early prototype from Scott Guthrie, he used an Extension method that could take the Request.Form as an argument and do the mapping between user input fields and model.

    product.UpdateFrom(Request.Form)

    In the view he used a naming convention to easy see which user input field should be mapped to which property of the model:

    <input name=”Product.Description” …>

    There are other different prototypes to make it easy to fill a model out from the posted data.

    We can use some of the controls to do one-way data binding to display data. Scott Guthrie has a good example in his post about how we can bind data to the ListView control that is shipped with ASP.Net 3.5 (ASP.Net 3.5 will be available at the end of this month, so really soon).

    If we have a ListView control in our View we can bind data like this:

    <asp:ListView id=”productList” runat=”server”>
        <LayoutTemplate>
              <table>
                     <asp:PlaceHolder Id=”itemPlaceHolder” runat=”server”/>
             </table>
        </LayoutTemplate>
        
       <ItemTemplate>
             <tr>
                  <td><%# Eval(“Description”) %></td>
             </tr>
       </ItemTemplate>
    </asp:ListView>

    Because the View is responsible to render the model, we will do the data binding in the code-behind of the View.

    public partial class Products : ViewPage<List<Product>>
    {
       public void Page_Load()
       {
          productList.DataSource = ViewData;
          productList.DataBind();
       }
    }

    Note: Because the View inherits the ViewPage<T>, we can specify the type of the ViewData (ViewData will be of type T). The ViewData is a property of the ViewPage which will contain the data we passed to the RenderView method in our control:

    [ControllerAction]
    public void List()
    {
          List<Products> products = ProductRepository.GetAll();
          RenderView(“Products”, products);
    }

    As you have seen in this post, we can do one-way data binding, but at the moment we can't easy do a two-way data binding. You will see more post about the MVC Framework from me.

    Read more...

  • ASP.Net MVC Framework an early look

    NOTE: “The information in this post is from an early stage of the MVC Framework and only an overview of the basics. The MVC Framework can and will be changed over time.”

    As many of you already know Microsoft is working on a MVC Framework for ASP.Net. MVC stands for “Model View Controller”. The Model View Controller is a design pattern and the idea is to separate business logic from the View (The View is the page that will display content, for example an .aspx page). The MVC in general maintain a clean separation of concerns, it will be easier to test business logic because it’s separated from the View and the View will not have any knowledge of the underlying model. Today when we build ASP.Net applications we have a code-behind which is a partial class of the “View”. With the code-behind model we can’t easy use Test Driven Development (TDD) or unit-test, at least is not easy. We can use the MVP (Model View Presenter), but that require us to write some extra code. With the MVC Framework it will be much easier to apply TDD.

    The ASP.Net MVC Framework is integrated with ASP.Net and can use existing infrastructure like caching, session and profile etc. It will also support static and dynamic languages. The MVC Framework will only as it looks now work on ASP.Net 3.5. The .Net 3.5 will be released within any weeks now. The final build of the framework was done only some days ago. With the MVC Framework we will get a Project Template and great tool support. The MVC Framework is extensible and pluggable, so we can replace any system components, it also support Inversion Of Control (IoC)/Dependency Injection (DI). It’s the lifecycle that makes the model extensible. It looks like this:

    Request -> Route (IRouteHandler) –> ControlFactory (IControllerFactory) -> Controller (IController) -> ViewFactory (IViewFactory) -> View (IView) -> Response

    The Web Server gets browser request, for example http://localhost/Product, the Route to Controller is determined. The Controller is activated and the “Action” method on Controller is invoked. The Controller will then access the model. The Controller will then render View and passing in custom ViewData to the View. The View is rendered.

    When we use the MVC Framework we will not specify an URL to a specific page and pass QueryStrings etc. Instead we use a cleaner URL. For example:
    http://localhost/Products or http://localhost/Producsts/Edit/4 etc. We will map this URL to a specific controller which will be executed when we enter the URL. In the Global.asax we can create routes, which will be handled by an IRouteHandler. The following is the default way to add a route:


    protected void Application_Start(object sender, EventArgs e)
     {
                RouteTable.Routes.Add(new Route {
                    Url = "[controller]/[action]/[id]",
                    Defaults = new { action = "Index", id = (string)null },
                    RouteHandler = typeof(MvcRouteHandler)
                });
     }

    Note: In a later release we will probably be able to add this to a configuration file instead of writing code.

    The Route that is added to the RouteTable will use an URL with the following format “[controller]/[Action]/[id]”. The controller is the controller that should be used, the action is the method in the controller that should be executed and the id is a value that can be passed to the controller’s method. If we use this format and enter a URL like the following: http://localhost/Product, the MVC Framework’s IControlleFactory will create and return the controller that belongs to the Product. It will try to locate a controller with the name ProductController. So if you enter an URL like http://localhost/Customer, it will try to instantiate a controller with the name CustomerController. When the controller is instantiated the Index method of the controller will be executed. The Defaults property of the Route class specify the default settings for the route, such as which action method of the controller is the default action (in this case the Index is the default one specified, this can also be specified on a controller with an attribute.), and the default values of the action method’s parameters that should be passed to the method. If we specify a URL like this one: http://localhost/Product/List the List method of the ProductController will be executed instead of the one that is default specified on the Route. The format of the URL specified for the Route was [controller]/[action]/[id], and the [action] in the format specifies which part of the URL is the name of the action method that should be executed. The [id] in the URL is the name of the action method’s parameter and the value enter at this location of an URL will be passed to the action method. If we enter a URL like this one: http://localhost/Product/Edit/4, the Edit method of the ProductController will be executed and the value 4 will be passed as a value to the Edit method’s id argument. The interface of the action method will look like this:

    public void Edit(int? id)

    I will later in this post write more about the controller.

    We can of course change the format of the URL if we want to pass more values to a controller’s action method, for example: “[controller]/[action]/[id]/[pageIndex]”.

    The RouteHandler property of the Route specifies which IRouteHandler we want to use.

    If we don’t need to use the format “[controller]/[action]/[id]”, for example instead of letting the URL have the name of the controller we can skip the [controller] from the URL and instead specify the type of the controller we want to use when we setup the Route. For example:

    RouteTable.Routes.Add(new Route {
            Url = "products/[category]",
            Defaults = new {
                   controller = "Product",
                   action = "Index"
              },
              RouteHandler = typeof(MvcRouteHandler)
    });

    Now when we have looked at how we can map a URL to a controller we can take a look at how we can implement a controller. A controller is a normal class that inherits the base class Controller located in the System.Web.Mvc namespace:

    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;

    namespace MyControllers
    {
        public class ProductController : Controller
        {
        }
    }

    An action method is a normal method that has the ControllerActionAttribute specified. The ControllerActionAttribute is used because of security reason so not anyone can enter an action in the URL and execute it. The ControllerActionAttbibute has some properties also, for example the DefaultAction which can be used to specify the default action method of the controller.

    [ControllerAction(DefaultAction = true)]
     public void Index()
     {
            RenderView("MyView");
     }

    The RenderView method will render the specified view. In this case the view with the name “MyView”. The RenderView will not do a call to Response.Redirect; instead it will use the Page.ProcessRequest method. By default the RenderView will look into a sub folder of your project with the name Views and then the sub folder with the name of the controller attached to the view.

    /root
        /Views
              /Product
                 MyView.aspx

    The RenderView method is located in the Controller’s base class. This method will execute the IView’s RenderView method. We can create our own IViewFactory which will return our IView representation where we can create our own implementation of the RenderView. For example if we want to render a view based on another format than HTML, for example a jpg or gif image etc. We can create our own IView and make sure our RenderView will render binary data to the output stream instead of text.

    The code-behind of the View inherits form the ViewPage instead of the Page object.

    Note: We can easy create our own IViewFactory and IView for mock out the views for testing and replace .aspx with other technologies.

    To send data to the View that should be displayed we can use the ViewData property of the Controller base class, or we can pass our data to the RenderView method:

    [ControllerAction]
    public void List(int? page)
     {
           PagedList<Product> products = repository.GetProducts(page ?? 0, 10);
           RenderView("List", products);
     }

     [ControllerAction]
     public void Edit(int id)
     {
            Product product = repository.GetProductByID(id);
             RenderView("Edit", product);
     }

    [ControllerAction]
    public void ShowCustomer(int? id)
    {
        ...
        ViewData["CustomerName"] = customer. Name;
        RenderView("ShowCustomer");
    }

    To display this information in our View we can user server side script block:

    <table class="product_listing">
            <tr>
                <th></th>
                <th>Product Name</th>
                <th>Unit Price</th>
            </tr>
           
            <% foreach(var p in ViewData) { %>
           
                <tr>
                    <td>
                        <%=Html.Link("Edit", "Products", new { Action="Edit", ID=p.ProductID }) %>
                    </td>
                    <td><%=p.ProductName %></td>
                    <td><%=p.UnitPrice.ToCurrency() %></td>
                </tr>
           
            <% } %>
           
    </table>

     

    <h2><%=ViewData.ProductName %></h2>


    <h1><%=ViewData["CustomerName"] %></h1>

    By using the ViewData collection we can pass several of objects to our view that should be displayed. If we want to pass typed data to the View, we can inherit the Controller<T> where ViewData will be of type T. If we use the Controller<T>, the page which uses the Controller<T> needs to inherit the ViewPage<T> instead of ViewPage.

    The MVC Framework doesn’t support postbacks and the use of ViewState, so most of the Controls shipped with ASP.Net can’t be used. Microsoft will probably add new Controls for the MVC Framework.

    Note: This framework is not Web Form 4.0 or will replace the existing postback model. The postback model will still exists and Microsoft will still provide new feature to it in the future.

    The MVC Framework will be added to the SP1 of VS 2008. This framework is for people that would like to use this MVC design pattern instead of the postback model. The MVC Framework will work better with Test Driven Development and unit-testing, so people that will make it easier to test web apps will also probably use this model. I will use it in every Web project in the future. With this model it would also be easier to maintain applications because we will have more control over the HTML. We don’t need to hook up to an event of a control and try to figure out how to add extra data into a GridView if we want to extend it etc. This model reminds of the old classic ASP, and it will be easier for people that work with classic ASP to move to ASP.net if they start using the MVC Framework.

    Testing with MVC will as I mentioned before be much easier. We have several of interfaces that we can use. The Mockable intrinsic objects are IHttpContext, IHttpResponse and IHttpRequest. Because the MVC Framework have interfaces for IRouteHandler, IController, IControllerFactory, IView and IVewFactory we have more extensibility options. If we want to test a Controller’s action we can for example create our own IViewFactory and IView, by doing this we can change the implementation of the RenderView method.

    [TestMethod]
    Public void TestTheEditActionFotTheProductContoller()
    {
        ProductController controller = new ProductController(mpr);

        TestViewEngine testView = new TestViewEngine();
        controller.ViewFactory = testView

        controller.Edit(5);

        Assert.Equal(testView.Template, "Edit");
        Asssert.Equal(testView.GetViewData<Product>().ProductID, 5);
    }

    If you want to see some sample code, you can download it from Scott Hanselman’s blog.

    Watch out for more information on Scott Guthrie blog.

    Read more...