Garry Pilkington


Application Developer
Liverpool, UK
Full Circle

Things have been a little bit hectic these past 6 months hence the lack of posts. My excuse is a good one though, my wife gave birth to our first son Tom back in September and it has been one hell of a rollercoaster ride since then. Things have settled back down now thank hevens.

My last development gig didn't quite work out so now I have took the plunge and started contracting. It turns out my first contract is with the NHS trust that I started my development career with, which seems a bit wierd as that was 10 years ago. A lot has changed in the techniques and tools the NHS now use to develop with, there is a lot more .net with a slant towards the web side of the spectrum (at least in this NHS trust). They are really getting to grips with the MVC platform, so you will hopefully see some MVC posts coming up.

The really suprising thing is that the Intranet I developed back in 2001 (classic asp migrated to .net 1.0) is still up and running and will finally be fazed out these coming weeks (to Sharepoint). It is like seeing an old friend all grown up.

 

Branching and Merging with TortoiseSVN

For this example I am using Visual Studio 2010, TortoiseSVN 1.6.6, Subversion 1.6.6 and AnkhSVN 2.1.7819.411, so if you are using different versions, some of these screen shots may differ.

This is assuming you have your code checked in to the trunk directory and have a standard SVN structure of trunk, branches and tags. There are a number of developers who prefer to develop solely in a branch and never touch the trunk, but the process is generally the same and you may be on a small team and prefer to work in the trunk and branch occasionally.

There are three steps to successful branching. First you branch, then when you are ready you need to reintegrate any changes that other developers may have made to the trunk in to your branch. Then finally when your branch and the trunk are in sync, you merge it back in to the trunk.

Branch

  1. Right click project root in Windows Explorer > TortoiseSVN > Branch/Tag
    1 - 1

  2. Enter the branch label in the ‘To URL’ box. For example /branches/1.1
    1 - 2

  3. Choose Head revision
  4. Check Switch working copy
  5. Click OK
  6. Make any changes to branch
    1 - 3

  7. Make any changes to trunk
    1 - 4

  8. Commit any changes
    1 - 5

For this example I copied the project to another location prior to branching and made changes to that using Notepad++. Then committed it to SVN, as this directory is mapped to the trunk, that is what gets updated.

 

Merge Trunk with Branch

  1. Right click project root in Windows Explorer > TortoiseSVN > Merge
    2 - 1

  2. Choose ‘Merge a range of revisions’
    2 - 2

  3. In ‘URL to merge from’ choose your trunk
    2 - 3

  4. Click Next, then the ‘test merge’ button. This will highlight any conflicts. Here we have one conflict we will need to resolve because we made a change and checked in to trunk earlier
    2 - 4


    2 - 5
  5. Click merge. Now we have the opportunity to edit that conflict
    2 -5 - a

  6. This will open up TortoiseMerge which will allow us to resolve the issue. In this case I want both changes.
    2 -5 - b


    2 -5 - c


    2 -5 - d

  7. Perform an Update then Commit
    2 - 7 - a


    2 - 7 - b

  8. Reloading in Visual Studio shows we have all changes that have been made to both trunk and branch.2 - 8

Merge Branch with Trunk

  1. Switch working copy by right clicking project root in Windows Explorer > TortoiseSVN > switch3 - 3

  2. Switch to the trunk then ok
    3 - 4

  3. Right click project root in Windows Explorer > TortoiseSVN > merge
    3 - 5

  4. Choose ‘Reintegrate a branch’
    3 - 6

  5. In ‘From URL’ choose your branch then next
    3 - 7

  6. Click ‘Test merge’, this shouldn’t show any conflicts
    3 - 8

  7. Click Merge
  8. Perform Update then Commit
    3 - 10


    3 - 10 - a

  9. Open project in Visual Studio, we now have all changes.

So there we have it we are connected back to the trunk and have all the updates merged.

Setting Up MVC Using StructureMap, Moq and NUnit...Quickly

When I was first attracted to the Microsoft MVC Framework, one of my main ambitions was to develop using a more test driven approach. There are ways to include Unit testing with WebForms, but the friction was just too much to justify on the web projects I was involved with.

As soon as I started using MVC I was amazed at how easy it was to incorporate unit testing and isolation frameworks; in a way it became more of a natural process.

Here in this post I am quickly covering getting up and running with unit testing, isolation frameworks and MVC.

My tools of choice are:-

This example is a simple green field site; the typical File >> New Project >> MVC application.

So we have our site, I want data from a database (in this example I won’t be bothering with creating a data store, which shows just how handy stubs can be).

