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:

  • 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" ;)

  • 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) {%>
            ...
    <% } %>

  • 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))

  • 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)

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

  • 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;
        }
    }

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

  • 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

  • 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.

  • 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.