Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Azure, PHP, OpenXML, VSTS, ...

About the author

Maarten Balliauw is currently employed as .NET Technical Consultant at RealDolmen. His interests are mainly web applications developed in ASP.NET (C#) or PHP and the Windows Azure cloud platform.
More about me More about me
Send mail E-mail me


ASP.NET MVC Quickly Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn
View Maarten Balliauw's MVP profile

Search

Latest Twitter

    Follow me on Twitter...

    My projects

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    © Copyright Maarten Balliauw 2010

    Mocking - VISUG session (screencast)

    A new screencast has just been uploaded to the MSDN Belgium Chopsticks page. Don't forget to rate the video!

    Mocking - VISUG session (screencast)

    Abstract: "This session provides an introduction to unit testing using mock objects. It builds a small application using TDD (test driven development). To enable easier unit testing, all dependencies are removed from code and introduced as mock objects. Afterwards, a mocking framework by the name of Moq (mock you) is used to shorten unit tests and create a maintainable set of unit tests for the example application. "

    Slides and example code can be found in my previous blog post on this session: Mocking - VISUG session

    kick it on DotNetKicks.com


    Mocking - VISUG session

    Thursday evening, I did a session on Mocking for the VISUG (Visual Studio User Group Belgium). As promised, here is the slide deck I’ve used. The session will be available online soon, in the meantime you'll have to go with the slide deck.

    Demo code can also be downloaded: MockingDemoCode.zip (1.64 mb)

    Thank you for attending the session!

    kick it on DotNetKicks.com


    More ASP.NET MVC Best Practices

    In this post, I’ll share some of the best practices and guidelines which I have come across while developing ASP.NET MVC web applications. I will not cover all best practices that are available, instead add some specific things that have not been mentioned in any blog post out there.

    Existing best practices can be found on Kazi Manzur Rashid’s blog and Simone Chiaretta’s blog:

    After reading the best practices above, read the following best practices.

    kick it on DotNetKicks.com

    Use model binders where possible

    I assume you are familiar with the concept of model binders. If not, here’s a quick model binder 101: instead of having to write action methods like this (or a variant using FormCollection form[“xxxx”]):

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save()
    {
        // ...

        Person newPerson = new Person();
        newPerson.Name = Request["Name"];
        newPerson.Email = Request["Email"];

        // ...
    }

    You can now write action methods like this:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(FormCollection form)
    {
        // ...

        Person newPerson = new Person();
        if (this.TryUpdateModel(newPerson, form.ToValueProvider()))
        {
            // ...
        }

        // ...
    }

    Or even cleaner:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(Person newPerson)
    {
        // ...
    }

    What’s the point of writing action methods using model binders?

    • Your code is cleaner and less error-prone
    • They are LOTS easier to test (just test and pass in a Person)

    Be careful when using model binders

    I know, I’ve just said you should use model binders. And now, I still say it, except with a disclaimer: use them wisely! The model binders are extremely powerful, but they can cause severe damage…

    Let’s say we have a Person class that has an Id property. Someone posts data to your ASP.NET MVC application and tries to hurt you: that someone also posts an Id form field! Using the following code, you are screwed…

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(Person newPerson)
    {
        // ...
    }

    Instead, use blacklisting or whitelisting of properties that should be bound where appropriate:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save([Bind(Prefix=””, Exclude=”Id”)] Person newPerson)
    {
        // ...
    }

    Or whitelisted (safer, but harder to maintain):

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save([Bind(Prefix=””, Include=”Name,Email”)] Person newPerson)
    {
        // ...
    }

    Yes, that can be ugly code. But…

    • Not being careful may cause harm
    • Setting blacklists or whitelists can help you sleep in peace

    Never re-invent the wheel

    Never reinvent the wheel. Want to use an IoC container (like Unity or Spring)? Use the controller factories that are available in MvcContrib. Need validation? Check xVal. Need sitemaps? Check MvcSiteMap.

    Point is: reinventing the wheel will slow you down if you just need basic functionality. On top of that, it will cause you headaches when something is wrong in your own code. Note that creating your own wheel can be the better option when you need something that would otherwise be hard to achieve with existing projects. This is not a hard guideline, you’ll have to find the right balance between custom code and existing projects for every application you’ll build.

    Avoid writing decisions in your view

    Well, the title says it all.. Don’t do this in your view:

    <% if (ViewData.Model.User.IsLoggedIn()) { %>
      <p>...</p>
    <% } else { %>
      <p>...</p>
    <% } %>

    Instead, do this in your controller:

    public ActionResult Index()
    {
        // ...

        if (myModel.User.IsLoggedIn())
        {
            return View("LoggedIn");
        }
        return View("NotLoggedIn");
    }

    Ok, the first example I gave is not that bad if it only contains one paragraph… But if there are many paragraphs and huge snippets of HTML and ASP.NET syntax involved, then use the second approach. Really, it can be a PITA when having to deal with large chunks of data in an if-then-else structure.

    Another option would be to create a HtmlHelper extension method that renders partial view X when condition is true, and partial view Y when condition is false. But still, having this logic in the controller is the best approach.

    Don’t do lazy loading in your ViewData

    I’ve seen this one often, mostly by people using Linq to SQL or Linq to Entities. Sure, you can do lazy loading of a person’s orders:

    <%=Model.Orders.Count()%>

    This Count() method will go to your database if model is something that came out of a Linq to SQL data context… Instead of doing this, retrieve any value you will need on your view within the controller and create a model appropriate for this.

    public ActionResult Index()
    {
        // ...

        var p = ...;

        var myModel = new {
            Person = p,
            OrderCount = p.Orders.Count()
        };
        return View(myModel);
    }

    Note: This one is really for illustration purpose only. Point is not to pass the datacontext-bound IQueryable to your view but instead pass a List or similar.

    And the view for that:

    <%=Model.OrderCount%>

    Motivation for this is:

    • Accessing your data store in a view means you are actually breaking the MVC design pattern.
    • If you don't care about the above: when you are using a Linq to SQL datacontext, for example, and you've already closed that in your controller, your view will error if you try to access your data store.

    Put your controllers on a diet

    Controllers should be really thin: they only accept an incoming request, dispatch an action to a service- or business layer and eventually respond to the incoming request with the result from service- or business layer, nicely wrapped and translated in a simple view model object.

    In short: don’t put business logic in your controller!

    Compile your views

    Yes, you can do that. Compile your views for any release build you are trying to do. This will make sure everything compiles nicely and your users don’t see an “Error 500” when accessing a view. Of course, errors can still happen, but at least, it will not be the view’s fault anymore.

    Here’s how you compile your views:

    1. Open the project file in a text editor. For example, start Notepad and open the project file for your ASP.NET MVC application (that is, MyMvcApplication.csproj).

    2. Find the top-most <PropertyGroup> element and add a new element <MvcBuildViews>:

    <PropertyGroup>

    ...
    <MvcBuildViews>true</MvcBuildViews>

    </PropertyGroup>

    3. Scroll down to the end of the file and uncomment the <Target Name="AfterBuild"> element. Update its contents to match the following:

    <Target Name="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">

    <AspNetCompiler VirtualPath="temp"
    PhysicalPath="$(ProjectDir)\..\$(ProjectName)" />
    </Target>

    4. Save the file and reload the project in Visual Studio.

    Enabling view compilation may add some extra time to the build process. It is recommended not to enable this during development as a lot of compilation is typically involved during the development process.

    More best practices

    There are some more best practices over at LosTechies.com. These are all a bit advanced and may cause performance issues on larger projects. Interesting read but do use them with care.

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | General | Quality code

    ASP.NET MVC and the Managed Extensibility Framework (MEF)

    Microsoft’s Managed Extensibility Framework (MEF) is a .NET library (released on CodePlex) that enables greater re-use of application components. You can do this by dynamically composing your application based on a set of classes and methods that can be combined at runtime. Think of it like building an appliation that can host plugins, which in turn can also be composed of different plugins. Since examples say a thousand times more than text, let’s go ahead with a sample leveraging MEF in an ASP.NET MVC web application.

    kick it on DotNetKicks.com

    Getting started…

    The Managed Extensibility Framework can be downloaded from the CodePlex website. In the download, you’ll find the full source code, binaries and some examples demonstrating different use cases for MEF.

    Now here’s what we are going to build: an ASP.NET MVC application consisting of typical components (model, view, controller), containing a folder “Plugins” in which you can dynamically add more models, views and controllers using MEF. Schematically:

    Sample Application Architecture

    Creating a first plugin

    Before we build our host application, let’s first create a plugin. Create a new class library in Visual Studio, add a reference to the MEF assembly (System.ComponentModel.Composition.dll) and to System.Web.Mvc and System.Web.Abstractions. Next, create the following project structure:

    Sample Plugin Project

    That is right: a DemoController and a Views folder containing a Demo folder containing Index.aspx view. Looks a bit like a regular ASP.NET MVC application, no? Anyway, the DemoController class looks like this:

    [Export(typeof(IController))]
    [ExportMetadata("controllerName", "Demo")]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class DemoController : Controller
    {
        public ActionResult Index()
        {
            return View("~/Plugins/Views/Demo/Index.aspx");
        }
    }

    Nothing special, except… what are those three attributes doing there, Export and PartCreationPolicy? In short:

    • Export tells the MEF framework that our DemoController class implements the IController contract and can be used when the host application is requesting an IController implementation.
    • ExportMetaData provides some metadata to the MEF, which can be used to query plugins afterwards.
    • PartCreationPolicy tells the MEF framework that it should always create a new instance of DemoController whenever we require this type of controller. By defaukt, a single instance would be shared across the application which is not what we want here. CreationPolicy.NonShared tells MEF to create a new instance every time.

    Now we are ready to go to our host application, in which this plugin will be hosted.

    Creating our host application

    The ASP.NET MVC application hosting these plugin controllers is a regular ASP.NET MVC application, in which we’ll add a reference to the MEF assembly (System.ComponentModel.Composition.dll). Next, edit the Global.asax.cs file and add the following code in Application_Start:

    ControllerBuilder.Current.SetControllerFactory(
        new MefControllerFactory(
            Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins")));

    What we are doing here is telling the ASP.NET MVC framework to create controller instances by using the MefControllerFactory instead of ASP.NET MVC’s default DefaultControllerFactory. Remember that everyone’s always telling ASP.NET MVC is very extensible, and it is: we are now changing a core component of ASP.NET MVC to use our custom MefControllerFactory class. We’re also telling our own MefControllerFactory class to check the “Plugins” folder in our web application for new plugins. By the way, here’s the code for the MefControllerFactory:

    public class MefControllerFactory : IControllerFactory
    {
        private string pluginPath;
        private DirectoryCatalog catalog;
        private CompositionContainer container;

        private DefaultControllerFactory defaultControllerFactory;

        public MefControllerFactory(string pluginPath)
        {
            this.pluginPath = pluginPath;
            this.catalog = new DirectoryCatalog(pluginPath);
            this.container = new CompositionContainer(catalog);

            this.defaultControllerFactory = new DefaultControllerFactory();
        }

        #region IControllerFactory Members

        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            IController controller = null;

            if (controllerName != null)
            {
                string controllerClassName = controllerName + "Controller";
                Export<IController> export = this.container.GetExports<IController>()
                                                 .Where(c => c.Metadata.ContainsKey("controllerName")
                                                     && c.Metadata["controllerName"].ToString() == controllerName)
                                                 .FirstOrDefault();
                if (export != null) {
                    controller = export.GetExportedObject();
                }
            }

            if (controller == null)
            {
                return this.defaultControllerFactory.CreateController(requestContext, controllerName);
            }

            return controller;
        }

        public void ReleaseController(IController controller)
        {
            IDisposable disposable = controller as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }

        #endregion
    }

    Too much? Time for a breakdown. Let’s start with the constructor:

    public MefControllerFactory(string pluginPath)
    {
        this.pluginPath = pluginPath;
        this.catalog = new DirectoryCatalog(pluginPath);
        this.container = new CompositionContainer(catalog);

        this.defaultControllerFactory = new DefaultControllerFactory();
    }

    In the constructor, we are storing the path where plugins can be found (the “Plugins” folder in our web application). Next, we are telling MEF to create a catalog of plugins based on what it can find in that folder using the DirectoryCatalog class. Afterwards, a CompositionContainer is created which will be responsible for matching plugins in our application.

    Next, the CreateController method we need to implement for IControllerFactory:

    public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
    {
        IController controller = null;

        if (controllerName != null)
        {
            string controllerClassName = controllerName + "Controller"
            Export<IController> export = this.container.GetExports<IController>()
                                             .Where(c => c.Metadata.ContainsKey("controllerName"
                                                 && c.Metadata["controllerName"].ToString() == controllerName)
                                             .FirstOrDefault();
            if (export != null) {
                controller = export.GetExportedObject();
            }
        }

        if (controller == null)
        {
            return this.defaultControllerFactory.CreateController(requestContext, controllerName);
        }

        return controller;
    }

    This method handles the creation of a controller, based on the current request context and the controller name that is required. What we are doing here is checking MEF’s container for all “Exports” (plugins as you wish) that match the controller name. If one is found, we return that one. If not, we’re falling back to ASP.NET MVC’s DefaultControllerBuilder.

    The ReleaseController method is not really exciting: it's used by ASP.NET MVC to correctly dispose a controller after use.

    Running the sample

    First of all, the sample code can be downloaded here: MvcMefDemo.zip (270.82 kb)

    When launching the application, you’ll notice nothing funny. That is, untill you want to navigate to the http://localhost:xxxx/Demo URL: there is no DemoController to handle that request! Now compile the plugin we’ve just created (in the MvcMefDemo.Plugins.Sample project) and copy the contents from the \bin\Debug folder to the \Plugins folder of our host application. Now, when the application restarts (for example by modifying web.config), the plugin will be picked up and the http://localhost:xxxx/Demo URL will render the contents from our DemoController plugin:

    Sample run MEF ASP.NET MVC

    Conclusion

    The MEF (Managed Extensibility Framework) offers a rich manner to dynamically composing applications. Not only does it allow you to create a plugin based on a class, it also allows exporting methods and even properties as a plugin (see the samples in the CodePlex download).

    By the way, sample code can be downloaded here: MvcMefDemo.zip (270.82 kb)

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | General | MEF | MVC | Quality code

    Book review: ASP.NET 3.5 Social Networking

    image Last week, I found another book from Packt in my letterbox. This time, the title is ASP.NET 3.5 Social Networking, written by Andrew Siemer.

    On the back cover, I read that this book shows you how to create a scalable, maintainable social network that can support hundreds of thousands of users, multimedia features and stuff like that. The words scalable and maintainable seem to have triggered me: I started reading ASAP. The first chapter talks about what a social network is and proposes a new social network: Fisharoo.com, a web site for salt water aquarium fanatics, complete with blogs, forums, personal web sites, …

    The book starts by building a framework containing several features such as logging, mail sending, …, all backed-up by a dependency injection framework to enable fast replacement of several components. Afterwards, each feature of the Fisharoo.com site is described in a separate chapter: what is the feature, how will we store data, what do we need to do in our application to make it work?

    A good thing about this book is that it demonstrates several concepts in application design using a sample application that anyone who has used a site like Facebook is familiar with. The concepts demonstrated are some that any application can benefit from: Domain Driven Design, Test Driven Design (TDD), Dependency Injection, Model-View-Presenter, … Next to this, some third-party components like Lucene.NET are demonstrated. This all is very readable and understandable, really a must-read for anyone interested in these concepts!

    Bottom line of the story: it has been a while since I was enthousiast about a book, and this one clearly made me enthousiast. Sure, it describes stuff about building a social network, but I think that is only a cover for what this book is really about: building good software that is easy to maintain, test and extend.


    Verifying code and testing with Pex

    Pex, Automated White box testing for .NET

    Earlier this week, Katrien posted an update on the list of Belgian TechDays 2009 speakers. This post featured a summary on all sessions, of which one was titled “Pex – Automated White Box Testing for .NET”. Here’s the abstract:

    “Pex is an automated white box testing tool for .NET. Pex systematically tries to cover every reachable branch in a program by monitoring execution traces, and using a constraint solver to produce new test cases with different behavior. Pex can be applied to any existing .NET assembly without any pre-existing test suite. Pex will try to find counterexamples for all assertion statements in the code. Pex can be guided by hand-written parameterized unit tests, which are API usage scenarios with assertions. The result of the analysis is a test suite which can be persisted as unit tests in source code. The generated unit tests integrate with Visual Studio Team Test as well as other test frameworks. By construction, Pex produces small unit test suites with high code and assertion coverage, and reported failures always come with a test case that reproduces the issue. At Microsoft, this technique has proven highly effective in testing even an extremely well-tested component.”

    After reading the second sentence in this abstract, I was thinking: “SWEET! Let’s try!”. So here goes…

    Getting started

    First of all, download the academic release of Pex at http://research.microsoft.com/en-us/projects/Pex/. After installing this, Visual Studio 2008 (or 2010 if you are mr. or mrs. Cool), some context menus should be added. We will explore these later on in this post.

    What we will do next is analyzing a piece of code in a fictive library of string extension methods. The following method is intended to mimic VB6’s Left method.

    /// <summary>
    /// Return leftmost characters from string for a certain length
    /// </summary>
    /// <param name="current">Current string</param>
    /// <param name="length">Length to take</param>
    /// <returns>Leftmost characters from string</returns>
    public static string Left(this string current, int length)
    {
        if (length < 0)
        {
            throw new ArgumentOutOfRangeException("length", "Length should be >= 0");
        }

        return current.Substring(0, length);
    }

    Great coding! I even throw an ArgumentOutOfRangeException if I receive a faulty length parameter.

    Pexify this!

    Analyzing this with Pex can be done in 2 manners: by running Pex Explorations, which will open a new add-in in Visual Studio and show me some results, or by generating a unit test for this method. Since I know this is good code, unit tests are not needed. I’ll pick the first option: right-click the above method and pick “Run Pex Explorations”.

    Run Pex Explorations

    A new add-in window opens in Visual Studio, showing me the output of calling my method with 4 different parameter combinations:

    Pex Exploration Results

    Frustrated, I scream: “WHAT?!? I did write good code! Pex schmex!” According to Pex, I didn’t. And actually, it is right. Pex explored all code execution paths in my Left method, of which two paths are not returning the correct results. For example, calling Substring(0, 2) on an empty string will throw an uncaught ArgumentOutOfRangeException. Luckily, Pex is also there to help.

    When I right-click the first failing exploration, I can choose from some menu options. For example, I could assign this as a task to someone in Team Foundation Server.

    Pex Exploration Options In this case, I’ll just pick “Add precondition”. This will actually show me a window of code which might help avoiding this uncaught exception.

    Preview and Apply updates

    Nice! It actually avoids the uncaught exception and provides the user of my code with a new ArgumentException thrown at the right location and with the right reason. After doing this for both failing explorations, my code looks like this:

    /// <summary>
    /// Return leftmost characters from string for a certain length
    /// </summary>
    /// <param name="current">Current string</param>
    /// <param name="length">Length to take</param>
    /// <returns>Leftmost characters from string</returns>
    public static string Left(this string current, int length)
    {
        // <pex>
        if (current == (string)null)
            throw new ArgumentNullException("current");
        if (length < 0 || current.Length < length)
            throw new ArgumentException("length < 0 || current.Length < length");
        // </pex>

        return current.Substring(0, length);
    }

    Great! This should work for any input now, returning a clear exception message when someone does provide faulty parameters.

    Note that I could also run these explorations as a unit test. If someone introduces a new error, Pex will let me know.

    More information

    More information on Pex can be found on http://research.microsoft.com/en-us/projects/Pex/.

    kick it on DotNetKicks.com


    Categories: C# | Debugging | General | Pex | Quality code | Testing | VSTS

    The devil is in the details (Visual Studio Team System test policy)

    Have you ever been in a difficult situation where a software product is overall very good, but a small detail is going wrong? At least I've been, for the past week...

    Team System allows check-in policies to be enforced prior to checking in your code. One of these policies is the unit testing policy, which allows you to enforce a specific test list to be run prior to checking in your code.

    How it is...

    Now here's the catch: what if you have a Team Project with 2 solutions in it? How can I enforce the check-in policy to run tests from solution A only when something in solution A is checked in, tests from solution B with solution B changes, ...

    How it should be...

    Creating a custom check-in policy

    To be honest, there actually are quite enough examples on creating a custom check-in policy and how to install them. So I'll keep it short: here's the source code of my solution (VS2008 only).

    kick it on DotNetKicks.com


    Categories: C# | General | Projects | Quality code | Testing | VSTS

    Detailed code metrics with NDepend

    A while ago, I blogged about code performance analysis in Visual Studio 2008. Using profiling and hot path tracking, I measured code performance and was able to react to that. Last week, Patrick Smacchia contacted me asking if I wanted to test his project NDepend. He promised me NDepend would provide more insight in my applications. Let's test that!

    After downloading, extracting and starting NDepend, an almost familiar interface shows up. Unfortunately, the interface that shows up after analyzing a set of assemblies is a little bit overwhelming... Note that this overwhelming feeling fades away after 15 minutes: the interface shows the information you want in a very efficient way! Here's the analysis of a personal "wine tracking" application I wrote 2 years ago.

    Am I independent?

    Let's start with the obvious... One of the graphs NDepend generates, is a dependency map. This diagram shows all dependencies of my "WijnDatabase" project.

    Dependencies mapped

    One thing I can see from this, is that there probably is an assembly too much! WijnDatabase.Classes could be a candidate for merging into WijnDatabase, the GUI project. These dependencies are also shown in the dependency window.

    Dependencies mapped

    You can see (in the upper right corner) that 38 methods of the WijnDatabase assembly are using 5 members of WijnDatabase.Classes. Left-click this cell, and have more details on this! A diagram of boxes clearly shows my methods in a specific form calling into WijnDatabase.Classes.

    More detail on dependencies

    In my opinion, these kinds of views are really useful to see dependencies in a project without reading code! The fun part is that you can widen this view and have a full dependency overview of all members of all assemblies in the project. Cool! This makes it possible to check if I should be refactoring into something more abstract (or less abstract). Which is also analysed in the next diagram:

    Is my application in the zone of pain?

    What you can see here is the following:

    • The zone of pain contains assemblies which are not very extensible (no interfaces, no abstract classes, nor virtual methods, stuff like that). Also, these assemblies tend to have lots of dependent assemblies.
    • The zone of uselessness is occupied by very abstract assemblies which have almost no dependent assemblies.

    Most of my assemblies don't seem to be very abstract, dependencies are OK (the domain objects are widely used so more in the zone of pain). Conclusion: I should be doing some refactoring to make assemblies more abstract (or replacable, if you prefer it that way).

    CQL - Code Query Language

    Next to all these graphs and diagrams, there's another powerful utility: CQL, or Code Query Language. It's sort of a "SQL to code" thing. Let's find out some things about my application...

     

    Methods poorly commented

    It's always fun to check if there are enough comments in your code. Some developers tend to comment more than writing code, others don't write any comments at all. Here's a (standard) CQL query:

    // <Name>Methods poorly commented</Name>
    WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE PercentageComment < 20 AND NbLinesOfCode > 10  ORDER BY PercentageComment ASC
    // METHODS WHERE %Comment < 20 and that have at least 10 lines of code should be more commented.
    // See the definition of the PercentageComment metric here http://www.ndepend.com/Metrics.aspx#PercentageComment

    This query searches the top 10 methods containing more than 10 lines of code where the percentage of comments is less than 20%.

    CQL result 

    Good news! I did quite good at commenting! The result of this query shows only Visual Studio generated code (the InitializeComponent() sort of methods), and some other, smaller methods I wrote myself. Less than 20% of comments in a method consisting of only 11 lines of code (btnVoegItemToe_Click in the image) is not bad!

    Quick summary of methods to refactor

    Another cool CQL query is the "quick summary of methods to refactor". Only one method shows up, but I should probably refactor it. Quiz: why?

    CQL result

    Answer: there are 395 IL instructions in this method (and if I drill down, 57 lines of code). I said "probably", because it might be OK after all. But if I drill down, I'm seeing some more information that is probably worrying: cyclomatic complexity is high, there are many variables used, ... Refactoring is indeed the answer for this method!

    Methods that use boxing/unboxing

    Are you familiar with the concept of boxing/unboxing? If not, check this article. One of the CQL queries in NDepend is actually finding all methods using boxing and unboxing. Seems like my data access layer is boxing a lot! Perhaps some refactoring could be needed in here too.

    CQL result

    Conclusion

    Over the past hour, I've been analysing only a small tip of information from my project. But there's LOTS more information gathered by NDepend! Too much information, you think? Not sure if a specific metric should be fitted on your application? There's good documentation on all metrics as well as short, to-the-point video demos.

    In my opinion, each development team should be gathering some metrics from NDepend with every build and do a more detailed analysis once in a while. This detailed analysis will give you a greater insight on how your assemblies are linked together and offer a great review of how you can improve your software design. Now grab that trial copy!

    kick it on DotNetKicks.com


    Zend Studio + Teamprise = PHP development with Team Foundation Server

    Ever since I started developing PHPExcel, I noticed this option of connecting to CodePlex's Team Foundation Server using Teamprise for Eclipse (free CodePlex license here). Back in the days, I was developing using Zend Studio 4, but I recently upgraded to Zend Studio 6 for Eclipse.

    Now this "Eclipse" word triggered the idea that perhaps integration of Zend Studio and Team Foundation Server could be something that works. So I downloaded the Teamprise Eclipse plugin package, copied it to the Zend Studio plugins ditrectory. And yes: tight integration of Team Foundation Server with Zend Studio is possible!

    Let's rephrase that: it is perfectly possible to use Team Foundation Server in a mixed Microsoft / PHP development team as your main store for source control, work items, reporting, ...

    Here's a screenshot of my installation when accessing the CodePlex Team Foundation Server from Zend Studio:

    Zend Studio Workspace with Teamprise installed

      kick it on DotNetKicks.com


    Categories: General | PHP | Quality code

    ASP.NET MVC - Testing issues Q and A

    WTF? When playing around with the ASP.NET MVC framework and automated tests using Rhino Mocks, you will probably find yourself close to throwing your computer trough the nearest window. Here are some common issues and answers:

    Q: How to mock Request.Form?

    A: When testing a controller action which expects Request.Form to be a NameValueCollection, a NullReferenceException is thrown... This is due to the fact that Request.Form is null.

    Use Scott's helper classes for Rhino Mocks and add the following extension method:

    public static void SetupFormParameters(this HttpRequestBase request)
    {
        SetupResult.For(request.Form).Return(new NameValueCollection());
    }

    Q: I can't use ASP.NET Membership in my controller, every test seems to go bad...

    A: To test a controller using ASP.NET Membership, you should use a little trick. First of all, add a new property to your controller class:

    private MembershipProvider membershipProvider;

    public MembershipProvider MembershipProviderInstance {
        get {
            if (membershipProvider == null)
            {
                membershipProvider = Membership.Provider;
            }
            return membershipProvider;
        }
        set { membershipProvider = value; }
    }

    By doing this, you will enable the use of a mocked membership provider. Make sure you use this property in your controller instead of the standard Membership class (i.e. MembershipProviderInstance.ValidateUser(userName, password) instead of Membership.ValidateUser(userName, password)).

    Let's say you are testing a LoginController which should set an error message in the ViewData instance when authentication fails. You do this by creating a mocked MembershipProvider which is assigned to the controller. This mock object will be instructed to always shout "false" on the ValidateUser method of the MembershipProvider. Here's how:

    LoginController controller = new LoginController();
    var fakeViewEngine = new FakeViewEngine();
    controller.ViewEngine = fakeViewEngine;

    MockRepository mocks = new MockRepository();
    using (mocks.Record())
    {
        mocks.SetFakeControllerContext(controller);
        controller.HttpContext.Request.SetupFormParameters();

        System.Web.Security.MembershipProvider membershipProvider = mocks.DynamicMock<System.Web.Security.MembershipProvider>();
        SetupResult.For(membershipProvider.ValidateUser("", "")).IgnoreArguments().Return(false);

        controller.MembershipProviderInstance = membershipProvider;
    }
    using (mocks.Playback())
    {
        controller.HttpContext.Request.Form.Add("Username", "");
        controller.HttpContext.Request.Form.Add("Password", "");

        controller.Authenticate();

        Assert.AreEqual("Index", fakeViewEngine.ViewContext.ViewName);
        Assert.IsNotNull(
            ((IDictionary<string, object>)fakeViewEngine.ViewContext.ViewData)["ErrorMessage"]
        );
    }

    More questions? Feel free to ask! I'd be happy to answer them.

    kick it on DotNetKicks.com