I want to run a test on the data and send it off to the view, simple stuff.

In Models, I want to create a data repository, but I don’t want to code against a concrete type, I will use an interface.


public interface IRepository
{
    int GetTotalOrders();
}
 
public class Repository : IRepository
{
    public int GetTotalOrders()
    {
        return 55;
    }
}

Here I have a simple method which in this case returns a hard coded integer.

So far so good, the site compiles.

I want the controller to handle this method call via an Order class like this.


public class Order
{
    private IRepository Repository;
 
    public Order(IRepository repository)
    {
        Repository = repository;
    }
 
    public int GetTotalOrders()
    {
        return Repository.GetTotalOrders();
    }
}

As can be seen there are two SOLID principles in use here. The Order is dependent on the Repository class, but this dependency is injected in to the constructor. Also it is handed an interface and not a concrete type.

So my controller can call the GetTotalOrders method on the Order and let that handle the repository, but before all that I want a test in place that will make sure I am returning that data from the repository.

Of course in the real world I don’t want to touch the database, and in this case I don’t even have one. Here is the unit test that stubs out the repository call.


[Test]
public void GetTotalOrders_returns_56()
{
    //Arrange
    var repositoryMock = new Mock<IRepository>();
    repositoryMock.Setup(r => r.GetTotalOrders()).Returns(56);
 
    Order orders = new Order(repositoryMock.Object);
 
    //Act
    int expectedValue = 56;
    int actualValue = orders.GetTotalOrders();
 
    //Assert
    Assert.AreEqual(expectedValue, actualValue);
}

In this case I am forcing the repository to return an integer of 56, not the 55 from the concrete class. The solution compiles and the test passes.

mvc_post_1

Great, but how do we code this for the controller.


public class HomeController : Controller
{
    public HomeController()
    {
    }
 
    public ActionResult Index()
    {
        Repository repository = new Repository();
 
        Order orders = new Order(repository);
 
        int totalOrders = orders.GetTotalOrders();
 
        ViewData["TotalOrders"] = totalOrders.ToString();
 
        return View();
    }
}

This works fine, but I don’t want the Index method to be responsible of creating the Repository object, so we take that out and let the constructor handle that.


public class HomeController : Controller
{
    private readonly IRepository Repository;
 
    public HomeController(IRepository repository)
    {
        Repository = repository;
    }
 
    public ActionResult Index()
    {
        Order orders = new Order(Repository);
 
        int totalOrders = orders.GetTotalOrders();
 
        ViewData["TotalOrders"] = totalOrders.ToString();
 
        return View();
    }
}

Now it compiles ok, the tests run ok, but the web application fails.


mvc_post_2

This is where we need to start injecting the dependencies needed. We need both an ApplicationRegistry and Bootstrapper class.


public class ApplicationRegistry : Registry
    {
        public ApplicationRegistry()
        {
            ForRequestedType<IRepository>()
             .TheDefault.Is.OfConcreteType<Repository>();
        }
    }

 

public static class Bootstrapper
{
    public static void ConfigureStructureMap()
    {
        ObjectFactory.Initialize
            (x => x.AddRegistry(new ApplicationRegistry()));
    }
}

The ApplicationRegistry class reads very fluently and simply injects any occurrence of the IRepository type with the Repository concrete type.

Next we need a controller factory which inherits from the MVC DefaultControllerFactory and is called from the Application_Start in the Global.asax file.


public class StructureMapControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(Type controllerType)
    {
        if (controllerType == null) return null;
 
        try
        {
            return ObjectFactory.GetInstance(controllerType) as Controller;
        }
 
        catch (StructureMapException)
        {
            System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
 
            throw;
        }
    }
}


protected void Application_Start()
{
    Bootstrapper.ConfigureStructureMap();
    ControllerBuilder.Current.SetControllerFactory
      (new StructureMapControllerFactory());
 
    RegisterRoutes(RouteTable.Routes);
}

Now rebuilding and running the site we successfully retrieve the value from the repository.

WinMerge as a Comparison Tool in Visual Studio 2008

Ok I know VS 2010 is the new toy to be seen playing around with, but as I have just recently  got delivery of my new Windows 7 pc I thought I would document how to get WinMerge to work as a comparison tool with VS2008 Team System. If for anything, so I know myself when the time comes to do it all over again.

