Garry Pilkington


Application Developer
Liverpool, UK
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 6 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: , ,
Complex Types in the Entity Framework

In this post I will describe the process you need to go through to get a stored procedure to return a complex type in the Entity Framework.

It is very easy in the Entity Framework to quickly create crud functions that will manipulate data in your tables. However if you want to use stored procedures that return data that is not mapped to an entity from your database, then there are a few more hoops you need to jump through.

Firstly, by examining the stored procedure, you can determine what data types are returned from the stored procedure.

This following method is a quick and dirty one I have used, there may be a better way to do this, and if there is please let me know. There is a tool called Entity Developer from devart which may do the same, but as yet I haven’t had the chance to use it.

  1. Switch to your *.edmx file and drop a new entity from the toolbox on to the design surface. You may need to delete the Id property that is automatically created if you don’t need it.
    2
  2. Then right click on any of the entries in the model browser and choose ‘Update Model From Database’
    1
  3. Choose any tables that your procedure uses from the Add tab. This will map the tables as entities, allowing you to simply copy and paste entity properties from the tables into your new entity.
  4. Add your stored procedure.
  5. Right click on ‘Function Imports’ within the Entity Container in the Model Browser and choose ‘Create Function Import’.
    3
  6. This then gives you the options to Choose the stored procedure, its name and most importantly the Entity that it will be imported to. Choose your new entity you have just created.
    4

Now your new entity can be called

   1: ProjectMVCEntities myEntities = new ProjectMVCEntities();
   2:                 
   3: var viewData = myEntities.Job(0, 4).ToList();
   4:         
   5: return View();

This is taken from an MVC project, hence the return value of View(), but I hope you get the idea.

Now the stored procedure will be executed with any required parameters and the Job entity will hold the data.

LINQ to XML Quick Brain Dump

LINQ to XML is a simple toolset that allows developers to easily interact with XML, whether it be in file form of on the wire in string form.

Write to an XML file

There are a few methods within the System.Xml.Linq namespace which make this interaction a breeze. The four main ones are:-

  • XDocument – Method which creates the XML document
  • XDeclaration – Allows you to set the declaration at the top of the file.
  • XElement – Creates a hierarchical element structure
  • XAttribute – Creates any attributes related to an element.

The following code shows a very simple way to generate an XML document for members of a club.

   1: Member[] members = new[] {
   2:  new Member{Age = 33, FullName = "John Havers", Title = "Mr"},
   3:  new Member{Age = 28, FullName = "Robin Southgate", Title = "Mrs"},
   4:  new Member{Age = 45, FullName = "Paul Chatwell", Title = "Mr"},
   5:     };
   6:  
   7: XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
   8:           new XElement("members",
   9:           from member in members
  10:           select new XElement("member",
  11:                  new XAttribute("age", member.Age),
  12:                  new XAttribute("title", member.Title),
  13:                  new XElement("fullname", member.FullName)
  14:         )
  15:     )
  16: );
  17:  
  18:         doc.Save(@"c:\members.xml");

This would generate this XML file.

   1: <?xml version="1.0" encoding="utf-8" standalone="yes" ?>
   2:     <members>
   3:      <member age="33" title="Mr">
   4:       <fullname>John Havers</fullname>
   5:      </member>
   6:      <member age="28" title="Mrs">
   7:       <fullname>Robin Southgate</fullname>
   8:      </member>
   9:      <member age="45" title="Mr">
  10:       <fullname>Paul Chatwell</fullname>
  11:      </member>
  12:     </members>

Reading from an XML file

Firstly use the Load method of the XDocument class, then a simple LINQ query will return all elements within the root element like this.

   1: IEnumerable<XElement> q = from c in loaded.Root.Elements("member")
   2:                                   select c;
   3:  
   4:         foreach (XElement element in q)
   5:         {
   6:             foreach (XElement r in element.Elements())
   7:             {
   8:                 Console.WriteLine(r.Value);
   9:             }
  10:         }

This query lists all the elements called ‘member’ within the root. Then for each member element it will again for each through for any elements within those. In our example the members full name is located there, so a simple value output will write the data to the console.

You can still use var for the query, but during running of the code it is possible to determine the resultant type.

debug

This shows that it is of type  XElement and that it is enumerable so you can change var to IENumerable<XElement> to give the code more meaning.

Posted: Aug 25 2009, 09:10 PM by capgpilk | with 4 comment(s)
Filed under: , , ,
Do you test your private methods?

There is ample discussion on the blogosphere as to why you should or shouldn't test your private methods. 

In the 'NO camp'

http://www.redhillconsulting.com.au/blogs/simon/archives/000119.html, http://www.lostechies.com/blogs/chad_myers/archive/2008/11/21/do-not-test-private-methods.aspx

In the 'YES camp'

http://beust.com/weblog/archives/000303.html

I think there is some confusion as to why you should or shouldn’t.

Test-Driven Development

If you personally are practicing TDD then you are testing a whole chunk of code before and after refactoring. If your code passes the tests before refactoring, then you can be sure that any extracted methods are covered. That is to say you don’t need to test these methods (private or public) as their containing code have tests already.

Ok so you write your test, it fails. You then write your code to make the test pass. You are green. Then you refractor. After you refractor, you realize the method can be made private as nothing outside the class needs to know it is there. So now you have a private without any immediately related test (even though it is actually covered with the pre-refractored test).

Now if at some point in the future another developer comes along and adds a private method without any associated test; you now have two private methods, one with a test, one without. A quick glance at the source code of the test suite may not show that the first private method is covered. Perhaps forcing a rule that all methods should be tested should eliminate those non tested methods from creeping in. It may be a case of refactoring your tests to make sure each method has at least one associated test.

Regression testing

If you are working with legacy code and you are required to make changes to some public or even private methods, it would be wise to wrap tests around these methods, that way you can be sure they are functioning the same after the changes as they were before. This would be the same case for both public and private.

Code Coverage

Code coverage is the extent to which code has been tested; that is all code. So if you have 2 public methods and 98 private methods (just for example, this would be a ridiculously large class) and you have tests only for the public methods and not the private ones; do you have 100% code coverage? I wouldn't say so. I wouldn't be confident with a situation where I don't have any coverage of private methods.

I like the quote from  Cedric Beust post.

"if it can break, test it"

More Posts Next page »