Team Foundation Server does have a built in comparison and merge tool, but personally I find WinMerge to be far better. Oh and it is free.

  1. After downloading and installing, you need to configure Visual Studio. Go to Tools >> Options

  2. Find the ‘Source Control’ section in the tree view and select ‘Visual Studio Team Foundation Server’

  3. Click the ‘Configure User Tools’ button.

    WinMerge1
  4. Click on the ‘Add’ button on the ‘Configure User Tools’ window.

  5. Enter these values in the textboxes:

    Extension: *
    Operation: Compare
    Command: C:\Program Files\WinMerge\WinMergeU.exe (or wherever you have installed WinMerge to)
    Arguments: /x /e /ub /wl /dl %6 /dr %7 %1 %2

    WinMerge2
  6. Click OK all the way back down to get back to the main IDE.

Now when you view a file history from Solution Explorer it will start up WinMerge.

Windows Explorer and Microsoft SkyDrive

Bit by bit more of our lives are moving in to the cloud. I have been a bit late to this party as I have never published my photos to Flikr or any other image sharing site. That is mainly because I want to keep them secret and I am really just after an off site backup solution. What I have been after is great easy storage with enough disk space for all my photographs. There are plenty of places out on the web which offer this service I know, but I want it cheap or free. This is where Microsoft SkyDrive comes in with a whopping 25GB of private storage.

Great, but what I was after was simple integration with the Windows UI without having to go through a web interface. This had deterred me from using it until I came across a piece of software called Cloud Desktop from Gladinet. After installation and a bit of minor configuration, it gives you access to your SkyDrive through a virtual network drive. It comes in three editions, with the Starter being free. The main limit of the free version is that you can only upload a maximum of 1000 files at a time. Simply drag and drop your files in to the virtual drive and you are away. A great resource to help you get up and running is this link from newbTech.

For easy synchronization between Windows directories and the cloud, there is always Live Mesh, but it would be great if Microsoft would release a SkyDrive API so we could have more control through our applications, perhaps hooking up the Sync Framework.

Multiple Strongly Typed Partial Views in MVC

Creating strongly typed views with the ASP.Net MVC framework is really easy, but what if you want to have multiple types on the same view? One way to achieve this is to create partial views for each type and creating a combined view model. Then the view will inherit this combined view model and each partial view will inherit from its component types.

In the following simple example I have a view which itself displays two partial views. This view inherits from a type I have called CombinedViewModel.

The hosting view

   <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
   Inherits="System.Web.Mvc.ViewPage<CombinedViewModel>" %>
   ...
    
   
   <asp:Content ID="Content1" ContentPlaceHolderID="MainContent"
   runat="server">
        
   <% Html.RenderPartial("PartialView1", ViewData.Model.Header); %>
   <% Html.RenderPartial("PartialView2", ViewData.Model.Detail); %>
    
  </asp:Content>

 

The controller passes the types in to the CombinedViewModel.

public ActionResult Detail(int id)
 {
  Header header = DataRepository.GetHeader(id);
  List<Detail> detail = DataRepository.GetDetail(id);
 
  CombinedViewModel viewData = new CombinedViewModel(header, detail);
 
  return View(viewData);         
 }

The CombinedViewModel

public class CombinedViewModel
{
 public Header  Header { get; private set; }
 public IEnumerable<Detail> Detail { get; private set; }  
 
public JobDetailViewModel(Header header, IEnumerable<Detail> detail)
{
 Header = header;
 Detail= detail;
}
}

 

So now each of the partial views can access the types they need.

The PartialViews

<%@ Control Language="C#"

Inherits="System.Web.Mvc.ViewUserControl<TestApp.Models.Header>" %>

<%= Model.CustomerTitle%>

<%@ Control Language="C#"

Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<TestApp.Models.Detail>>" %>

<%= Model.OrderNumber%>
Posted: Oct 20 2009, 09:29 AM by capgpilk | with 12 comment(s)
Filed under: , , ,
Unit Testing Videos

The Learn Visual Studio.net website has just published a new series on unit testing, covering an introduction to unit testing, using MSTest, and NUnit. These are always good sources of practical information to help you get up to speed on anything .net. Go check them out.

TempData and DropDownList in ASP.Net MVC

TempData

Sometimes while developing web applications, you have a need to keep certain data between web requests. In asp.Net MVC you can use TempData which will keep hold of any values you pass to it for that request and the next request when it is then removed. This is a great way of keeping form elements at a particular state during form submission from an mvc view. In the following example I will briefly explain how to render a drop down list populated with data which will keep the selected value across form submission.

The ActionResult

In the ActionResult in the controller for the view you get the value of the drop down selected item which is held in the FormCollection. Then simply call a method that returns a IList<SelectListItem> collection, passing in the selected item. The resulting collection is then passed to a TempDataDictionary which is in turn passed back to the view.

   1: public ActionResult DistrictsView(FormCollection collection)
   2: {
   3:   int selectedValue = Convert.ToInt32(collection["Districts"]);
   4:  
   5:   TempData["Districts"] = DropDownPopulators.GetDistricts(selectedValue);
   6:  
   7:   return View();
   8:  
   9: }

Keeping the selected value

The drop down list takes a collection of SelectlistItems in the form of text/value pairs. What the following method does is generate a dictionary collection of districts and the associated key, then creates the IList<SelectListItem> for the drop down, but it also sets the selected property to true for the selected value passed in from the view. The GetDistrictList method call simply returns a dictionary collection from the database of district and integer values.

   1: public static IList<SelectListItem> GetDistricts(int selectedValue)
   2: {
   3:   IList<SelectListItem> districts = new List<SelectListItem>();
   4:   Dictionary<int, string> districtCollection 
   5:    = DataRepository.GetDistrictList();  
   6:  
   7:   SelectListItem itemAll = new SelectListItem();
   8:  
   9:   itemAll.Value = "0";
  10:   itemAll.Text = "All";
  11:   districts.Add(itemAll);   
  12:  
  13:   foreach (var dist in districtCollection)
  14:   {
  15:    if (dist.Key == selectedValue)
  16:    {
  17:     SelectListItem item = new SelectListItem();  
  18:  
  19:     item.Value = dist.Key.ToString();
  20:  
  21:     item.Text = dist.Value;
  22:     item.Selected = true;
  23:     districts.Add(item);
  24:    }
  25:    else
  26:    {
  27:     SelectListItem item = new SelectListItem();  
  28:  
  29:     item.Value = dist.Key.ToString();
  30:  
  31:     item.Text = dist.Value;
  32:     item.Selected = false;
  33:     districts.Add(item);
  34:    }
  35:   }
  36:     return districts;
  37: }

Displaying the DropDownList in a view

   1: <%=Html.DropDownList("Districts", TempData["Districts"] 
   2: as List<SelectListItem>
   3:  , new { @onchange = "this.form.submit();" })%>

This binds the Districts TempData to the DropDownList helper in the view. The clever bit here is the creation of the form submit java script when the drop down is changed.

Posted: Sep 29 2009, 11:15 AM by capgpilk | with 7 comment(s) |
Filed under: , ,
Code Snippet Plugin for Live Writer

For anybody who regularly displays code using Live Writer, then this plugin by Leo Vildosola is a must to check out. When ever I do a rebuild of any of my computers this has to go on and I always have trouble remembering where I found it.

So here are a couple of links.

Leo Vilosola’s blog

Plugin site at codeplex

LINQ Projection

just recently I have been doing quite a bit of work with LINQ and L2S in particular. Although LINQ is nothing new now and I am sure the vast majority of readers out there have had some form of introduction to LINQ. However one of the great things that I still find fascinating is a technique called projection. This is a way to shape data coming back from a query into something more akin to what you want.

   1: class User
   2: {
   3:     public string UserFullName { get; set; }
   4:     public double HoursWorked { get; set; }
   5: }
   6:  
   7: class Program
   8: {
   9:     static void Main()
  10:     {
  11:         List<User> users = new List<User>();
  12:  
  13:         users.Add(new User { HoursWorked = 12.5d, 
  14:             UserFullName = "Ann Admin" });
  15:         users.Add(new User { HoursWorked = 6.5d, 
  16:             UserFullName = "Test User" });
  17:         users.Add(new User { HoursWorked = 8.5d, 
  18:             UserFullName = "Test User" });
  19:         users.Add(new User { HoursWorked = 3.5d, 
  20:             UserFullName = "Test User" });
  21:  
  22:         var q = from user in users
  23:                 where user.UserFullName.Equals("Test User")
  24:                 select new
  25:                  {
  26:                      user.UserFullName,
  27:                      user.HoursWorked,
  28:                      HoursRemaining = (8.5 - user.HoursWorked)
  29:                  };
  30:  
  31:         foreach (var list in q)
  32:         {
  33:             Console.WriteLine(list.UserFullName + " - "
  34:                 + list.HoursWorked
  35:                 + "(" + list.HoursRemaining + ")");
  36:         }
  37:  
  38:         Console.Read();
  39:     }
  40: }

Here the query is creating a new type with three fields. This is especially useful if like above you are doing some form of calculation which you want to use, but is not represented anywhere in the data model.

Posted: Sep 08 2009, 10:00 AM by capgpilk | with 2 comment(s)
Filed under: , ,
More Posts Next page »