# Wednesday, December 19, 2012

At BUILD, during this session by Entity Framework Program Manager Rowan Miller, Entity Framework 6 beta was announced and made publicly available.  You can get the Entity Framework 6 beta bits via NuGet.  Currently they are only available via the Package Manager Console, more info can be found on the EF NuGet page

Entity Framework 6 is the first new version of EF since the announcement earlier this year that the product would be Open Sourced.  This means that not only is the source available but the builds of EF6 beta are available as soon as the code is checked in.  Entity Framework is hosted on CodePlex.

The EF 6 roadmap defines in detail what is currently in the works and what is still on the board as far as features and improvements for EF 6.  In this post I want to focus on one new addition to Entity Framework that I find very compelling.

One of the great features introduced in .NET 4.5 was the task-based asynchronous functionality using the async and await keywords.  Now with EF 6 comes support for asynchronous querying and saving using the same async and await coding convention.  Let’s first look at asynchronous querying.

The following asynchronous extension methods have been implemented for querying your data context and as you’d expect they are the asynchronous versions of their synchronous namesakes:

  • AllAsync
  • AnyAsync
  • AverageAsync
  • ContainsAsync
  • CountAsync
  • FindAsync
  • FirstAsync
  • FirstOrDefaultAsync
  • LoadAsync
  • LongCountAsync
  • MaxAsync
  • MinAsync
  • SingleAsync
  • SingleOrDefaultAsync
  • SumAsync
  • ToArrayAsync
  • ToDictionaryAsync
  • ToListAsync

In the code snippet below you can see an example of using the ForEachAsync method to asynchronously loop through all the manufacturers in my data context and print them to the console.

private static async Task PrintAllManufacturers() {
    using (DataContext context = new DataContext()) {
        await context.Manufacturers.ForEachAsync(m => Console.WriteLine("{0} : {1}", m.Name, m.Country));

Another piece of Entity Framework functionality that the asynchronous goodness has been added too is saving. Below is an example of adding a manufacturer and asynchronously saving the changes.

private static async Task AddManufacturer(string name, string country) {
    using (DataContext context = new DataContext()) {
        context.Manufacturers.Add(new Manufacturer {Name = name, Country = country});
        await context.SaveChangesAsync();

Using the asynchronous pattern is a great way to provide a more responsive user experience and now loading data asynchronously with Entity Framework has become much easier.

posted on Wednesday, December 19, 2012 11:08:48 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
# Friday, June 29, 2012

A great new feature in ASP.NET MVC is the ability to bundle scripts and CSS files and register them as a group.  More detail on this functionality can be found here.  Because by default all the scripts and CSS classes in a new MVC 4 project are registered using bundles I felt a little dirty in my previous posts referencing my Kendo UI scripts and CSS files each individually.  I rectified that.

So I started the rectification process by adding entries to the BundleConfig.cs.  In this file is where you create and configure your bundles.  Out of the box there are a number of bundles configured so all I needed to was follow the same conventions when creating my bundles. 

bundles.Add(new ScriptBundle("~/bundles/kendojs").Include(
bundles.Add(new StyleBundle("~/Content/kendocss").Include(

Obviously I took the least amount of scripts I needed to get my contrived sample created, but you can add whatever scripts you need.

After creating the bundles I need to register or “Render” them as the method is called.  Have to admit I am not a fan of “Render” as the method name.  In the past “Render” has always had a visual connotation.  The registering of the bundles for this example is taking place in the _layout.cs, but you could do the same thing directly in your ASP.NET MVC View.

@Styles.Render([...other CSS bundles], "~/Content/kendocss")
@Scripts.Render([...other Script bundles],"~/bundles/kendojs")

And that’s it.  Now I have my Kendo UI scripts and CSS files registered/referenced/rendered using the new bundling features of ASP.NET MVC

Code is available on GitHub.

posted on Friday, June 29, 2012 3:38:27 PM (Central Daylight Time, UTC-05:00)  #    Comments [4]
# Monday, June 25, 2012

Note: If you are following along at home you may have noticed that the number of the series posts has changed.  I have taken some *poetic license* and decided that the previous post introducing Kendo UI for ASP.NET MVC was actually part part 3 of the original series on Kendo UI in ASP.NET MVC as well as part 1 of a new series on Kendo UI for ASP.NET MVC.  Clear as mud, right?

To stay in line, and catch up, with the pre-Kendo UI for ASP.NET MVC series this post is going to show you how to implement the Kendo UI AutoComplete control using the HtmlHelper extension.  In case you didn’t catch the original post on implementing the AutoComplete using Kendo UI (core/non-mvc) in ASP.NET MVC, the Kendo UI AutoComplete control is a text box that has an associated list of items that when text is entered into it a suggestion list is displayed allowing the user to select an item.

To get started follow steps 1 - 6 in the previous post to prep a new solution.

Next I created a server side model: Manufacturer.cs

namespace Part2_AutoComplete.Web.Models
    public class Manufacturer
        public int Id { get; set; }
        public string Name { get; set; }

As you can see the view the model is a very simple class that contains only an Id and a Name field.

After that I created my view: Index.cshtml

@using Kendo.Mvc.UI
@model IEnumerable<Part2_AutoComplete.Web.Models.Manufacturer>
    ViewBag.Title = "Kendo UI for ASP.NET MVC: Part 2 - AutoComplete";
    .DataSource(source => {
            source.Read(read =>
                        read.Action("GetManufacturers", "Home");

Lastly we can code our controller: HomeController.cs

namespace Part2_AutoComplete.Web.Controllers {
    public class HomeController : Controller {
        public ActionResult Index() {
            return View(new List<Manufacturer> {new Manufacturer {Id = 1, Name = "Aston Martin"}});
        public JsonResult GetManufacturers() {
            string searchValue = Request.Params["filter[filters][0][value]"];
            IList<Manufacturer> manufacturers = BuildManufacturersList().Where(x => x.Name.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase)).ToList();
            return Json(manufacturers, JsonRequestBehavior.AllowGet);
        private IEnumerable<Manufacturer> BuildManufacturersList() {
            IList<Manufacturer> manufacturers = new List<Manufacturer>();
            manufacturers.Add(new Manufacturer {Id = 1, Name = "Aston Martin"});
            manufacturers.Add(new Manufacturer {Id = 2, Name = "Audi"});
            manufacturers.Add(new Manufacturer {Id = 3, Name = "Buggati"});
            manufacturers.Add(new Manufacturer {Id = 4, Name = "BMW"});
            manufacturers.Add(new Manufacturer {Id = 5, Name = "Chevrolet"});
            manufacturers.Add(new Manufacturer {Id = 6, Name = "Ferrari"});
            manufacturers.Add(new Manufacturer {Id = 7, Name = "Ford"});
            manufacturers.Add(new Manufacturer {Id = 8, Name = "Lamborghini"});
            manufacturers.Add(new Manufacturer {Id = 9, Name = "Mazda"});
            manufacturers.Add(new Manufacturer {Id = 10, Name = "McLaren"});
            manufacturers.Add(new Manufacturer {Id = 11, Name = "Mercedes Benz"});
            manufacturers.Add(new Manufacturer {Id = 12, Name = "Porsche"});
            return manufacturers;

That’s it.  Now that we are caught up with the transition to Kendo UI for ASP.NET MVC in the next post we can move on to something fresh and new…and Kendo UI certainly has a lot to offer in that area!

The code is available on GitHub.

posted on Monday, June 25, 2012 7:37:36 AM (Central Daylight Time, UTC-05:00)  #    Comments [2]
# Tuesday, June 19, 2012

Back in April I started a series of posts related to using Kendo UI in ASP.NET MVC.  Last month the Kendo team released the first beta of Kendo UI for ASP.NET MVC.  So, long story short the blog posts on Kendo UI will continue but from this point forward they will move from implementing Kendo UI proper in ASP.NET MVC to using Kendo UI for ASP.NET MVC.

Kendo UI for ASP.NET MVC includes the complete Kendo UI suite (Web, Mobile, DataViz) plus a set .NET wrappers to be used with ASP.NET MVC that leverage exciting features of MVC such as data annotations, editor/display templates and validation.  Those of you still using the WebForms view engine are safe,  the wrappers work in both the Razor view engine and the WebForms view engine.

To get started download the Kendo UI for ASP.NET MVC bits and install them.  The bits include, what I would call, the Kendo UI core features plus all the ASP.NET MVC specific features so there is no need install both Kendo UI and Kendo UI for ASP.NET MVC.  If you already have Kendo UI core installed, don’t worry, the installer will adjust accordingly.

Once installed pull up the install location, for me it is “C:\Program Files (x86)\Telerik\Kendo UI for ASP.NET MVC Q2 2012 BETA”, and play around with the example projects by running “\Examples\StartExamples.exe”.

Now…let’s get it up and running in an ASP.NET MVC project.

NOTE: The Kendo UI for ASP.NET MVC documentation states that both MVC 3 and MVC 4 are supported even though the actual Kendo.MVC.dll resides in the “Mvc3” directory.

  1. Create a new ASP.NET MVC 3 or 4 project
  2. Add a reference to: [Kendo UI Directory]\Binaries\Mvc3\Kendo.Mvc.dll
  3. Copy the contents of [Kendo UI Directory]\Scripts to the Scripts folder of your MVC project
  4. Copy the contents of [Kendo UI Directory]\Content to the Content folder of your MVC project
  5. Reference the Kendo UI scripts and and CSS files in your layout page.
    *Note: If your using ASP.NET MVC 4 I suggest creating a bundler package

    <link rel="stylesheet" href="@Url.Content("~/Content/kendo.common.min.css")">
    <link rel="stylesheet" href="@Url.Content("~/Content/kendo.default.min.css")">
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    <script src="@Url.Content("~/Scripts/kendo.web.min.js")"></script>
    <script src="@Url.Content("~/Scripts/kendo.aspnetmvc.min.js")"></script>
  6. Add a reference to the Kendu.Mvc.UI namespace to the <namespaces> section of the web.config to allow your views to know about the Kendo HTML Helper extensions.
    <add namespace="Kendo.Mvc.UI"/>
  7. Let’s test it out.  Open up Index.cshtml and create a Kendo UI control using the new HTML Helpers.



As with the previous parts of the series the code is available on GitHub.

posted on Tuesday, June 19, 2012 11:15:53 AM (Central Daylight Time, UTC-05:00)  #    Comments [6]
# Monday, April 30, 2012

I have recently started diving in to Kendo UI and have decided to document that dive and blog about it.  So this is the first post in a series dedicated to using Kendo UI in ASP.NET MVC.

Kendo UI is a JavaScript toolset developed by Telerik that leverages jQuery, HTML5, CSS3, and JavaScript to provide rich UI widgets and an MVVM framework that is ‘scary fast’.  The thing that really drew me to Kendo UI in the first place is there native skinning on mobile devices.  Unlike vanilla jQuery Mobile that renders the same iOS-esque view on all mobile devices Kendo UI Mobile applies specific native-looking styles for iOS, Android, and Blackberry.  Over the series of posts I have planned we will cover exactly what Kendo UI brings to the table for both the ‘desktop’ web and the mobile web, but today I will cover getting Kendo UI installed and configured in an ASP.NET MVC application.

Before we dive in to getting the bits I want to prepare you…Kendo UI is not free.  I know, I was surprised by this as well and it actually delayed my dive in to it for a bit.  In all honesty I am still not 100% sure how I feel about it not being free.  What I do know is that as a long time user of Telerik products they produce damn good tooling and there support system is second to none.  If you want to just play around with Kendo UI there is a 60-day free trial available.

Update: I received a comment from a member of the KendoUI team, thanks John, and my statement above needs some clarification.  Kendo UI is dual licensed (GPLv3 and commercial), so although it is not free for commercial use they do support open source development.  You can can get the official terms here: http://www.kendoui.com/get-kendo-ui.aspx

Note: To prepare for experimenting with KendoUI I created an empty MVC 4 project, that of course is not empty, and removed all scirpt and css files (other than Site.css).  I then removed all script and css registrations in _Layout.cshtml.  I did this because I wanted to deal strictly with KendoUI without all the other *noise* of the other script references.

You can download the KendoUI bits here: http://www.kendoui.com/get-kendo-ui.aspx

Once downloaded and unzipped copy the contents of the ‘js’ directory to the ‘Scripts’ directory of your ASP.NET MVC application and the contents of the ‘styles’ directory to the ‘Content’ directory.

Next you need to register the scripts and CSS files that Kendo UI needs in the _Layout.cshtml.

  1. DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <meta charset="utf-8" />
  5.         <meta name="viewport" content="width=device-width" />
  6.         <title>@ViewBag.Titletitle>
  7.         <script src="~/Scripts/jquery.min.js">script>
  8.         <script src="~/Scripts/kendo.all.min.js">script>
  9.         <link href="~/Content/kendo.common.min.css" rel="stylesheet" type="text/css"/>
  10.         <link href="~/Content/kendo.default.min.css" rel="stylesheet" type="text/css"/>
  11.     head>
  12.     <body>
  13.         @RenderBody()
  14.     body>
  15. html>

That’s it.  Kendo UI is now wired up.  Pretty much the same process as wiring up jQuery.  So now we can do a quick implementation to prove it.

If you followed my lead and created an empty project you you will need to create a controller and a view at this point.

The actual implementation of KendoUI is almost identical to that of jQuery which makes the ramp up time a lot less if you are familiar with jQuery.

  1. @{
  2.     ViewBag.Title = "Getting Started With KendoUI - Installation and Configuration";
  3. }
  5. <script type="text/javascript">
  6.     $(document).ready(function(){
  7.         $("#datePicker").kendoDatePicker();
  8.     });
  9. script>
  11. <h2>@ViewBag.Titleh2>
  13. <input id="datePicker" />

As you can see on line 13 I have an input tag with and id of datepicker and then starting on line 5 I have my document ready function that selects the control with id of datepicker and calls the ‘kendoDatePicker’ function it.  The result is below.


KendoUI Calendar

In the next installment we will dig deeper into the different controls available in Kendo UI.

If you want to follow along with the source code it is available on GitHub.

posted on Monday, April 30, 2012 2:01:26 PM (Central Daylight Time, UTC-05:00)  #    Comments [14]
# Monday, April 23, 2012

Having been a part of many large enterprise ASP.NET MVC application implementations using test driven development I learned early on that separating your controller classes into a their own project significantly reduces the noise in your web project.  It wasn’t until a recent talk I gave to user group in my region that I realized that this isn’t a widely adopted practice.  For large applications with a lot of developers and a complex architecture I highly recommend it. 

Putting your controllers in a separate assembly is very straight forward.  First create a controllers project in your solution and then you just need to update your route registrations to tell them where to look for the controllers.

  1. routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}",
  2.                 namespaces: new[] {"[Namespace of the Project that contains your controllers]"},
  3.                 defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional});

In order to tell ASP.NET MVC where to look for your controllers when registering your routes you use the ‘namespaces’ parameter of the MapRoute method as illustrated above.

I know that the concept of putting controllers in a separate assembly is a bit controversial and everyone seems to have a strong opinion either for or against, so let me know what side of the fence you fall on.

posted on Monday, April 23, 2012 8:02:14 AM (Central Daylight Time, UTC-05:00)  #    Comments [13]
# Monday, April 16, 2012

Back in 2009 I published ReSharper Live Template For Creating Unit Test Stub.  A lot of things have changed since 2009, including my templates.  Since I am doing another series of presentations on Test Driven Development I thought I should get these out because people always ask for them.

As stated in my original post these templates are a way for you to create unit test names that help in describing the true intentions of the test and also to provide a common unit test format that will make reading and comprehending your unit tests easier on everyone.  And of course as lazy developers any redundancies should be automated!

The first template is for a unit test that does not have specific input criteria.

Test w/out Input Criteria
  1. [TestMethod]
  2. public void $MethodUnderTest$_Should_$ExpectedResult$() {
  3.     //Arrange
  4.     $END$
  5.     //Act
  6.     //Assert
  7. }

The second template is for a unit test that has specific input criteria.

Test with Input Criteria
  1. [TestMethod]
  2. public void $MethodUnderTest$_Should_$ExpectedResult$_When_$Condition$() {
  3.     //Arrange
  4.     $END$
  5.     //Act
  6.     //Assert
  7. }

You can take the two templates and create new Live Templates and map to whatever key stroke combination you wish.  I use ‘tt’ and ‘tw’.

Note:  I have been using these Live Templates since ReSharper 3 and I am currently using them in the latest build of ReSharper 6 without any issues so you should be good to go.

As always if you feel these can be improved on or have other Live Templates you want to share let me know in the comments below.

posted on Monday, April 16, 2012 7:09:59 AM (Central Daylight Time, UTC-05:00)  #    Comments [1]
# Monday, February 06, 2012

I have been working a lot with MVC sites lately and experimenting with how to make them *usable* on mobile browsers.  This is post is about the single line of mark-up you can add to your sites Master Page, or in this case your _Layout.cshtml.

Before I get to that line I am going to show you a quick screen shot of a vanilla MVC 3 application, that can be downloaded here.

First is a screen shot of the site running in a desktop browser.



Next, is the site rendered on Windows Phone 7, Android, and iPhone.

Windows Phone 7

Opera Mobile (Android)


image image image


The first thing you notice is that iOS does a fairly good job adaptively rendering the site, damn Apple!  Next you will notice that all WP7 and Android do is zoom out so the site fits on the device.  A site of any significant content or functionality would be almost useless because of the amount of panning and zooming that would be required.  I am sure we have all dealt with sites on our mobile devices like that.  So what can we do to make the site render better in WP7 and Android?

You can actually get a long way towards perfect mobile rendering of your site by adding one simple html tag.

  1. <meta name="viewport" />

The meta viewport tag can be used to control how HTML content is displayed in mobile browsers.  The meta viewport tag has properties like width, height, minimum-scale, and maximum-scale.  In this example the particular property we are concerned with is the width property.  We want to tell the the browser to render our content width at the width of device.

  1. <meta name="viewport" content="width=device-width">

Let’s see what happens when we add that tag to the head of our _Layout.cshtml file


As you can see above, because the meta viewport tag only effects mobile browsers our desktop version looks exactly the same.  Let’s check on the mobile browsers.

Windows Phone 7

Opera Mobile (Android)


image image image

The site looks much better on Windows Phone 7 and Android, and still looks the same in Apple.  So by adding that single line of mark-up we where able to give our mobile users a much better user experience.

Stay tuned for a future post on using CSS Media Queries to improve the mobile experience even further.

posted on Monday, February 06, 2012 8:15:38 AM (Central Standard Time, UTC-06:00)  #    Comments [2]
# Monday, January 23, 2012

Support for spatial data was introduced in SQL Server 2008.  What this allows you to do is capture data related to 2D geometric or geographical images in SQL Server.  It actually allows you to do much more than just storing a bunch of numbers representing this data.  In the initial releases of Entity Framework the spatial data type was not available for use, but with the Entity Framework June 2011 CTP release this functionality is now available.

I am once again working with the code from my Entity Framework Code First Demo post.  This simple application is dream car tracker that tracks manufacturers and models of cars that someday I would love to own.  As part of the manufacturer data I currently store the Country but would like to be able to map out the corporate headquarters for the day when I get to take a trip and take delivery.  I am able to retrieve the latitude and longitude from Google Maps by knowing the address.

The Ferrari factory located at: Via Abetone Inferiore n. 4, I-41053 Maranello Italy has a latitude and longitude of 44.53244, 10.86412.  At this point if you are new to the spatial data type, like I was, you are probably thinking “that is just a decimal and you could always store decimals in SQL Server” and you are correct.  I could certainly just add two decimal properties to my model that represent latitude and longitude and go on my merry way but using spatial data functionality introduced in the June CTP I get so much more.

Because I am dealing with geographical data and not geometric data I am going to use the DbGeography type, that can be found in System.Data.Spatial, and add a Location property to my Manufacturer model.

  1. public class Manufacturer {
  3.     public long ManufacturerId { get; set; }
  5.     [Required]
  6.     [StringLength(40)]
  7.     public string Name { get; set; }
  9.     [Required]
  10.     [StringLength(40)]
  11.     public string Country { get; set; }
  13.     [Required]
  14.     public DbGeography Location { get; set; }
  16.     #region << Navigation Properties >>
  18.     public virtual IList<Model> Models { get; set; }
  20.     #endregion
  22. }

Once I have Entity Framework Code First regenerate my database I can take a look and see that the .NET Framework type DbGeography translates to the SQL Server type Geography.


Now that I have my property I can populate the Location data by converting my latitude and longitude values to a DbGeography using the static parse method.  I can add this to my SeedManufacturer method.

  1. private void SeedManufacturer(DataContext context) {
  2.     _ferrari = new Manufacturer {Name = "Ferrari", Country = "Italy"};
  3.     _lamborghini = new Manufacturer {Name = "Lamborghini", Country = "Italy"};
  4.     _astonMartin = new Manufacturer {Name = "Aston Martin", Country = "United Kingdom"};
  5.     _porsche = new Manufacturer {Name = "Porsche", Country = "Germany"};
  6.     _ferrari.Location = DbGeography.Parse("POINT(44.53244    10.86412)");
  7.     _lamborghini.Location = DbGeography.Parse("POINT (44.65934    11.12693)");
  8.     _astonMartin.Location = DbGeography.Parse("POINT (52.18708    -1.48351)");
  9.     _porsche.Location = DbGeography.Parse("POINT (48.83498    9.15231)");
  10.     new List<Manufacturer> {_ferrari, _lamborghini, _astonMartin, _porsche}.ForEach(x => context.Manufacturers.Add(x));
  11. }

Now if you look at the data in SQL Server you an see that the data is now represented as a nasty looking hex.


I know you are still wondering what the point is, pun intended!  Well, now I can get to the cool part.  I can use the methods that come along with DbGeography to do things such as getting distance between two manufacturers as illustrated below in line 3.

  1. Manufacturer ferrari = dc.Manufacturers.First(x => x.Name == "Ferrari");
  2. Manufacturer lamborghini = dc.Manufacturers.First(x => x.Name == "Lamborghini");
  3. double distanceInKilometers = ferrari.Location.Distance(lamborghini.Location);
  4. double distanceInMiles = distanceInKilometers/1609.344;
  5. string outputText = string.Format("{0} is {1} miles from {2}", ferrari.Name, distanceInMiles, lamborghini.Name);

You can also use the methods in LINQ.  The query below finds all the manufacturers that are within a 100 mile radius of my house.

  1. DbGeography myHouse = DbGeography.Parse("POINT (4.65934    1.12693)");
  2. IList<Manufacturer> closeToMe = manufacturers.Where(x => (x.Location.Distance(myHouse)*.00062) <= 100).ToList();
posted on Monday, January 23, 2012 8:30:40 AM (Central Standard Time, UTC-06:00)  #    Comments [3]
# Monday, January 09, 2012

The most requested feature for Entity Framework has been Enum support for a very long time.  At TechEd this year it was announced that Enums would be supported in the next version of the Entity Framework and in June the Entity Framework June CTP was released with Enum support as well some other enhancements.

In the past I dealt with Entity Framework not supporting Enum by having an int property on my model that represented the Enum’s id.  My model also had a property of the Enum type that was marked as ignored so that EF did not try create a database column for the property.  The setter of the property would set the Enum id field and the getter would convert the Enum id field to the Enum type and return it.  If you are confused by that statement, like me, see the code below.

  1. public class Model {
  3.         public long ModelId { get; set; }
  5.         [Required]
  6.         [StringLength(50)]
  7.         public string Name { get; set; }
  9.         [Required]
  10.         public int Year { get; set; }
  12.         [Required]
  13.         public decimal BasePrice { get; set; }
  15.         public int EngineLocation { get; set; }
  17.         public EngineLocationType EngineLocationType {
  18.             get { return (EngineLocationType) EngineLocation; }
  19.             set { EngineLocation = (int) value; }
  20.         }
  22.         #region << Navigation Properties >>
  24.         public long ManufacturerId { get; set; }
  25.         public virtual Manufacturer Manufacturer { get; set; }
  27.         public virtual IList<Engine> AvailableEngines { get; set; }
  29.         #endregion
  31.     }
  1. public class DataContext : DbContext {
  3.         public DataContext() : base("name=EFCodeFirst") {}
  5.         public IDbSet<Manufacturer> Manufacturers { get; set; }
  6.         public IDbSet<Model> Models { get; set; }
  7.         public IDbSet<Engine> Engines { get; set; }
  9.         protected override void OnModelCreating(DbModelBuilder modelBuilder) {
  10.             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  11.             modelBuilder.Entity<Model>().Ignore(x => x.EngineLocationType);
  12.             modelBuilder.Entity<Model>().HasMany(x => x.AvailableEngines).WithMany(x => x.AvailableOn).Map(x => x.MapLeftKey("ModelId").MapRightKey("EngineId").ToTable("ModelEngine"));
  13.             base.OnModelCreating(modelBuilder);
  14.         }
  15.     }

This gets the job done and really isn’t that messy, but with the new Enum support in the June CTP I can make things cleaner.  To make use of the new Enum support all I have to do is declare a property of EngineLocationType in my model and EF will make all the connections for me.

  1. public class Model {
  3.         public long ModelId { get; set; }
  5.         [Required]
  6.         [StringLength(50)]
  7.         public string Name { get; set; }
  9.         [Required]
  10.         public int Year { get; set; }
  12.         [Required]
  13.         public decimal BasePrice { get; set; }
  15.         public EngineLocationType EngineLocation { get; set; }
  17.         #region << Relationships >>
  19.         public long ManufacturerId { get; set; }
  20.         public virtual Manufacturer Manufacturer { get; set; }
  22.         public virtual IList<Engine> AvailableEngines { get; set; }
  24.         #endregion
  27.     }

So that is the new EF Enum support.  The only issue I have with the implementation is that ideally I would like to be able to have an EngineLocationType table in my database that Entity Framework would create and populate based on my Enum definition and assign a foreign key relationship to EngineLocation on my Model entity.  That would make the entire process complete and architecturally sound IMHO.

If you are looking for a code download this is part of the Entity Framework Code First Demo that I did in a previous blog post and the code is available on GitHub.

posted on Monday, January 09, 2012 8:18:40 AM (Central Standard Time, UTC-06:00)  #    Comments [3]
# Monday, December 12, 2011

Integration Testing is a necessary evil that often gets overlooked or is implemented, ran once, and then not maintained.  The reasoning behind this is that by definition Integration Testing relies on external resources that are often outside of our control and some times completely hands off.  Also these external resources are in constant use by a large number of people making whatever resource the external systems are serving very volatile.  In this post I am going to focus on the most common external resource; the Database.

Integration Testing when you have a Database as an external resource can be a nightmare.  First off you need to have access to the database.  Once that is accomplished you need to have elevated access to the database in order to run scripts.  Scripts you say?  Yes scripts!  Scripts that can put the database in an expected state every time you run the Integration Tests.  Oh, yeah then you have to make sure that the script is run.

Luckily if you are using Entity Framework Code First you more than likely already have elevated access to the Database and are probably running a local instance of SQL Server on your dev box that you are in control of.  But in the typical scenario you would still have to write the SQL Scripts, which if you are like me you don’t enjoy, and then you have to make sure they are run and that they don’t impact the data that you use to manually UI test your application…we all have that one piece of data that rely on…don’t deny it!

So how does EF Code First help me with this overwhelming problem?

All example code is from my EFCodeFirstDemo.

Seeded Data:

In Entity Framework Code First you are given the ability to hook into the database generation process and seed the database with relevant data for testing.  The best part about this is that you do it all using your POCO domain entities and LINQ to Entities…NO SQL SCRIPTS!  WOOT!

The first step in the process is to create a custom data context initializer that implements an implementation IDatabaseInitializer.

  1. public class TestDataContextInitializer : DropCreateDatabaseIfModelChanges<DataContext> {}

The next step is to override the Seed method that hooks into the generation of the database.

  1. protected override void Seed(DataContext context) {
  2.     base.Seed(context);
  3. }

Finally you can use this Seed method to build up your test data and populate the database either every time your model changes (DropCreateDatabaseIfModelChanges) or if you choose every time you spin up a new session that accesses the database (DropCreateDatabaseAlways), I don’t recommend the latter.

In the code below I am building up object graphs using my standard POCO entities and LINQ to Entities.

  1. public class TestDataContextInitializer : DropCreateDatabaseIfModelChanges<DataContext> {
  3.     private Manufacturer _astonMartin;
  4.     private Model _astonMartinDB9;
  5.     private Engine _astonMartinV12;
  6.     private Model _astonMartinV12Vantage;
  7.     private Manufacturer _ferrari;
  8.     private Model _ferrari458Italia;
  9.     private Model _ferrariScaglietti;
  10.     private Engine _ferrariV12;
  11.     private Engine _ferrariV8;
  12.     private Manufacturer _lamborghini;
  13.     private Model _lamborghiniAventador;
  14.     private Model _lamborghiniGallardo;
  15.     private Engine _lamborghiniV10;
  16.     private Engine _lamborghiniV12;
  17.     private Manufacturer _porsche;
  18.     private Model _porsche911GT2R2;
  19.     private Engine _porscheStraight6;
  21.     protected override void Seed(DataContext context) {
  22.         SeedManufacturer(context);
  23.         SeedEngine(context);
  24.         SeedModel(context);
  25.         base.Seed(context);
  26.     }
  28.     private void SeedManufacturer(DataContext context) {
  29.         _ferrari = new Manufacturer {Name = "Ferrari", Country = "Italy"};
  30.         _lamborghini = new Manufacturer {Name = "Lamborghini", Country = "Italy"};
  31.         _astonMartin = new Manufacturer {Name = "Aston Martin", Country = "United Kingdom"};
  32.         _porsche = new Manufacturer {Name = "Porsche", Country = "Germany"};
  33.         _ferrari.Location = DbGeography.Parse("POINT(44.53244    10.86412)");
  34.         _lamborghini.Location = DbGeography.Parse("POINT (44.65934    11.12693)");
  35.         _astonMartin.Location = DbGeography.Parse("POINT (52.18708    -1.48351)");
  36.         _porsche.Location = DbGeography.Parse("POINT (48.83498    9.15231)");
  37.         new List<Manufacturer> {_ferrari, _lamborghini, _astonMartin, _porsche}.ForEach(x => context.Manufacturers.Add(x));
  38.     }
  40.     private void SeedEngine(DataContext context) {
  41.         _astonMartinV12 = new Engine {Name = "6.0L V12", BreakHorsepower = 510, NumberOfCylinders = 12, Liters = 6.0m};
  42.         _ferrariV8 = new Engine {Name = "5.4L V8", BreakHorsepower = 570, NumberOfCylinders = 8, Liters = 5.4m};
  43.         _ferrariV12 = new Engine {Name = "5.7L V12", BreakHorsepower = 532, NumberOfCylinders = 12, Liters = 5.7m};
  44.         _lamborghiniV10 = new Engine {Name = "5.2L V10", BreakHorsepower = 562, NumberOfCylinders = 10, Liters = 5.2m};
  45.         _lamborghiniV12 = new Engine {Name = "6.5L V12", BreakHorsepower = 700, NumberOfCylinders = 12, Liters = 6.5m};
  46.         _lamborghiniV12 = new Engine {Name = "6.5L V12", BreakHorsepower = 700, NumberOfCylinders = 12, Liters = 6.5m};
  47.         _porscheStraight6 = new Engine {Name = "3.6L Straight 6", BreakHorsepower = 620, NumberOfCylinders = 6, Liters = 3.6m};
  48.         new List<Engine> {_astonMartinV12, _ferrariV8, _ferrariV12, _lamborghiniV10, _lamborghiniV12, _porscheStraight6}.ForEach(x => context.Engines.Add(x));
  49.     }
  51.     private void SeedModel(DataContext context) {
  52.         _ferrari458Italia = new Model {Name = "458 Italia", BasePrice = 220000, Year = 2012, Manufacturer = _ferrari, AvailableEngines = new List<Engine> {_ferrariV8, _ferrariV12}, EngineLocation = EngineLocationType.Mid};
  53.         _ferrariScaglietti = new Model {Name = "Scaglietti", BasePrice = 313000, Year = 2012, Manufacturer = _ferrari, AvailableEngines = new List<Engine> {_ferrariV12}, EngineLocation = EngineLocationType.Front};
  54.         _lamborghiniGallardo = new Model {Name = "Gallardo LP 570-4 Superleggera", BasePrice = 237600, Year = 2012, Manufacturer = _lamborghini, AvailableEngines = new List<Engine> {_lamborghiniV10}, EngineLocation = EngineLocationType.Mid};
  55.         _lamborghiniAventador = new Model {Name = "Aventador LP 700-4", BasePrice = 387000, Year = 2012, Manufacturer = _lamborghini, AvailableEngines = new List<Engine> {_lamborghiniV12}, EngineLocation = EngineLocationType.Mid};
  56.         _astonMartinDB9 = new Model {Name = "DB9", BasePrice = 185000, Year = 2012, Manufacturer = _astonMartin, AvailableEngines = new List<Engine> {_astonMartinV12}, EngineLocation = EngineLocationType.Front};
  57.         _astonMartinV12Vantage = new Model {Name = "V12 Vantage", BasePrice = 180000, Year = 2012, Manufacturer = _astonMartin, AvailableEngines = new List<Engine> {_astonMartinV12}, EngineLocation = EngineLocationType.Mid};
  58.         _porsche911GT2R2 = new Model {Name = "911 GT2 R2", BasePrice = 245000, Year = 2012, Manufacturer = _porsche, AvailableEngines = new List<Engine> {_porscheStraight6}, EngineLocation = EngineLocationType.Rear};
  59.         new List<Model> {_ferrari458Italia, _ferrariScaglietti, _lamborghiniAventador, _lamborghiniGallardo, _astonMartinDB9, _astonMartinV12Vantage, _porsche911GT2R2}.ForEach(x => context.Models.Add(x));
  60.     }
  61. }

The result of this process is that every time my database is dropped and recreated it is also seeded with test data. 

I know what your saying…”But I don’t use the same data for manually walking through my UI that I would use for Integration Testing!”  Luckily I can easily specify a different Connection String and Database Initializer to use when running my Integration Tests.

The first thing you have to do is modify the connection string in the AppConfig of your Integration Test project to use a different initial catalog.  As you can see all I did was suffix mine with “_TEST”…clever I know!  This is going to setup a new database for you that will only be used for testing.

  1. <connectionStrings>
  2.     <add name="EFCodeFirst" connectionString="Data Source=(local);Initial Catalog=EFCodeFirst_TEST;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient"/>
  3.   connectionStrings>

Next you need to tell EF what Database Initializer to use.  This can be accomplished two ways.  The first way is to explicitly set it in code.  In the example below I am doing this in the ClassInitialize of my Integration Test class.

  1. [ClassInitialize]
  2. public static void ClassInitialize(TestContext context) {
  3.     Database.SetInitializer(new TestDataContextInitializer());
  4. }

The second way is to set it configure it in the App/Web Config.

  1. <appSettings>
  2.     <add key="DatabaseInitializerForType EFCodeFirst.DataContext.DataContext, EFCodeFirst" value="EFCodeFirst.DataContext.TestDataContextInitializer, EFCodeFirst" />
  3.   appSettings>
That’s it!  Now you have a separate Database instance just for Integration Testing that will always contain the clean fresh data that is required to exercise your Integration Test suite.  Better yet, every developer that runs your Integration Tests will also have this data and everything will just work.
posted on Monday, December 12, 2011 9:25:24 AM (Central Standard Time, UTC-06:00)  #    Comments [2]
# Monday, December 05, 2011

Configuration of Entity Framework Code First is a necessary evil and you have to admit is a very well designed user friendly process.  But, in typical Microsoft fashion, the EF developers have given us more than one way to perform this configuration.

  1. Fluent API
    1. Fluent expression based configuration
    2. Performed during the OnModelCreating process of the DbContext.
    3. Allows for complex configurations that are not possible via Attribute based configuration
      Fluent Configuration
      1. protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      2.     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
      3.     modelBuilder.Entity<Model>().HasMany(x => x.AvailableEngines)
      4.         .WithMany(x => x.AvailableOn)
      5.         .Map(x => x.MapLeftKey("ModelId")
      6.         .MapRightKey("EngineId")
      7.         .ToTable("ModelEngine"));
      8.     modelBuilder.Entity<Model>().Ignore(x => x.SomeDerivedProperty);
      9.     base.OnModelCreating(modelBuilder);
      10. }

  2. Attributes
    1. Attribute based configuration
    2. Performed directly on the Domain Model Class/Property being configured
    3. Allows the non-EF specific attributes to be used in other pieces of your application
    4. Allows validation of your Model at any time
      Attribute Configuration
      1. public class Manufacturer {
      3.     public long ManufacturerId { get; set; }
      5.     [StringLength(40)]
      6.     [Required]
      7.     public string Name { get; set; }
      9.     [Required]
      10.     [StringLength(40)]
      11.     public string Country { get; set; }
      13.     [Required]
      14.     public DbGeography Location { get; set; }
      16.     #region << Relationships >>
      18.     public virtual IList<Model> Models { get; set; }
      20.     #endregion
      22. }


So…When do you use which!?

Use Fluent Configuration When:

  • Configuration is being done solely to make the database behave correctly.
  • Configuration has no effect on the design and/or behavior of your Domain Model.
  • Examples:
    • Specifying the database table the Domain Model is to be mapped to
    • Specifying the database table column the Domain Model Field is to be mapped to
    • Ignoring a Domain Model Field
    • Configuring the keys and table names for relationships not able to be picked up by EF

Use Attribute Configuration When:

  • Configuration solely applies to your Domain Model.
  • Configuration has no effect on the design and/or behavior of your Database.
  • Examples:
    • Making a field Required
    • Validating a field (String length, Range, etc.)
  • Also…Don’t forget that for the most part these Attributes are not EF specific and can be used in the UI with MVC.
posted on Monday, December 05, 2011 8:53:57 AM (Central Standard Time, UTC-06:00)  #    Comments [1]
# Monday, November 28, 2011

The jQuery Accordion control is great for creating rich interactive HTML menus.  I used it in a recent project where I wanted “Home” to be the top menu option.  I Googled around and wasn’t able to find a way to have a menu item with no children link to some URL.  So I played around for a bit and came up this solution. 

  1. $(function() {
  2.     $("#navigationMenu").accordion({ autoHeight: false });
  3.     $('#homeNavMenu').find('a').click(function() { window.location = '/'; });
  4. });
posted on Monday, November 28, 2011 9:52:57 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
# Monday, November 21, 2011

If you ever need to redirect to a custom page in ASP.NET MVC when a user is either not authenticated or not authorized here is how you do it.

  1. Create a custom attribute that inherits from AuthorizeAttribute.
  2. Override the OnAuthorization method.
    • call the base OnAuthorization
    • Handle user not being authenticated
    • Handle user not being authorized
  3. Use the newly created attribute in your controller in place of the ASP.NET Authorize attribute


The Custom Attribute
  1. public class CustomAuthorizeAttribute : AuthorizeAttribute {
  3.     public override void OnAuthorization(AuthorizationContext filterContext) {
  4.         base.OnAuthorization(filterContext);
  5.         if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
  6.             filterContext.Result = new RedirectResult("~/Account/Logon");
  7.             return;
  8.         }
  10.         if (filterContext.Result is HttpUnauthorizedResult) {
  11.             filterContext.Result = new RedirectResult("~/Account/AccessDenied");
  12.             return;
  13.         }
  14.     }
  15. }
Example Controller Usage
  1. [CustomAuthorize(Roles = ("Admin,Manager"))]
  2. public ActionResult Index() {
  3.     return View("Index");
  4. }
posted on Monday, November 21, 2011 9:46:18 AM (Central Standard Time, UTC-06:00)  #    Comments [9]
# Monday, November 14, 2011

ASP.NET MVC has an HTML Helper DropDownListFor that takes an IEnumerable and creates a drop down list for it.  Often you want to create a drop down list for an Enum.  Of course you can do this without using an HTML Helper and use standard HTML controls but you don’t have the standard clean view code that HTML Helpers give you.  Extending and creating your own HTML Helpers is rather easy, as demonstrated in my last post. With that in mind I created an extension to DropDownListFor that will create a drop down list for an Enum type.


Enum Html Helper
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. using DropDownListForEnumDemo.Extensions;
  6. namespace System.Web.Mvc.Html {
  8.     public static class EnumHtmlHelper {
  10.         public static MvcHtmlString DropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression) {
  11.             return DropDownListFor(htmlHelper, expression, null, null);
  12.         }
  14.         public static MvcHtmlString DropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string optionLabel) {
  15.             return DropDownListFor(htmlHelper, expression, optionLabel, null);
  16.         }
  18.         public static MvcHtmlString DropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes) {
  19.             return DropDownListFor(htmlHelper, expression, null, htmlAttributes);
  20.         }
  22.         public static MvcHtmlString DropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string optionLabel, object htmlAttributes) {
  23.             ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
  24.             Type enumType = Nullable.GetUnderlyingType(typeof (TEnum)) ?? typeof (TEnum);
  25.             IEnumerable<TEnum> enumValues = Enum.GetValues(enumType).Cast<TEnum>();
  26.             IEnumerable<SelectListItem> items = enumValues.Select(e => new SelectListItem {Text = e.ToString().FromCamelToProperCase(), Value = e.ToString(), Selected = e.Equals(metadata.Model)});
  27.             if (optionLabel != null) {
  28.                 new[] {new SelectListItem {Text = optionLabel}}.Concat(items);
  29.             }
  30.             return htmlHelper.DropDownListFor(expression, items, optionLabel, htmlAttributes);
  31.         }
  32.     }
  33. }


  1. namespace DropDownListForEnumDemo.Enumerations {
  3.     public enum Cars {
  4.         FerrariItalia = 0,
  5.         LamborghiniGallardoLP560,
  6.         LamborghiniAventador,
  7.         AstonMartinVantage,
  8.         Porsche911GT2,
  9.     }
  10. }


  1. namespace DropDownListForEnumDemo.Models {
  3.     public class CarsModel {
  4.         [Display(Name = "Select A Car:")]
  5.         [Required(ErrorMessage = "* Required")]
  6.         public Cars? SelectedCar { get; set; }
  7.     }
  8. }


  1. @{ViewBag.Title = "Home Page";}
  2. @using DropDownListForEnumDemo.Models
  3. @model CarsModel
  4. <h2>@ViewBag.Message</h2>
  5. @using (Html.BeginForm()) {
  6.     <div>
  7.         <fieldset>
  8.             <div class="editor-label">
  9.                 @Html.LabelFor(m => m.SelectedCar)
  10.             </div>
  11.             <div class="editor-field">
  12.                 @Html.DropDownListFor(m => m.SelectedCar, "-- Select --")
  13.                 @Html.ValidationMessageFor(m => m.SelectedCar)
  14.             </div>
  15.         </fieldset>
  16.         <input type="submit" value="Click Me"/>
  17.     </div>
  18. }




Note:  Because enumeration values have to adhere to the same naming conventions as variables I had to work some magic to get the display values formatted correctly.  OK, it’s really not magic…just a little RegEx Voo-Doo.

The code is available on GitHub

posted on Monday, November 14, 2011 8:46:32 AM (Central Standard Time, UTC-06:00)  #    Comments [3]
# Monday, November 07, 2011

ASP.NET MVC provides a lot of HTML Helpers that allow you to more easily with less code create your views.  Typically navigation in MVC is done using the ActionLink HTML Helper that allows you easily generate an html anchor tag that will redirect to a specified controller and action.  I found cases where I wanted my navigation to be done via a button rather than a link so I created my own HTML Helper to make this easier.


  1. using System.Web.Routing;
  3. namespace System.Web.Mvc.Html {
  5.     public static class ActionLinkButtonHelper {
  7.         public static MvcHtmlString ActionLinkButton(this HtmlHelper htmlHelper, string buttonText, string actionName, string controllerName, RouteValueDictionary routeValues) {
  8.             string href = UrlHelper.GenerateUrl("default", actionName, controllerName, routeValues, RouteTable.Routes, htmlHelper.ViewContext.RequestContext, false);
  9.             string buttonHtml = string.Format("<input type=\"button\" title=\"{0}\" value=\"{0}\" onclick=\"location.href='{1}'\" class=\"button\" />",buttonText,href);
  10.             return new MvcHtmlString(buttonHtml);
  11.         }
  12.     }
  13. }

Example Usage:

  1. @Html.ActionLinkButton("Add", "AddSiteFromDistrict", "SiteMaintenance", new RouteValueDictionary(new { districtID = @Model.DistrictID }))
posted on Monday, November 07, 2011 8:53:15 AM (Central Standard Time, UTC-06:00)  #    Comments [2]
# Monday, October 31, 2011

I recently put together an Entity Framework Code First demo that I presented to my colleagues at Skyline Technologies.

The demo includes:

  • Generating DB from POCO’s
  • Fluent and Attribute EF configuration examples
  • Creating Relationships (1 –> Many, Many –> Many)
  • Seeding Data
  • Using a separate DB instance for integration testing
  • How using Data Annotations saves you time in MVC
  • New Features Coming In EF vNext
    • Enums
    • Spatial Data Type

I put the code up on GitHub so if you are looking for an EF Code First kick starter took a look!

posted on Monday, October 31, 2011 7:35:41 AM (Central Standard Time, UTC-06:00)  #    Comments [3]
# Saturday, October 29, 2011

My latest project was being done in ASP.NET MVC3 and I needed to do some date validation that was beyond what was available out-of-the-box.  I Googled around the inter-webs for awhile and couldn’t find anything that met my needs so I decided to create my own set of extensions…and while I was at create my NuGet package and CodePlex project.

For some reason the validation attributes available for the Date data type are non-existence in MVC.  You can compare to another model field, but that only checks for equality.  You can use regular expressions, which is not fun, and you can only compare against static values, or you can create your own validation attributes…which is the route I chose.

I created custom validation attributes that I found that I needed in my projects and packed some up to make available to the masses.

EzValidation contains validation for:

  • Equal, NotEqual, Greater, Less, GreaterOrEqual, LessOrEqual
    • Available for all Primitive Data Types (including nullable)
    • Compare to another field in the Model
        1. [Equal("Email")]
        2. public string ConfirmEmail { get; set; }
    • Compare to a specific value
        1. [NotEqual("|28|")]
        2. public int Age {get; set;}
    • Compare to Current Date (Dates and Strings only)
        1. [Greater("CompareToCurrentDate")]
        2. public DateTime ADateInTheFuture { get; set; }
    • Compare to Yesterday's Date (Dates and Strings only)
        1. [Less("CompareToYesterday")]
        2. public DateTime DateBeforeYesterday { get; set; }
    • Compare to Tomorrow's Date (Dates and Strings only)
        1. [GreaterOrEqual("CompareToTomorrow")]
        2. public DateTime DateAfterTomorrow { get; set; }


    The source Code is available on CodePlex.

    The package can be installed via NuGet.  “package-install EzValidation"

    posted on Saturday, October 29, 2011 7:09:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [1]
    # Sunday, May 22, 2011

    Last weekend I presented a session at the third annual Chicago Code Camp entitled: Test-driven Development in .NET – Tips, Tools, and Techniques.  The session was standing room only and carried into the commons area afterwards with some excellent questions from attendees.  What is greater than that is that the questions didn’t stop there, they kept coming via email.  One question in particular has stuck with me because it was a hurdle I myself had to overcome early on in my TDD adventures.

    The question boiled down to how do you test code the depends on ASP.NET, specifically Web Configuration and Application Settings?  So I thought I would put together a blog post how this can be done, and how it should be done.

    To set the stage…I have a simple ASP.NET web application with one page and one class.  The page load method calls the one method in the class that returns an app setting stored in the web config file.

    1. namespace WebApp
    2. {
    3.     public partial class Index : System.Web.UI.Page
    4.     {
    5.         protected void Page_Load(object sender, EventArgs e) {
    6.             lblValue.Text = SomeClassThatNeedsTesting.GetSomeStringValue();
    7.         }
    8.     }
    9. }

    1. namespace WebApp
    2. {
    3.     public static class SomeClassThatNeedsTesting
    4.     {
    5.         public static string GetSomeStringValue() {
    6.             return System.Web.Configuration.WebConfigurationManager.AppSettings["MyAppSettingValue"];
    7.         }
    8.     }
    9. }

    Your first option to getting your tests to run and return the configuration and/or app settings is to tell your tests to run under the ASP.NET host process and not the VSTest host process and also tell what url to run the test under.

    1. [TestMethod]
    2. [HostType("ASP.NET")]
    3. [UrlToTest("http://localhost:2356/Index.aspx")]
    4. [AspNetDevelopmentServerHost("$(SolutionDir)\\WebApp")]
    5. public void GetSomeStringValue_ShouldReturn_NonNull_NonEmpty_String() {
    6.     var val = WebApp.SomeClassThatNeedsTesting.GetSomeStringValue();
    7.     Console.WriteLine(val.ToString());
    8.     Assert.IsFalse(string.IsNullOrEmpty(val));
    9. }

    If you run this you will see that the test passes…eventually…after Casini is started and the test runner twiddles its thumbs for a bit.  Speed is my first issue with setting up your test to run in this fashion.  My second issue is that you aren’t testing the ASP.NET configuration framework so why would you need to add all this extra plumbing to make your code take that route?  There is a better option!

    Since we really don’t care how or where are value comes from we just need some sort of value returned so we can test our method, we can easily add a thin layer of abstraction and mock the pieces of code that depend on ASP.NET.

    Lets start by creating an interface for a simple class that reads application settings.

    2. namespace WebApp {
    4.     public interface IAppSettingsReader {
    6.         string GetAppSettingValue(string settingKey);
    7.     }
    8. }

    Now we can implement the interface and add the actual code to read the app settings from the web config file.

    1. namespace WebApp {
    3.     public class AppSettingsReader : IAppSettingsReader {
    5.         public string GetAppSettingValue(string settingKey) {
    6.             if (string.IsNullOrEmpty(settingKey)) throw new NullReferenceException("settingKey is required");
    7.             return (WebConfigurationManager.AppSettings[settingKey]);
    8.         }
    10.     }
    11. }

    Next we will modify our class that needs testing to use the new AppSettingsReader.  Because our goal is to eventually be able to mock the settings reader we need to invert the control of the dependency and provide a mechanism for injecting the dependency.  The change is fairly straightforward.

    1. namespace WebApp {
    3.     public class SomeClassThatNeedsTesting {
    5.         private readonly IAppSettingsReader _settingsReader;
    7.         public SomeClassThatNeedsTesting(IAppSettingsReader settingsReader) {
    8.             _settingsReader = settingsReader;
    9.         }
    11.         public string GetSomeStringValue() {
    12.             return _settingsReader.GetAppSettingValue("MyAppSettingValue");
    13.         }
    14.     }
    15. }

    Now we have introduced a breaking change and need to modify our page and our test to accommodate the change to SomeClassThatNeedsTesting.

    1. namespace WebApp {
    3.     public partial class Index : Page {
    5.         protected void Page_Load(object sender, EventArgs e) {
    6.             var someClass = new SomeClassThatNeedsTesting(new AppSettingsReader());
    7.             lblValue.Text = someClass.GetSomeStringValue();
    8.         }
    9.     }
    10. }

    1. namespace TestProject {
    3.     [TestClass]
    4.     public class SomeClassThatNeedsTesting_Tests {
    6.         [TestMethod]
    7.         [HostType("ASP.NET")]
    8.         [UrlToTest("http://localhost:2356/Index.aspx")]
    9.         [AspNetDevelopmentServerHost("$(SolutionDir)\\WebApp")]
    10.         public void GetSomeStringValue_ShouldReturn_NonNull_NonEmpty_String_ASP() {
    11.             SomeClassThatNeedsTesting someClass = new SomeClassThatNeedsTesting(new AppSettingsReader());
    12.             string val = someClass.GetSomeStringValue();
    13.             Console.WriteLine(val);
    14.             Assert.IsFalse(string.IsNullOrEmpty(val));
    15.         }
    16.     }
    17. }

    At this point we can run our test from above and, after we have taken a bathroom break, checked Twitter, and made a sandwich, we will notice that the test still passes.  This is true because all we have done is add a layer of abstraction.  We have not changed the core functionality of the process.  Now that the layer of abstraction is in place we can write another test and this time instead of writing more code to please ASP.NET lets drop that dependency completely by mocking it.

    To implement our mock I am going to use my mocking tool of choice, RhinoMocks.  (I am purposefully not supplying a URL here because you should be using NuGet to get your packages!)

    Here is our new and improved test.

    New And Improved Test
    1. [TestMethod]
    2. public void GetSomeSringValue_ShouldReturn_NonNull_NonEmpty_String_Mocked() {
    3.     //Arrange
    4.     string myAppSettingValue = "This is my expected mocked setting value";
    5.     MockRepository _repository = new MockRepository();
    6.     IAppSettingsReader mockSettingsReader = MockRepository.GenerateStrictMock<IAppSettingsReader>();
    7.     mockSettingsReader.Expect(msr => msr.GetAppSettingValue("MyAppSettingValue")).Return(myAppSettingValue).Repeat.Once();
    8.     _repository.ReplayAll();
    9.     //Act
    10.     SomeClassThatNeedsTesting someClass = new SomeClassThatNeedsTesting(mockSettingsReader);
    11.     string val = someClass.GetSomeStringValue();
    12.     //Assert
    13.     Assert.AreEqual(myAppSettingValue, val, "Wrong value returned from GetSomeSringValue");
    14. }

    If you take a look at the test you can see that the first thing that I did was create my mock AppSettingReader and set my expectations.  After that I instantiated my class under test and passed in the settings reader mock.

    Hope you found this useful!  Complete code is available here!

    posted on Sunday, May 22, 2011 7:17:23 PM (Central Daylight Time, UTC-05:00)  #    Comments [0]
    # Saturday, April 02, 2011

    Unit testing certainly does give you the developer a warm fuzzy but that warm fuzzy can only get you so far.  In the end you still have to make sure all your little pieces of code/functionality play nice together.  This requires integration testing and if we are going to do any sort of testing that we actually expect to be performed on a regular basis we have to automate it.  Automated integration testing often gets neglected and is substituted with manual testing, which delays finding issues and adds time to the project timeline.  The reason that integration testing is often neglected is that it requires touching actual data. 

    Why is this is an issue:

    1. Someone has to take the time create the data for the testing.
    2. The data has to be reset after each test run

    All of this requires a lot of work, coordination…and a DBA [cringe]!

    Let me introduce a scenario where all that is not required.  Why can’t we wrap our tests in a Transaction?

    Here’s what I am thinking:

    1. Have a local empty copy of the database.
    2. Either in a test-by-test basis or test-suite basis
      1. Start a transaction (either at the start of your test or on build-up of the test suite)
      2. Create your data and put it in the DB
      3. Perform your tests on the data you just created and inserted
      4. Rollback the transaction
    3. … And Repeat

    Here is an example:

    1.         [TestMethod]
    2.         public void GetAllEligible_ShouldReturn_All_Attendess_InThe_Database_Where_IsEligible_Equals_True() {
    3.             using (new TransactionScope()) {
    4.                 //Arrange
    5.                 int expectedCount = 1;
    6.                 Attendee attendee1 = new Attendee {FirstName = "Joe", LastName = "Smith", IsEligible = true};
    7.                 Attendee attendee2 = new Attendee {FirstName = "Randy", LastName = "Jones", IsEligible = false};
    8.                 using (var dc = new DayOfDotNetDataContext()) {
    9.                     dc.Attendees.InsertAllOnSubmit(new List<Attendee> {attendee1, attendee2});
    10.                     dc.SubmitChanges();
    11.                 }
    12.                 //Act
    13.                 IAttendeeRepository attendeeRepository = new AttendeeRepository();
    14.                 IList<AttendeeDTO> attendees = attendeeRepository.GetAllEligible();
    15.                 //Assert
    16.                 attendees.Count.ShouldEqual(expectedCount, "Wrong number of attendess");
    17.             }
    18.         }

    You can see that the first line of my test starts a transaction scope.  I then create some data and add it to my empty database.  Now, remember this database needs to be empty as to not mess up your expectations.  After the data has been created I then perform the operation I am testing and assert the results.

    You may be confused by the lack of a “Rollback” statement.  The way TransactionScope works is that it only commits when explicitly told to do so.

    Automated integration testing is a must have and in order to make your life easier follow the steps I have outlined and you will be free to live the TDD dream!

    posted on Saturday, April 02, 2011 2:19:41 PM (Central Standard Time, UTC-06:00)  #    Comments [4]
    # Friday, December 17, 2010

    As I have stated in previous posts I am huge supporter of TDD and you can’t get too far doing true TDD before you are forced to introduce an IoC Container, also known as a Dependency Injection Container.  You can find out more about Inversion of Control and Dependency Injection here.  When I first started looking into using the concept of Inversion Of Control in my code, my first stop was StructureMap.  Why…I can’t really remember but it was the first IoC framework I tried and it is the one I currently prefer to use.  But, being a consultant I pride myself in knowing my options and being able to work with or recommend the tool that is best suited for the situation…hence this blog post and example code.  I decided to put together this post and code showing how, if you plan accordingly, you can swap out any of the *major* IoC Frameworks without impacting the code. 

    I set out with the goal of creating a swappable solution that would allow me work with the following IoC Frameworks.

    Side Note:  Using NuGet really makes pulling down tools/packages very easy.  Check It Out!

    So, let’s get started!  The basic principals of setting up and using an IoC container in code are the same no matter what Container you are using.  From the 30,000 foot view you need to:

    1. Map what concrete class implementations to use for what abstract (interface, abstract class) implementations.
    2. Have some way of resolving to a concrete implementation when passed an abstract implementation.

    To get the juices flowing here is how you tackle this in StructureMap.

    1. Create a class that will be called on when our app spins up that will take care of our abstract –> concrete mappings.  Typically this class is called a Bootstrapper.  As you can see this class contains when method called Bootstrap that performs the mapping.  In this example there is one mapping that says (see line 18) whenever you need a concrete instance of IMyBusinessClass use the MyBusinessClass class.
      1. using ChoosingAnIoC.Business;
      2. using ChoosingAnIoC.Core.Interfaces.Business;
      3. using StructureMap;
      5. namespace ChoosingAnIoC.App.Bootsrappers {
      7.     /// <summary>
      8.     /// Maps Abstract to Concrete Implementations Using StructureMap
      9.     /// </summary>
      10.     public class StructureMapBootstrapper : IBootstrapper {
      12.         #region IBootstrapper Members
      14.         /// <summary>
      15.         /// Setup of mappings
      16.         /// </summary>
      17.         public void Bootstrap() {
      18.             ObjectFactory.Initialize(x => x.For<IMyBusinessClass>().Use<MyBusinessClass>());
      19.         }
      21.         #endregion
      22.     }
      23. }


    1. Create a class that can use the IoC containers mappings to hand you a concrete instance of class on demand.  I call this class a Resolver.
      1. using ChoosingAnIoC.Core.Interfaces;
      2. using StructureMap;
      4. namespace ChoosingAnIoC.Core.DependencyResolvers
      5. {
      6.     /// <summary>
      7.     /// Class for resolving dependency's using StructureMap
      8.     /// </summary>
      9.     public class StructureMapDependencyResolver : IDependencyResolver
      10.     {
      11.         /// <summary>
      12.         /// Returns a concrete instance of the
      13.         /// supplied Interface
      14.         /// </summary>
      15.         /// <typeparam name="T">Interface of concrete instance to return</typeparam>
      16.         /// <returns>Concrete instance of the supplied interface</returns>
      17.         public T GetConcreteInstanceOf<T>() {
      18.             return ObjectFactory.GetInstance<T>();
      19.         }
      20.     }
      21. }

    If  we add enough level of abstraction at these two points we can swap out any of the current IoC containers and hopefully be able to handle any that come along in the future.  As you probably noticed in the two code examples above…both of these classes implement an interface.  Below is the code for the two interfaces.

        1. namespace ChoosingAnIoC.App.Bootsrappers {
        3.     /// <summary>
        4.     /// Bootsrapper Interface
        5.     /// </summary>
        6.     public interface IBootstrapper {
        8.         /// <summary>
        9.         /// Bootstrap and perform mappings
        10.         /// </summary>
        11.         void Bootstrap();
        12.     }
        13. }
        1. namespace ChoosingAnIoC.Core.Interfaces {
        3.     /// <summary>
        4.     /// Interface for implementations of Dependency Resolver
        5.     /// <remarks>
        6.     /// This interface adds a layer of abstraction when we
        7.     /// resolve dependencies.  It will allow us to swap out
        8.     /// out IoC framework with minimal impact on our code.
        9.     /// </remarks>
        10.     /// </summary>
        11.     public interface IDependencyResolver {
        13.         /// <summary>
        14.         /// Returns a concrete instance of the
        15.         /// supplied Interface
        16.         /// </summary>
        17.         /// <typeparam name="T">Interface of concrete instance to return</typeparam>
        18.         /// <returns>Concrete instance of the supplied interface</returns>
        19.         T GetConcreteInstanceOf<T>();
        21.     }
        22. }

                                      Use this code a couple of factory classes to return whatever Bootstrapper and DependencyResolver our application is configured to use we can swap out IoC containers without affecting our code.

                                      The complete code including implementations of all the IoC containers noted above can be found here!

                                      posted on Friday, December 17, 2010 11:06:46 AM (Central Standard Time, UTC-06:00)  #    Comments [3]
                                      # Friday, October 22, 2010

                                      At my current client I was tasked with implementing coding standards and styles and developing a process so the configurations can be easily maintained and shared.  ReSharper was already in place at the client and the since 99% of what they wanted to enforce, initially at least, was style related I chose to combine ReSharper with StyleCop.

                                      After looking around the interwebs for awhile I realized this process is either impossible or undocumented…or both.

                                      The process I came up with is about 90% of what I was hoping and still requires two manual steps by the developer but overall it is solid.  So, let’s get started.  First download and install the following tools:

                                      1. StyleCop 
                                      2. StyleCop+

                                      Although StyleCop+ is technically not required it does a great job with allowing you to extend and customize a lot of the built in StyleCop rules.  So I certainly recommend it.

                                      The trick with StyleCop is that it will continue to look up the code tree for settings files and keep adding them together and then adds the settings file from StyleCop install directory to top things off.  That is unless you tell it to do otherwise.  What where going to do is first place a Settings.StyleCop file where all devlopers can access it.  Next we are going to place another at the root of our code directory.  So if your code resides at C:\Dev\Code then place the Settings.StyleCop file there.  We can then open up the settings file we placed out on the network that everyone has access to and tell it not to merge with any other settings file.  This will be the official settings file.


                                      Next we will open the settings file in the root of our source tree and tell it merge only with the settings in the shared location.


                                      Now once you make changes at the shared level they will be merged with each developers settings file.

                                      Next we can deal with ReSharper…Stay Tuned!

                                      posted on Friday, October 22, 2010 4:19:52 PM (Central Daylight Time, UTC-05:00)  #    Comments [10]
                                      # Friday, September 17, 2010

                                      Earlier this week I got into a bit of spat with a couple of Tweeps on Twitter.  It started with someone I follow and respect re-tweeting something someone tweeted about him which basically said the tools which he is associated with aid developers in creating bad design.  I responded to this tweet in support of this person whom I respect by saying…

                                      Tools don’t do bad design.  Bad developers do bad design.

                                      Immediately after tweeting this I got multiple reply’s stating that just because you do bad design or write bad code you are not necessarily a bad developer. 

                                      To be blunt…this confused the hell out of me.  If you knowingly create a bad design or write bad code how can you be a good developer?  I guess the key word in that previous statement is *knowingly*.  But if you don’t know what good design/code is in my book you can’t be a good developer.

                                      Don’t get me wrong.  We have all been in the position when due to forces outside of our control we have been forced to write imperfect code or create a less than perfect design.  To me this is one place where you can quantifiably determine the good developer from the bad developer.  A good developer, when writing imperfect code due to factors outside of there control, will do one or more of the following:

                                      1. Get upset because they know they are writing less than perfect code/design.
                                      2. Leave a comment stating why the code/design was done in this factor.
                                      3. Add a ToDo for refactoring later.
                                      4. Will do the imperfect code/design in such a way that the refactoring effort will require less effort.

                                      This argument of writing bad code does not a bad developer make really rattles me.  That is exactly what it does!

                                      OK…Let me have it!

                                      posted on Friday, September 17, 2010 8:58:51 AM (Central Daylight Time, UTC-05:00)  #    Comments [1]
                                      # Friday, September 10, 2010

                                      * Download Complete Source Code

                                      In my previous post I covered doing automated user interface testing of a WPF application using Iron Ruby and Cucumber.  The reason I was drawn to this path was my current interest in Ruby, Rails, and BDD.  What made Bewildr such a draw for me, other than writing my tests in IronRuby, was the fact that I can use with Cucumber and have a truly human-readable natural language test.

                                      1. Scenario: The Log On window should be displayed on application start
                                      2.     Given I ensure that there are no instances of "CompositeAppPoc.Shell.exe" running
                                      3.     When I start "C:\\MyCompositeAppPoc.Shell.exe"
                                      4.     Then 1 window is displayed with name "Log On"
                                      5.       And Terminate the app

                                      Again, because of the learning curve and the fact that I would be introducing a completely new programming language, and let’s face it a completely new way of thinking, into a corporate environment that I will not be around to support long-term I had to pursue a more conventional solution, which led me to White.

                                      White is an automated UI testing framework similar to Bewildr in that they both rely on the MS UI Automation Framework to hook and manipulate the user interface.  What makes White a better choice given my current situation is that from a programmers perspective it is implemented and reads exactly like the standard .NET test frameworks.

                                      1. [TestMethod]
                                      2. public void OnApplicationStart_TheLogOnWindow_ShouldBeDisplayed() {
                                      3.     //Act
                                      4.     Window window = _app.GetWindow("Log On");
                                      5.     //Assert
                                      6.     window.ShouldNotBeNull();
                                      7. }

                                      Take a look at the video clip below to see what running a White test looks like.

                                      Getting up and running with White is very easy.  Other than downloading the binaries from CodePlex all you need is a tool like UISpy to help you dig deep into how the UI elements are rendered.

                                      At the highest level White operates on the concepts of Application and Windows.  Application being the application you are testing and Windows being the main surface of the application.  As a best practice I would recommend spinning up the application, retrieving your window(s) and killing your application as part of test setup and teardown.

                                      1. #region Private Fields
                                      3. private Application _app;
                                      4. private Window _window;
                                      6. #endregion
                                      8. #region Setup & Tear Down
                                      10. [TestInitialize]
                                      11. public void MyTestInitialize() {
                                      12.     _app = Application.Launch(@"c:\pathtomyapp\myapp.exe");
                                      13.     _window = _app.GetWindow("MyWindow");
                                      14. }
                                      16. [TestCleanup]
                                      17. public void MyTestCleanup() {
                                      18.     _app.Kill();
                                      19. }
                                      21. #endregion

                                      With all that in place let’s walk through setting up a couple tests.

                                      The first thing I want to test is that when my application spins up for the first time the Log On window is displayed.  Because this is an Application level test I am going to put it in a test class called ApplicationTests.  I will use the practice of spinning up the app and killing it as I described above.  My test will simply attempt to retrieve a window with title “Log On” and make sure it is not null.

                                      1. [TestClass]
                                      2. public class ApplicationTests {
                                      3.     #region Private Fields
                                      5.     private Application _app;
                                      7.     #endregion
                                      9.     #region Setup & Tear Down
                                      11.     [TestInitialize]
                                      12.     public void MyTestInitialize() {
                                      13.         _app = Application.Launch(
                                      14.         @"c:\wpf\compositeapppoc\compositeapppoc.shell\compositeapppoc.shell\bin\debug\compositeapppoc.shell.exe");
                                      15.     }
                                      17.     [TestCleanup]
                                      18.     public void MyTestCleanup() {
                                      19.         _app.Kill();
                                      20.     }
                                      22.     #endregion
                                      24.     [TestMethod]
                                      25.     public void OnApplicationStart_TheLogOnWindow_ShouldBeDisplayed() {
                                      26.         //Act
                                      27.         Window window = _app.GetWindow("Log On");
                                      28.         //Assert
                                      29.         window.ShouldNotBeNull();
                                      30.     }
                                      31. }

                                      My next test is going to be to make sure that when I enter an invalid username and password and click the log on button a message is displayed telling me my credentials are not valid.  Because this test is specific to the Log On window I am going to create a new test class called LogOnTests.  I will use the practice of spinning up the app, getting my window and killing the app as I described above.  My test will enter an invalid username and password, click the log on button, and verify that the error message label is visible.

                                      1. [TestClass]
                                      2. public class LogOnTests {
                                      4.     #region Private Fields
                                      6.     private Application _app;
                                      7.     private Window _window;
                                      9.     #endregion
                                      11.     #region Setup & Tear Down
                                      13.     [TestInitialize]
                                      14.     public void MyTestInitialize() {
                                      15.         _app = Application.Launch(
                                      16.             @"c:\wpf\compositeapppoc\compositeapppoc.shell\compositeapppoc.shell\bin\debug\compositeapppoc.shell.exe");
                                      17.         _window = _app.GetWindow("Log On");
                                      18.     }
                                      20.     [TestCleanup]
                                      21.     public void MyTestCleanup() {
                                      22.         _app.Kill();
                                      23.     }
                                      25.     #endregion
                                      27.    [TestMethod]
                                      28.     public void Entering_InvalidCredentials_AndClickingThe_LogOnButton_ShouldDisplayThe_InvalidCredentialsMessage() {
                                      29.         //Arrange
                                      30.         _window.Get<TextBox>("txtUsername").Text = "InvalidUsername";
                                      31.         _window.Get<TextBox>("txtPassword").Text = "InvalidPassword";
                                      32.         var btn = _window.Get<Button>("btnLogOn");
                                      33.         //Act
                                      34.         btn.Click();
                                      35.         _window = _app.GetWindow("Log On");
                                      36.         //Assert
                                      37.         (_window.Get<Label>("lblErrorMessage")).Visible.ShouldBeTrue();
                                      38.     }
                                      39. }

                                      It’s that easy.  With very little effort you can have a full suite of automated tests for testing your UI.  How cool is that!?

                                      * Download Complete Source Code

                                      posted on Friday, September 10, 2010 4:25:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [6]
                                      # Monday, August 23, 2010

                                      * Download Complete Source Code

                                      In an attempt to be a Pragmatic Programmer I make an effort to learn a new programming language yearly.  This year the language of choice is Ruby, including Rails.  About a month ago I started the Build Your Own Blog :: Rails series at TekPub.  In this series Rob Conery instructs on creating a blog engine using Rails and focusing on Behavior Driven Development.  Rob introduces some amazing tools, such as Cucumber and Pickle, that make BDD on Rails easy and dare I say…fun!

                                      If you have been following along at home with my previous serious of blog posts you know that in my day job I am currently architecting a large WPF MVVM composite application using Prism.  My development methodology for .Net development is TDD and not BDD, because I just don’t feel the tools are there yet in the .Net space for efficient BDD.  I am at the point in the project where I am starting work on the UI and being fresh of learning the wonderful BDD tools available in the Rails stack it was really annoying me that I had no way to TDD my UI.  Grant it, using MVVM I was able to get much closer to the actual UI than I otherwise would, but it still wasn’t the same.  Finally I got to the point where I just had to research the idea of Cucumber style testing in WPF.  What I found out was it is possible using IronRuby.  Don’t be mistaken, it does not offer the same ease and simplicity as it does on the Rails stack but it is certainly a leap in the right direction.

                                      The tool that is going to make this all possible was written by Nathaniel Ritmeyer and is called Bewildr!

                                      Here are the steps to getting your environment setup…

                                      1. Follow the steps in my previous blog post to get Ruby, IronRuby, and Cucumber installed. 
                                      2. Install Bewildr.
                                      3. Install UISpy.

                                      I am going to be testing the UI created in my previous series: Rolling Your Own Module Level Security for a WPF MVVM Composite Application

                                      Detailed information on Cucumber can be found here.  But, basically Cucumber allows you to write plain-text functional descriptions as automated tests.  Cucumber code consists of two main pieces; Features/Scenarios and Step Definitions.  This is not meant to be a Cucumber tutorial so if you are not familiar with Cucumber I would suggest reading up on it prior to continuing.

                                      OK.  So, now that your familiar with Cucumber you are probably asking yourself how is this going to allow me to do automated UI testing?  This is where Bewildr enters the party.  Bewildr is a Ruby GEM that uses the MS UI Automation Framework to gain programmatic access to a WPF UI.  Basically, I can spin up a WPF application and manipulate the UI, click buttons, enter text in text boxes, etc, all via code.

                                      So, let’s start with a simple scenario.  (I apologize for the formatting/highlighting…need to find a good formatter plug-in for Cucumber code.

                                      1. @application
                                      2. @window
                                      4. Feature: Application Interaction
                                      6.   Scenario: The Log On window should be displayed on application start
                                      7.     Given I ensure that there are no instances of "CompositeAppPoc.Shell.exe" running
                                      8.     When I start "C:\\development\\research\\wpf\\CompositeAppPoc\\CompositeAppPoc.Shell\\CompositeAppPoc.Shell\\bin\\Debug\\CompositeAppPoc.Shell.exe"
                                      9.     Then 1 window is displayed with name "Log On"
                                      10.       And Terminate the app

                                      If we go ahead and run this feature Cucumber is going to puke on us because we haven’t created our steps yet.  But, when Cucumber pukes…it pukes in a helpful way.  It is going to give us the shell for the steps we need to create in order to execute this feature.


                                      As you can see Cucumber lets us know that we need to define 4 steps in order to get our Feature and Scenario running.  So let’s do that.  Since 3 of the steps deal with the application itself and 1 deals specifically with a window I am going to create 2 step files.

                                      1. require 'bewildr'
                                      3. Given /^I ensure that there are no instances of "([^"]*)" running$/ do |app|
                                      4.   Bewildr::Application.kill_all_processes_with_name(app)
                                      5. end
                                      7. When /^I start "([^"]*)"$/ do |app|
                                      8.   @application = Bewildr::Application.start(app)
                                      9. end
                                      11. When /^Terminate the app$/ do
                                      12.   @application.kill
                                      13. end

                                      1. require 'bewildr'
                                      3. Then /^ (\d+) window is displayed with name "([^"]*)"$/ do |count,name|
                                      4.       @window = @application.wait_for_window(name)
                                      5.       @application.windows.size.should == count.to_i
                                      6.       @window.name.should match(name)
                                      7. end

                                      In the steps coded above you can begin to see what Bewildr allows us to do.  Now if you run this feature you should see the output below as well as the app physically spinning up and closing.


                                      And as you can see our scenario passed.

                                      This is really just scratching the surface of what you can do.  I would suggest downloading the code and get an understanding of some of the more advanced scenarios and then start creating your own.

                                      * Download Complete Source Code

                                      posted on Monday, August 23, 2010 6:04:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [145]
                                      # Monday, August 16, 2010

                                      Note: This expands on the code created in my previous post: Requiring Log-On in a WPF MVVM Composite Application

                                      * Download Complete Source Code

                                      Continuing on my WPF MVVM Adventures...  Well, I am still waiting on the business to finalize the requirements so I am going to take a shot at coding it to what I think the final specs will be.  Although this is a very common situation, when you take this slippery slope you need to be careful that you don’t end up creating throw away code.   Make sure you:

                                      1. Program to Interfaces. (FYI – you should be doing this anyway!)
                                      2. Add Abstraction layers that will allow you to swap out implementation. (See step 1)
                                      3. Keep all the possible solutions to the problem in mind when designing/coding.  In my case I am 99% certain the business will want security down to the composite module level, but I am still going to leave paths open that will allow me to implement field level security without too much re-work.

                                      The first thing I need is to define by security roles.  Since the actual roles are TBD I am just going to create a simple Enumeration.

                                      1. namespace CompositeAppPoc.Infrastructure.Enumerations {
                                      3.     public enum AuthorizationLevel {
                                      4.         ReadOnly,
                                      5.         ReadWrite,
                                      6.         Admin
                                      7.     }
                                      8. }

                                      In thinking about what the Authentication method of my yet to be created service will return I decided it was going to need to return multiple things.

                                      1. Boolean representing whether or not the credentials where able to be authenticated.
                                      2. Level of authorization granted to credentials.
                                      3. List of modules that credentials are able to view.

                                      Knowing I was going to need to return multiple values I created a data transfer object (DTO) to handle it.

                                      1. using System.Collections.Generic;
                                      2. using CompositeAppPoc.Infrastructure.Enumerations;
                                      4. namespace CompositeAppPoc.Infrastructure.DataTransferObjects {
                                      6.     public class AuthenticationContext {
                                      8.         public bool IsAuthorized { get; set; }
                                      10.         public AuthorizationLevel AuthLevel { get; set; }
                                      12.         public IList<string> AllowedModules { get; set; }
                                      14.     }
                                      15. }

                                      Now I can create my service.  This is going to reside in my Infrastructure project and will allow me to push(abstract) the implementation of the actual authentication farther down the stack.  Sticking to what I recommended at the beginning of this post I am going to create a simple interface for the service.  The interface will declare one signature, Authenticate, that accepts a username and password and returns an AuthenticationContext.

                                      1. using CompositeAppPoc.Infrastructure.DataTransferObjects;
                                      3. namespace CompositeAppPoc.Infrastructure.Interfaces {
                                      5.     public interface IAuthenticationService {
                                      6.         AuthenticationContext Authenticate(string userName, string password);
                                      7.     }
                                      8. }

                                      Next we need to code the actual implementation of IAuthenticationService.  At this time the implementation of Authenticate will need to perform the actual authentication, which will set the IsAuthorized flag as well as the AuthLevel, and determine what modules are viewable for the AuthLevel.  Because I still have not defined the details of these process I am going to “stub” them out with a trivial implementation.

                                      1. using System.Collections.Generic;
                                      2. using CompositeAppPoc.Infrastructure.Constants;
                                      3. using CompositeAppPoc.Infrastructure.DataTransferObjects;
                                      4. using CompositeAppPoc.Infrastructure.Enumerations;
                                      5. using CompositeAppPoc.Infrastructure.Interfaces;
                                      7. namespace CompositeAppPoc.Infrastructure.Services {
                                      9.     public class AuthenticationService : IAuthenticationService {
                                      11.         private readonly AuthenticationContext _authenticationContext = new AuthenticationContext();
                                      13.         public AuthenticationContext Authenticate(string userName, string password) {
                                      14.             Authorize(userName, password);
                                      15.             if (_authenticationContext.IsAuthorized) {
                                      16.                 GetApprovedModules();
                                      17.             }
                                      18.             return _authenticationContext;
                                      19.         }
                                      21.         private void Authorize(string userName, string password) {
                                      22.             if (userName.Equals("admin") && password.Equals("pass")) {
                                      23.                 _authenticationContext.IsAuthorized = true;
                                      24.                 _authenticationContext.AuthLevel = AuthorizationLevel.Admin;
                                      25.             }
                                      26.             else if (userName.Equals("readwrite") && password.Equals("pass")) {
                                      27.                 _authenticationContext.IsAuthorized = true;
                                      28.                 _authenticationContext.AuthLevel = AuthorizationLevel.ReadWrite;
                                      29.             }
                                      30.             else if (userName.Equals("readonly") && password.Equals("pass")) {
                                      31.                 _authenticationContext.IsAuthorized = true;
                                      32.                 _authenticationContext.AuthLevel = AuthorizationLevel.ReadOnly;
                                      33.             }
                                      34.         }
                                      36.         private void GetApprovedModules() {
                                      37.             IList<string> modules = new List<string>();
                                      38.             switch (_authenticationContext.AuthLevel) {
                                      39.                 case AuthorizationLevel.Admin:
                                      40.                     modules.Add(EmployeeConstants.EmployeeEditModuleName);
                                      41.                     modules.Add(EmployeeConstants.EmployeeCreateModuleName);
                                      42.                     break;
                                      43.                 case AuthorizationLevel.ReadWrite:
                                      44.                     modules.Add(EmployeeConstants.EmployeeCreateModuleName);
                                      45.                     break;
                                      46.             }
                                      47.             _authenticationContext.AllowedModules = modules;
                                      48.         }
                                      49.     }
                                      50. }

                                      Now we need to hop over the Shell project and start making adding in the hooks for our module level security.

                                      This first I am going to do is change how the modules are loaded.  Initially I used the ConfigurationModuleCatalog which loads the modules from a configuration file.  I decided against this approach because I wanted to avoid configuration changes when a module was added or removed.  Luckily Prism provides another option called the DirectoryModuleCatalog.  This allows you to supply a directory path that contains the dll’s for your modules.  So, all that needs to be done in order to add a new module is to drop its dll’s in that directory.  This change needs to implemented in the bootstrapper and while we are in there we need to tell our IOC container how to wire up our AuthenticationService.

                                      1. using System.Windows;
                                      2. using CompositeAppPoc.Infrastructure.Interfaces;
                                      3. using CompositeAppPoc.Infrastructure.Services;
                                      4. using Microsoft.Practices.Composite.Modularity;
                                      5. using Microsoft.Practices.Composite.UnityExtensions;
                                      6. using Microsoft.Practices.Unity;
                                      8. namespace CompositeAppPoc.Shell {
                                      10.     public class Bootstrapper : UnityBootstrapper {
                                      12.         protected override DependencyObject CreateShell() {
                                      13.             Shell shell = new Shell();
                                      14.             shell.Show();
                                      15.             return shell;
                                      16.         }
                                      18.         protected override IModuleCatalog GetModuleCatalog() {
                                      19.             return new DirectoryModuleCatalog() {ModulePath=Infrastructure.Constants.GeneralConstants.ModulePath};
                                      20.         }
                                      22.         protected override void ConfigureContainer() {
                                      23.             base.ConfigureContainer();
                                      24.             Container.RegisterType<IAuthenticationService, AuthenticationService>(new ContainerControlledLifetimeManager());
                                      25.             Container.RegisterType<IEmployeeDataService, EmployeeDataService>(new ContainerControlledLifetimeManager());
                                      26.             Container.RegisterType<IModuleManager, ModuleManager>(new ContainerControlledLifetimeManager());
                                      27.         }
                                      28.     }
                                      29. }

                                      So now that we did that we can more easily add new modules but it’s still all or nothing.  We need to tell Prism to not load certain modules until we tell it to…load on demand.  This is accomplished by simply by decorating the modules you want to load on demand with the Module attribute and setting the ModuleName and OnDemand properties.  As you can guess we are going to set the OnDemand property to “True”.  This tells Prism, when it is processing the modules in the directory we tell it, not to load the module just yet.  Prism notes the name of the module and waits for us to tell it when to load it.  We will do this on the EmployeeEditModule, and EmployeeCreateModule which will both require authorization but we will not do this to the EmployeeListModule because that module is viewable by all.

                                      1. [Module(ModuleName=EmployeeConstants.EmployeeEditModuleName, OnDemand=true)]
                                      2. public class EmployeeEditModule : IModule {

                                      1. [Module(ModuleName=EmployeeConstants.EmployeeCreateModuleName, OnDemand=true)]
                                      2. public class EmployeeCreateModule : IModule {

                                      Now when you run the the shell you won’t be able to edit or create a new employee because those modules are not loaded which means that nothing is registered to the associated commands.

                                      We already have the list of allowed secured modules being returned from the authentication service so we just need to write a method to process the list and load the modules.  This method will be in the Bootstrapper and it will load the allowed secured modules using the Module Manager.

                                      1. public void LoadSecuredModules(IList<string> allowedModules) {
                                      2.     var moduleManager = Container.Resolve<IModuleManager>();
                                      3.     foreach (string module in allowedModules) {
                                      4.         moduleManager.LoadModule(module);
                                      5.     }
                                      6. }

                                      Lastly we need to call LoadSecuredModules.  We will do this as the last step in the App.xaml’s StartUp method.

                                      1. private static void StartUp(IList<string> allowedModules) {
                                      2.     Current.MainWindow = null;
                                      3.     Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
                                      4.     var bs = new Bootstrapper();
                                      5.     bs.Run();
                                      6.     bs.LoadSecuredModules(allowedModules);
                                      7. }

                                      Now when we log in with a read-only id (readonly,pass) the edit and create new buttons are not enabled because the modules are not loaded.


                                      * Download Complete Source Code

                                      posted on Monday, August 16, 2010 5:40:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [39]
                                      # Friday, August 13, 2010

                                      In doing some research I found that it is possible to do Rails type BDD/testing in WPF using IronRuby.  I am very excited about this and will be doing an in-depth post on this in the very near future.  But, for now I wanted to get a post out on how to get Cucumber up and running in IronRuby because in attempting to do this myself I ran into an issue that turns out is fairly well-known but as far as I can tell is not documented.  I would like to thank Nathaniel Ritmeyer, aka NatOnTesting, for helping me through this and take a look at his Bewildr gem…it will be a key piece of my future post.

                                      Here are the steps for getting Cucumber up and running with IronRuby:

                                      1. Install Ruby (to save headaches install to c:\ruby and make sure “c:\ruby\bin” is in your Path environment variable)
                                      2. Install IronRuby (to save headaches install to c:\ironruby and make sure “c:\ironruby\bin” is in your Path environment variable)
                                      3. Install Cucumber (here is the undocumented part…until now)
                                        1. Because Gherkin is required by Cucumber version > 0.6.3 and Gherkin is not compatible with IronRuby we need to install Cucumber version <= 0.6.3.
                                        2. image
                                      4. Next you need to create a Cucumber wrapper script for IronRuby
                                        1. Go to c:\ruby\bin
                                        2. Create a blank text file “icucumber.bat”
                                        3. Open icucumber.bat in text editor
                                        4. Enter this text
                                          1. @ECHO OFF
                                            SET GEM_PATH=c:\ruby\lib\ruby\gems\1.9.1
                                            @"C:\IronRuby\bin\ir.exe" "c:\Ruby\bin\cucumber" %*

                                        5. Save the file
                                      5. Test it (results are truncated)


                                      That’s it.  You now have Cucumber running with IronRuby.  Why is this helpful?  Stay Tuned!

                                      posted on Friday, August 13, 2010 5:00:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [6]
                                      # Monday, August 09, 2010

                                      Note: This expands on the code created in my previous post: Implementing Attribute Based Domain Validation In a WPF MVVM Application

                                      * Download Complete Source Code

                                      Continuing on my WPF MVVM Adventures... My next task was to implement security on my composite application.  Unfortunately, as is all to often the case, there where still business decisions to be made concerning the granularity of the security {is field level required} and also the source of record {LDAP, roll-our-own}.  Not wanting to loose focus on the security piece and knowing I couldn’t sit around and do nothing I decided to tackle the one piece I knew that was constant…I was going to need a UI for logging in a user.

                                      I started this process by creating a simple/standard log on window.

                                      image  image 

                                      1. <Window x:Class="CompositeAppPoc.Shell.LogOn"
                                      2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                                      3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                                      4.         Title="Log On" SizeToContent="WidthAndHeight"
                                      5.         WindowStartupLocation="CenterScreen" WindowStyle="None"
                                      6.         ResizeMode="NoResize" MinWidth="300" BorderThickness="4" AllowsTransparency="True">
                                      8.     <Window.Resources>
                                      9.         <Style TargetType="TextBox">
                                      10.             <Setter Property="Margin" Value="4"/>
                                      11.             <Setter Property="MinWidth" Value="100"/>
                                      12.         </Style>
                                      13.         <Style TargetType="PasswordBox">
                                      14.             <Setter Property="Margin" Value="4"/>
                                      15.             <Setter Property="MinWidth" Value="100"/>
                                      16.         </Style>
                                      17.         <Style TargetType="Button">
                                      18.             <Setter Property="Margin" Value="4"/>
                                      19.             <Setter Property="MinWidth" Value="75"/>
                                      20.         </Style>
                                      21.     </Window.Resources>
                                      23.     <Grid>
                                      24.         <Grid.ColumnDefinitions>
                                      25.             <ColumnDefinition Width="Auto"/>
                                      26.             <ColumnDefinition/>
                                      27.         </Grid.ColumnDefinitions>
                                      28.         <Grid.RowDefinitions>
                                      29.             <RowDefinition Height="Auto"/>
                                      30.             <RowDefinition Height="Auto"/>
                                      31.             <RowDefinition Height="Auto"/>
                                      32.             <RowDefinition Height="Auto"/>
                                      33.             <RowDefinition/>
                                      34.         </Grid.RowDefinitions>
                                      35.         <!-- Header -->
                                      36.         <StackPanel Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2">
                                      37.             <Label HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"
                                      38.                    FontWeight="Bold" FontSize="16" Content="Log On">
                                      39.             </Label>
                                      40.         </StackPanel>
                                      41.         <!-- Main Controls -->
                                      42.         <Label Grid.Column="0" Grid.Row="1" HorizontalAlignment="Right" Content="User Name"/>
                                      43.         <TextBox Grid.Column="1" Grid.Row="1" GotFocus="CredentialsFocussed" x:Name="txtUsername"/>
                                      44.         <Label Grid.Column="0" Grid.Row="2" HorizontalAlignment="Right" Content="Password"/>
                                      45.         <PasswordBox Grid.Column="1" Grid.Row="2" GotFocus="CredentialsFocussed" x:Name="txtPassword" />
                                      46.         <Label Grid.Column="0" Grid.Row="3" Grid.ColumnSpan="2" HorizontalAlignment="Center" Foreground="Red" FontStyle="Italic" Visibility="{Binding ShowInvalidCredentials}" Content="*Invalid User Name and/or Password"/>
                                      47.         <StackPanel Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="2" Orientation="Horizontal" VerticalAlignment="Bottom" Margin="5" HorizontalAlignment="Right" Height="Auto">
                                      48.             <Button Content="Log-on" Click="LogonClick" IsDefault="True"/>
                                      49.             <Button Content="Cancel" IsCancel="True"/>
                                      50.         </StackPanel>
                                      52.     </Grid>
                                      54. </Window>

                                      1. using System.ComponentModel;
                                      2. using System.Windows;
                                      3. using System.Windows.Controls;
                                      4. using System.Windows.Controls.Primitives;
                                      6. namespace CompositeAppPoc.Shell {
                                      8.     public partial class LogOn : Window, INotifyPropertyChanged {
                                      10.         #region Private Fields
                                      12.         private int _attempts;
                                      14.         #endregion
                                      16.         #region Public Properties
                                      18.         public int Attempts {
                                      19.             get { return _attempts; }
                                      20.             set {
                                      21.                 if (value != _attempts) {
                                      22.                     _attempts = value;
                                      23.                     OnPropertyChanged("Attempts");
                                      24.                 }
                                      25.             }
                                      26.         }
                                      28.         public Visibility ShowInvalidCredentials {
                                      29.             get {
                                      30.                 if (_attempts > 0) {
                                      31.                     return Visibility.Visible;
                                      32.                 }
                                      33.                 return Visibility.Hidden;
                                      34.             }
                                      35.         }
                                      37.         public string UserName {
                                      38.             get { return txtUsername.Text; }
                                      39.         }
                                      41.         public string Password {
                                      42.             get { return txtPassword.Password; }
                                      43.         }
                                      45.         #endregion
                                      47.         public LogOn() : this(string.Empty,string.Empty) {}
                                      49.         public LogOn(string userName, string password) {
                                      50.             InitializeComponent();
                                      51.             DataContext = this;
                                      52.             txtUsername.Focus();
                                      53.             txtUsername.Text = userName;
                                      54.             txtPassword.Password = password;
                                      55.         }
                                      57.         #region INotifyPropertyChanged Members
                                      59.         public event PropertyChangedEventHandler PropertyChanged {
                                      60.             add { PropertyChangedEvent += value; }
                                      61.             remove { PropertyChangedEvent -= value; }
                                      62.         }
                                      64.         #endregion
                                      66.         private void LogonClick(object sender, RoutedEventArgs e) {
                                      67.             DialogResult = true;
                                      68.             Close();
                                      69.         }
                                      71.         private void CredentialsFocussed(object sender, RoutedEventArgs e) {
                                      72.             TextBoxBase tb = sender as TextBoxBase;
                                      73.             if (tb == null) {
                                      74.                 PasswordBox pwb = sender as PasswordBox;
                                      75.                 pwb.SelectAll();
                                      76.             }
                                      77.             else {
                                      78.                 tb.SelectAll();
                                      79.             }
                                      80.         }
                                      82.         private event PropertyChangedEventHandler PropertyChangedEvent;
                                      84.         protected void OnPropertyChanged(string prop) {
                                      85.             if (PropertyChangedEvent != null)
                                      86.                 PropertyChangedEvent(this, new PropertyChangedEventArgs(prop));
                                      87.         }
                                      88.     }
                                      89. }

                                      Now I have my Log On window but it doesn’t do anything.  I need to tell my application to show that window first.  Your first thought would be to go into the project properties and set LogOn as the startup object, but once you got in there you would notice that there is currently no startup object defined and this is by design.  Currently, because we are working with a composite application, all of that is handles by our Bootstrapper which is kicked off from App.xaml in the OnStartUp event.

                                      App.xaml.cs (Old)
                                      1. using System.Windows;
                                      3. namespace CompositeAppPoc.Shell {
                                      5.     public partial class App : Application {
                                      7.         protected override void OnStartup(StartupEventArgs e) {
                                      8.             base.OnStartup(e);
                                      9.             new Bootstrapper().Run();
                                      10.         }
                                      12.     }
                                      13. }

                                      We need to modify App.xaml.cs to:

                                      1. Show LogOn dialog
                                      2. Process result from LogOn dialog
                                        1. If ‘Cancel’ is clicked then close the application
                                        2. If ‘OK’ is clicked
                                          1. Perform authorization
                                            1. If authorized
                                              1. Run the bootstrapper
                                            2. If not authorized
                                              1. If exceeded the number of allowed attempts close the application
                                              2. Else…add 1 to the attempts, store username and password, and re-show the LogOn
                                      App.xaml.cs (New)
                                      1. using System.Collections.Generic;
                                      2. using System.Windows;
                                      3. using CompositeAppPoc.Infrastructure.Entities;
                                      4. using CompositeAppPoc.Infrastructure.Services;
                                      6. namespace CompositeAppPoc.Shell {
                                      8.     public partial class App : Application {
                                      10.         #region Private Fields
                                      12.         private readonly AuthenticationService _authenticationService = new AuthenticationService();
                                      13.         private int _attempts;
                                      14.         private string _userName = "";
                                      15.         private string _pass = "";
                                      17.         #endregion
                                      19.         #region Private Methods
                                      21.         private void ShowLogOn() {
                                      22.             var logon = new LogOn(_userName,_pass);
                                      23.             logon.Attempts = _attempts;
                                      24.             bool? res = logon.ShowDialog();
                                      25.             if (!res ?? true) {
                                      26.                 Shutdown(1);
                                      27.             }
                                      28.             else {
                                      29.                 AuthenticationContext ac = _authenticationService.Authenticate(logon.UserName, logon.Password);
                                      30.                 if (ac.IsAuthorized) {
                                      31.                     StartUp(ac.AllowedModules);
                                      32.                 }
                                      33.                 else {
                                      34.                     if (logon.Attempts > 2) {
                                      35.                         MessageBox.Show("Application is exiting due to invalid credentials", "Application Exit", MessageBoxButton.OK, MessageBoxImage.Error);
                                      36.                         Shutdown(1);
                                      37.                     }
                                      38.                     else {
                                      39.                         _attempts += 1;
                                      40.                         _userName = logon.UserName;
                                      41.                         _pass = logon.Password;
                                      42.                         ShowLogOn();
                                      43.                     }
                                      44.                 }
                                      45.             }
                                      46.         }
                                      48.         private static void StartUp(IList<string> allowedModules) {
                                      49.             Current.MainWindow = null;
                                      50.             Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
                                      51.             var bs = new Bootstrapper();
                                      52.             bs.Run();
                                      53.             bs.LoadSecuredModules(allowedModules);
                                      54.         }
                                      56.         #endregion
                                      58.         #region Public Methods
                                      61.         public App() {
                                      62.             Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                                      63.             ShowLogOn();
                                      64.         }
                                      66.         #endregion
                                      67.     }
                                      68. }

                                      That’s it, now we are requiring logging in to our application.  You may notice that there are bits in there that we haven’t covered yet, AuthenticationContext etc., this was me planning for the actual authentication implementation and can be replaced with whatever code you need.

                                      Stay tuned for the actual security implementation.

                                      * Download Complete Source Code

                                      posted on Monday, August 09, 2010 4:02:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [2]
                                      # Thursday, July 29, 2010

                                      Note: This expands on the code created in my previous post: WPF MVVM Multi-Solution Composite App


                                      * Download Complete Source Code

                                      Continuing on my WPF MVVM Adventures... My next task was to architect and code a validation framework that would:

                                      1. Adhere to the DRY principle.
                                      2. Allow me to define all validation in my domain objects.
                                      3. Allow me to easily relay validation issues to the UI/users.
                                      4. Allow me to easily add/modify validation rules.
                                      5. Not be *too* complex :)

                                      Not wanting to re-invent the wheel I did some Googling, on Bing of course.  The first post that caught my eye was by Karl Shifflett, whom to me is one of the Grandfathers of WPF, and despite being a VB guy, usually has the answer.  So I read Karl’s article, downloaded the code and did some investigating.  The code would get the job done, but it wasn’t DRY.  Basically every field that was required had a check for not null and not empty, all validation code was done in the IDataErrorInfo’s Item override,  and even Karl himself recommends not doing it this way, and that you should use Ocean or another validation framework.  Not to discredit Karl, and I certainly recommend reading not only this post but all of Karl’s posts, but this didn’t fill all of my requirements.  Also, I am the type of developer who won’t use a framework for something I can code myself with out too much effort.

                                      The next post that looked promising was by Josh Smith, whose Advanced MVVM book is a must read for anyone using MVVM.  Josh’s approach is nearly identical to Karl’s in that the base of the validation logic is repeated for every field.  Josh’s example also allows for further validation to be done at the ViewModel level, and this confuses me a little, in that the domain object itself should be the *gatekeeper* of valid object state.

                                      So, having read these two posts from two of the more prominent WPF developers, and not finding what I wanted worried me.  Maybe I am totally missing something or what I want is flawed.  But hey, that’s why I blog…if I’m wrong call me out…and tell me why.

                                      I started throwing some designs and thoughts down on paper and kept coming back to using attributes on the properties of domain objects.  Now, I am by no means a developer that pushes or even prefers attribute based solutions, but in this case it seemed to fit.

                                      I knew that I was going to need an Interface or Abstract Base Class that would allow me to generically process the validators and always know what I was dealing with.  In this case I decided to go with an abstract base class just so I could have it inherit from Attribute and only require my instances of Validator to inherit a single class.  As you can see below the base class is very simple, it inherits Attribute and declares an abstract Validate method.  The other thing you’ll notice is that I decided to decorate the base class with the Attribute configuration.  This may change in the future, i.e. in some instances I may want to allow multiple of the same validator…say, if each is configurable.

                                        1: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, 
                                        2:      AllowMultiple = false, Inherited = true)]
                                        3:  public abstract class ValidatorBase : Attribute {
                                        4:      public abstract string Validate(object value);
                                        5:  }

                                      Now I need a validator.  Let’s start simple with a standard required field validator.  I created my class, made it inherit from ValidatorBase and coded the Validate override.

                                        1: public class ValidRequiredField : ValidatorBase {
                                        3:     private const string _INVALID_REQUIRED_FIELD = "Required Field";
                                        5:     public override string Validate(object value) {
                                        6:         try {
                                        7:              if (value == null || string.IsNullOrEmpty(value.ToString()))
                                        8:                  return _INVALID_REQUIRED_FIELD;
                                        9:         }
                                       10:         catch (NullReferenceException) {
                                       11:             return _INVALID_REQUIRED_FIELD;
                                       12:         }
                                       13:         return null; 
                                       14:     }
                                       15: }

                                      The next step is decorate the properties in the domain entity with any validation attributes.  In this case I am decorating the LastName property with the ValidRequiredField attribute.

                                        1: [ValidRequiredField]
                                        2: public string LastName {
                                        3:     get { return _lastName; }
                                        4:     set {
                                        5:         if (_lastName != value) {
                                        6:             _lastName = value;
                                        7:             OnPropertyChanged("LastName");
                                        8:         }
                                        9:     }
                                       10: }

                                      OK.  Cool.  Unfortunately, this by itself does nothing.  We have to kick off the validation and put in the processes that allow the ViewModel and UI to receive notification of validation issues.  We will start this process by creating an abstract base class that our domain entities will inherit from.  This abstract base class will implement INotifyPropertyChanged, and IDataErrorInfo.  I am sure we are all familiar with INotifyPropertyChanged so I am not going to go into detail on what needs to be done to implement that interface. 

                                      IDataErrorInfo is what is going to allow us to fire off our validation and communicate any issues to the ViewModel and UI.  First we are going to create a Validate function that will accept a string parameter that represents the property name.  The function will verity that the passed in property name is valid and that a property with said name exists on the domain entity.  If the property exists, its value is retrieved.  The property is then interrogated for attributes of type ValidatorBase.  If/When one is found the validation logic is performed on that property.  A the validation of the property returns something other than null that means the property is invalid and a string containing details of the validation issue is returned.  If no validation issue is found on the current attribute then the next attribute is checked and the process continues until we are out of attributes or a validation issue is found.

                                        1: public string Validate(string propertyName) {
                                        2:     string result = null;
                                        3:     PropertyInfo prop = GetType().GetProperty(propertyName);
                                        4:     if (prop != null && !prop.Name.Equals("item", StringComparison.InvariantCultureIgnoreCase)) {
                                        5:         object value = prop.GetValue(this, null);
                                        6:         var attributes = (ValidatorBase[])prop.GetCustomAttributes(typeof(ValidatorBase), false);
                                        7:         foreach (ValidatorBase attribute in attributes) {
                                        8:             result = attribute.Validate(value);
                                        9:             if (result != null)
                                       10:                 return result;
                                       11:             }
                                       12:             return result;
                                       13:         }
                                       14:         return result;
                                       15:     }
                                       16: }

                                      Next we will implement the contract for IDataErrorInfo.  This contract requires us to implement two properties, even know WPF only uses one of them.  The Item property is an enumerator for the collection of strings representing errors.  In the getter of this property we will return the results of calling our Validate function with the supplied property name.  This will later be hooked up in a round about way to the View via the ViewModel.

                                        1: public string this[string propertyName] {
                                        2:     get { return Validate(propertyName); }
                                        3: }
                                        5: //Note: WPF does not use this function.
                                        6: public string Error {
                                        7:     get { return null; }
                                        8: }

                                      This completes the plumbing for our validation framework.  There are an abundant number of blogs post on how to consume the IDataErrorInfo details in your views.  Beth Massi has done an excellent one which you can find here.

                                      So, in wrapping up I feel like I have completed a validation framework that satisfies my goals.  Hopefully you will find it adaptable to your situation.

                                      * Download Complete Source Code

                                      posted on Thursday, July 29, 2010 11:00:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [17]
                                      # Monday, July 26, 2010

                                      My current client is looking to combine a series of line of business Access (YIKES) and Win Forms apps into a composite WPF MVVM solution.  I was also brought in to architect one of the heavy hitter apps that will be a part of the new composite application.  In the initial discussion concerning creating a composite application, one of the client’s developers presented a proof of concept composite application using Microsoft’s Prism. I voiced my concern about the amount of code said solution would be required to handle and recommended going with a multi-solution composite rather than a multi-project composite.

                                      I started researching multi-solution composite applications on the inter-webs and found very little, virtually no, useful material…and this worried me.  I couldn’t be the first guy to think the multi-solution approach would be preferred for a composite application that will, when all is said and done, contain hundreds of thousands of lines of code.  Not wanting to lead my client in the direction of the proverbial unicorn I decided to put together a little proof of concept of my own.

                                      This code is a Proof Of Concept and was developed as such.  The overall functionality of the application is trivial.  It is UI centric and does not contain a true data access layer and it does not contain any unit tests.  I know this is horrible but please understand. :)

                                      The typical WPF composite application is broken down into three major sections.

                                      1. Infrastructure (VS Project)
                                        • Commands
                                        • Events
                                        • Domain Entities
                                        • Interfaces
                                      2. Shell (VS Project)
                                        • WPF Window that will act as the *shell* of your composite application
                                        • Bootstrapper (we will discuss this later)
                                      3. Modules (1 or more VS Projects)
                                        • WPF user controls that make up the functionality of your application
                                        • Modules should be as self contained as possible with minimal references to Infrastructure
                                        • Each module will contain
                                          • View
                                          • View Model
                                          • Controller (optional)

                                      The structure for a multi-solution composite application is similar but is broken out into solutions instead of projects, surprise!


                                      The code is really straightforward.  There a couple of requirements though:

                                      1. Prism
                                      2. Unity

                                      I included some UI enhancements, including implementing the Avalon Dock controls for docking windows.

                                      Download Here!!!!!!

                                      posted on Monday, July 26, 2010 10:49:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [6]
                                      # Friday, May 29, 2009

                                      I have a few issues with the standard ASP.NET MVC view engine.  First off it is too verbose…you have type too much and in my opinion the views don’t look like html.  Luckily there are alternatives.  One of the most popular ASP.NET MVC view engine replacements is Spark.  Spark is replacement view engine that allows you to type less and makes your Views much easier to read.  So for part 3 of NerdDinnerAdvanced I am replacing the built in ASP.NET MVC view engine with Spark.

                                      Replacing the view engine in the NerdDinnerAdvanced project was very straight forward.  Here are the steps.

                                        1. Reference Spark.dll and Spark.Web.MVC.dll in NerdDinnerAdvanced.UI
                                        2. Register Spark as a view engine in Global.asax Application_Start
                                          /// <summary>
                                          /// Application Start
                                          /// </summary>
                                          protected void Application_Start() {
                                              //Wire Up Spark as our ViewEngine (Step 1)
                                              //Initialize IoC
                                              //Wire up controller factory
                                              ControllerBuilder.Current.SetControllerFactory(new IoCControllerFactory());
                                        3. Add a declaration for the Spark configuration section to the Web.config
                                          <!-- Spark Config Section Declaration (Step 2) -->
                                          <section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
                                        4. Add Spark configuration to the Web.config
                                          <!-- Spark Configuration Section -->
                                              <compilation debug="true">
                                                  <add assembly="NerdDinnerAdvanced.UI"/>
                                                  <add assembly="System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                                                  <add namespace="System.Collections.Generic"/>
                                                  <add namespace="System.Linq"/>
                                                  <add namespace="System.Web.Mvc"/>
                                                  <add namespace="System.Web.Mvc.Html"/>
                                                  <add namespace="System.Web.Mvc.Ajax"/>
                                                  <add namespace="NerdDinnerAdvanced.Domain.Models" />
                                              <use content="MainContent" />
                                        5. Create Spark master page

                                          How master pages are implemented in Spark is very cool.  I am not going to go into details all the ways you can implement master pages in Spark, but you can check it out here.  I am going to use the default behavior in which Spark will look for a file name Application.spark in either the Views/Layout or Views/Shared folders and will apply that to all the views in project.  So I no longer have to explicitly tell my view what master to use. So to setup our master page we need to;

                                          1. Add a new class file under Views –> Shared and name it Application.spark.
                                          2. Copy all the code from Site.master into Application.spark
                                          3. Remove the Page directive
                                          4. Remove the title content place holder
                                          5. Replace the main content place holder with Spark content div
                                            <div id="content">
                                          6. Replace all '<%= xxx %>' with '${ xxx }'
                                          7. You should end up with…
                                            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                                            <html xmlns="http://www.w3.org/1999/xhtml">
                                            <head runat="server">
                                                <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
                                                <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
                                                <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>    
                                                <script src="/Scripts/jQuery-1.3.2.js" type="text/javascript"></script>
                                                <div class="page">
                                                    <div id="header">
                                                        <div id="title">
                                                            <h1>Nerd Dinner For The Real World</h1>
                                                        <div id="logindisplay">
                                                            <% Html.RenderPartial("LogOnUserControl"); %>
                                                        <div id="menucontainer">
                                                            <ul id="menu">              
                                                                <li>${ Html.ActionLink("Find Dinner", "Index", "Dinners")}</li>
                                                                <li>${ Html.ActionLink("Host Dinner", "Create", "Dinners")}</li>
                                                                <li>${ Html.ActionLink("About","About","Home") }</li>
                                                    <div id="main">
                                                        <div id="content">
                                                            <use content="MainContent" />
                                                        <div id="footer">
                                        6. Convert our first page.  Home/Index.aspx
                                          1. Rename Index.aspx to Index.spark
                                          2. Remove Page directive
                                          3. Remove Title content
                                          4. Replace ASP main content tag with Spark main content tag
                                          5. Replace all '<%= xxx %>' with '${ xxx }'
                                        7. Now we ran it!  What to notice here is first of all it runs.  The second thing to notice is the really cool part.  We are seeing a view created using the Spark View Engine but we are displaying a partial view created using the standard ASP.NET MVC View Engine.  The Log In/Out user control is still being rendered by the default view engine.
                                        8. Now we are ready to convert the remaining pages.  One difference from the built in view engine is how you tell the view about the model.  You need to explicitly specify what model the view uses.
                                          <viewdata model="NerdDinnerAdvanced.UI.Utility.PaginatedCollection<NerdDinnerAdvanced.Domain.Models.Dinner>"/>

                                      The complete code can be downloaded here.  Stay tuned for part 4.

                                      posted on Friday, May 29, 2009 11:05:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [7]
                                      # Wednesday, May 27, 2009

                                      In part 2 of the NerdDinnerAdvanced code I replaced the LinqToSql DAL with a DAL that uses NHibernate.  NHibernate is an open sourced object relational mapper.  If you are not familiar with ORM and/or NHibernate I highly suggest you check them out.  Because of the way we architected our project in Part 1 implementing an NHibernate DAL had little to no impact on any code above the DAL.

                                      To start I re-structured the project a little.  I created a NerdDinnerAdvanced.Data.LinqToSql project and moved the LinqToSql DinnerRepository and the NerdDinner.dbml file into the new project.  This left just the IDinnerRepository in the NerdDinnerAdvanced.Data project.  You could certainly move the IDinnerRepository class to the NerdDinnerAdvanced.Common project and remove the NerdDinnerAdvanced.Data project if you wish.


                                      Now it was time to create my NHibernate mappings.  If you are not familiar with how ORM’s work the basic concept is that the ORM framework maps data from a database to your entity/domain objects In order to accomplish this you need to tell the ORM what tables/columns map to what objects/fields and this is typically done via an XML file.  In this case we only have 2 objects to map, Dinner and Rsvp, so the mapping would not be complex.  Often, though, you are dealing with hundreds of objects with a lot of fields and the management of the XML mapping files can get very difficult.  For this reason, and because I wanted to have a chance to play with it, I decided to use Fluent NHibernate to do my mapping.  Fluent NHibernate allows you to do your mappings using strongly typed C# code.

                                      In my NerdDinnerAdvanced.Domain project I created a new folder called Mappings and added two mapping classes, one for each of my two domain objects.



                                      Because this is not a Fluent NHibernate tutorial I am not going to go into detail on how you create the mappings…and for the most part it is fairly intuitive.

                                       /// <summary>
                                       /// Fluent NHibernate mapping for the Dinner class
                                       /// </summary>
                                       public class DinnerMap : ClassMap<Dinner> {
                                           public DinnerMap() {
                                               SetAttribute("lazy", "false");
                                               Id(x => x.DinnerId);
                                               Map(x => x.Title);
                                               Map(x => x.Description);
                                               Map(x => x.EventDate);
                                               Map(x => x.HostedBy);
                                               Map(x => x.Address);
                                               Map(x => x.Country);
                                               Map(x => x.ContactPhone);
                                               Map(x => x.Latitude);
                                               Map(x => x.Longitude);
                                               HasMany(x => x.Rsvps).Inverse().KeyColumnNames.Add("DinnerId").Cascade.All().SetAttribute("lazy", "false");

                                      Next it was time to create the NHibernate DAL so I added a NerdDinnerAdvanced.Data.NHibernate project to the solution.  The first thing you have to do when using NHibernate, after creating your mapping files, is create your NHibernate Session class.  Session to NHibernate is like DataContext to Linq.   The Session for the most part contains connection string and mapping info and it is the mediator between you and your data.

                                          /// <summary>
                                          /// NHibernate session factory
                                          /// </summary>
                                          public class SessionFactory {
                                              public static ISessionFactory CreateSessionFactory() {
                                                  return Fluently.Configure()
                                                      .Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.Is("Data Source=keith-166938fd4;Initial Catalog=NerdDinner;Integrated Security=True")))  
                                                      .Mappings(m =>  m.FluentMappings.AddFromAssemblyOf<Dinner>())  

                                      After creating the NHibernate Session class I can now implement my DinnerRepository using NHibernate.  Below is an example of the FindAllDinners method.

                                              /// <summary>
                                      /// Returns a list of all dinners
                                      /// </summary>
                                      /// <returns>List of all dinners</returns>
                                      public IQueryable<Dinner> FindAllDinners() {
                                      var sessionFactory = SessionFactory.CreateSessionFactory();
                                      using (var session = sessionFactory.OpenSession()) {
                                      using (session.BeginTransaction()) {
                                      return session.CreateCriteria(typeof(Dinner)).List<Dinner>().AsQueryable();

                                      After completing the DinnerRepository we can tell our application to use the the new DAL by changing one line in our InversionOfControlHelper class.

                                              /// <summary>
                                              /// Initializes the inversion of control mappings
                                              /// </summary>
                                              public static void Initialize() {
                                      //Tell Structure Map we are using Fluent mapping rather than onfiguration file based mapping! StructureMapConfiguration.UseDefaultStructureMapConfigFile = false;
                                      //This is the only line of code outside of the DAL that needed to be modified to implement the NHibernate data access layer! //StructureMapConfiguration.BuildInstancesOf<IDinnerRepository>().TheDefaultIsConcreteType<Data.LinqToSql.DinnerRepository>();

                                      Once again the complete source can be downloaded here.  Stay tuned for Part 3!

                                      posted on Wednesday, May 27, 2009 8:52:17 AM (Central Daylight Time, UTC-05:00)  #    Comments [13]
                                      # Saturday, May 16, 2009

                                      The first chapter of Professional ASP.NET MVC 1.0 walks you through creating the basic NerdDinner site.  This is a great introduction to ASP.NET MVC but really isn’t something you could as reference for creating a real world ASP.MVC site.  With this in mind I set out on a multi part project to create a real world ASP.NET reference application based on the base NerdDinner code.

                                      It the first installation of what I am calling NerdDinnerAdvanced I extended the base NerdDinner code in the following ways;

                                        • Created 3-tier architecture.  One of the major misconceptions about ASP.NET MVC is that it is a UI framework.  I think this is mainly due to the fact that the major changes that developers need to wrap their head around are in the UI.  To help alleviate this misconception I structured the MVC project architecturally that developers who have experience in n-tier architecture will find familiar.
                                           The layers, as you can see highlighted above, are UI, Business, and Data.  Because of the overall simplistic nature of the underlying code I did not include a Service layer.  The other projects are shared by the layers.  The Domain project contains my models and the Common project contains common utility classes.


                                        • The base NerdDinner code used LINQ to SQL and was content with passing the LINQ to SQL entities between the layers of the application.  I would guess that Mr. Gu did this for simplicity and brevity and not a show of best practice.  If you are asking yourself what is wrong with architecting around LINQ to SQL entities I would recommend picking up Dino Esposito’s latest book.  The main reason is that you are tightly coupling yourself to the database.  So in my Domain project I created a Models namespace and created Dinner, Rsvp, and DinnerFormView domain objects.


                                        •   Implemented Inversion Of Control/Dependency Injection using Structure Map.  The base NerdDinner code used manual IoC/Di in the DinnersController but I decided to take that a step further because I am on a bit of an Ioc/Di fix lately.  I implemented it on the repository and the dinner services business object as well as the Dinner and Rsvp controllers.


                                        • Implemented a full suite of unit testing using MOQ for mocking objects.

                                      The code can be downloaded here.  Stay tuned for the next installment which will include nHibernate as the DAL.

                                      posted on Saturday, May 16, 2009 4:10:32 PM (Central Daylight Time, UTC-05:00)  #    Comments [6]
                                      # Wednesday, May 13, 2009

                                      I recently finished reading the first chapter of ASP.NET MVC 1.0, which deals strictly with the Nerd Dinner site that 3 of the 4 authors of the book put together.  This book has been a delight to read to this point and I highly recommend it.  In reading the first chapter I wrote  the code along with the book.  I wanted to make the code a source of reference for me in the future so while I was coding I added comments detailing points of interest from the book.  Along the way I thought making it available to the masses might be a good idea.  Since I wasn't sure on the legal ramifications of putting exact text from a book into my code comments I contacted one of the authors.  I received an email from said author a day later and he stated, and I quote “I say blog first, ask permission later.”  So that is exactly what I am doing.  You can download the full source here. Below is a sample...

                                              /// <summary>
                                              /// Attempts to perform an edit on the Dinner with the provided id using the provided formValues
                                              /// URL     :   /Dinners/Edit/[id]
                                              /// Verb    :   Post
                                              /// Purpose :   Save the form changes for a particular Dinner to the database
                                              /// </summary>
                                              /// <param name="id">Id of dinner to edit</param>
                                              /// <param name="formValues">Incoming form parameters</param>
                                              /// <returns>Details for view for the dinner that was edited</returns>
                                              /// <remarks>
                                              /// The "AcceptVerbs" attribute indicates it handles HTTP Post scenarios.
                                              /// When the attribute is applied to overloaded action methods ASP.NET MVC
                                              /// automatically handles dispatching to the appropriate action method depending
                                              /// on the incoming HTTP verb.
                                              /// For details on why MVC differentiates via HTTP verbs and doesn't use the 
                                              /// multiple URL approach see page 64.
                                              /// </remarks>
                                              public ActionResult Edit(int id, FormCollection formValues) {
                                                  //Call method on our DinnerRepository to get the Dinner being edited
                                                  var dinner = _dinnerRepository.GetDinner(id);
                                                  //Verify that a dinner was found
                                                  if (dinner == null)
                                                      return View("NotFound");
                                                  //Verify that the logged-in user matches the dinner host
                                                  if (!dinner.IsHostedBy(User.Identity.Name))
                                                      return View("InvalidOwner");
                                                  //The "try" block will catch errors in calling UpdateModel or when we
                                                  //try and save the DinnerRepository, which will throw if the Dinner object
                                                  //we are tyring to save is invalid because of a rule violation.
                                                  try {
                                                      //The "UpdateModel" helper method on the Controller base class supports updating
                                                      //the properties of the object being passed to it using the incoming form parameters.
                                                      //It uses reflection to determine the property names on the object, and then automatically
                                                      //converts and assigns values to them based on the input values submitted by the client.
                                                      //The method will automatically update the "ModelState" collection when it encounters errors
                                                      //while trying to assign form values to properties on the model object.  For example putting 
                                                      //something other than a DateTime in the EventDate field.
                                                      //Persist the changes
                                                      //Return the Details view for the dinner being edited
                                                      return RedirectToAction("Details", new{id = dinner.DinnerId});
                                                  catch {
                                                      //Handle edit errors
                                                      //****** The code below was refactored to an extension method in the class ControllerHelpers
                                                      ////Loop through the rule violations and add to ModelState
                                                      //foreach (var issue in dinner.GetRuleViolations()){
                                                      //    //The "ModelState" property collection provides a way to indicate that
                                                      //    //errors exist with a model object being passed to a view.  Error entries
                                                      //    //within the the "ModelState" collection identify the name of the model 
                                                      //    //property with the issue and allow a human-friendly error message to be specified.
                                                      //    //HTML helper methods like "HTML.TextBox" check the "ModelState" collection to see 
                                                      //    //if there were any errors associated with the property on the model object the control
                                                      //    //is associated with.  If it determines that there was an error it renders the submitted user
                                                      //    //input as the value and adds a CSS error class to the markup it generates.
                                                      //    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                                                      //Example below uses ViewData...which is not strongly-typed
                                                      //Add the SelectList to ViewData so the Countries drop down list is populated when rendered
                                                      //ViewData["countries"] = new SelectList(PhoneValidator.Countries, dinner.Country);
                                                      //Example using ViewModel which is strongly-typed
                                                      return View(new DinnerFormViewModel(dinner));
                                                      //Return the Dinner view
                                                      //return View(dinner);

                                      posted on Wednesday, May 13, 2009 5:17:26 PM (Central Daylight Time, UTC-05:00)  #    Comments [6]
                                      # Sunday, April 26, 2009

                                      I figured I was to the point where I was comfortable enough with the concept of mocking that I would start implementing it in one of the projects I am working on at my current client.  The data access layer of the application obtains data from two sources; a CIS system that is only reachable via web services and a data warehouse on a SQL Server that we are accessing directly using stored procedures and LINQ to SQL.  I started with mocking the web service piece and that went off without a hitch. 

                                      The Linq To SQL piece did not go as smoothly.  I had a few issues creating the Interface for the DataContext and then ran into trying to mock System.Data.Linq.Table which is Sealed.  Instead of copying and pasting the code in the post and explaining it I think that I will let the code speak for itself.  If you are like me you find it much easier to understand complex code in the solution structure offered by Visual Studio.  So grab the code from here and dive in.

                                      posted on Sunday, April 26, 2009 7:26:34 PM (Central Daylight Time, UTC-05:00)  #    Comments [6]
                                      # Sunday, April 19, 2009
                                      There are a few assertions, other than Exception assertion, that are missing from MsTest.  Some of these I missed enough to roll my own are GreaterThan, GreaterThanOrEqualTo, LessThan, and LessThanOrEqualTo.  Check the code out to see how I accomplished this.

                                      posted on Sunday, April 19, 2009 5:30:22 PM (Central Daylight Time, UTC-05:00)  #    Comments [2]
                                      # Friday, April 03, 2009

                                      Although the built in unit testing is nice, for us user’s of ReSharper it is something we have had for awhile with their NUnit integration, it is missing some things from NUnit that I have come to love, one of which is the ability to test expected exceptions.  MSTest does supply the ExpectedException attribute which does allow you to test for a single exception, helpful if all methods you code only throw a single exception each.  If your methods are more complicated you have to write a test for each of the exceptions you expect to encounter.

                                              /// <summary>
                                              ///A test for ATestMethod
                                              [AspNetDevelopmentServerHost("%PathToWebRoot%\\Learning\\CustomAssertions\\CustomAssertions\\CustomAssertions", "/")]
                                              public void ATestMethodTest()
                                                  string s = "Test";
                                                  int actual = MethodsForTesting.ATestMethod(s);
                                                  //This is a valid, simple but still valid, test of the pass condition.
                                                  Assert.AreEqual(1, actual);
                                                  //What if I want to test the part of my code that throws exceptions?
                                                  //The only built in solution that MsTest offers is using the "ExpectedException" attribute.
                                                  actual = MethodsForTesting.ATestMethod(null);
                                                  //Because you can only have one per method it leaves a little something to be desired
                                                  //If I want to test more than one expected exception I need to have a test for each ExpectedException after the first
                                              /// <summary>
                                              ///Another test for ATestMethod
                                              [AspNetDevelopmentServerHost("%PathToWebRoot%\\Learning\\CustomAssertions\\CustomAssertions\\CustomAssertions", "/")]
                                              public void ATestMethodTest2()
                                                  //So this is the test of my second ExpectedException.
                                                  //If you are writing one unit test per method plus one for each expected exception
                                                  //your test suite is going to get of of control before you know it.
                                                  string s = "This is a long string";
                                                  int actual = MethodsForTesting.ATestMethod(s);
                                      Because creating a unit test for every exception I needed to catch is not something I wanted to do, not to mention that in my opinion using attributes doesn’t lend itself to easily read code, I decided to look into re-creating the functionality.  Using generics and delegates I was able to accomplish this without too much of a headache, other than the fact that my current contracting gig has me coding in VB and for some reason when I am coding in VB I occasionally mix in some C# and when I am coding in C# I mix in some VB…shouldn’t the IDE be smart enough to make the conversion for you?  So I can now test for expected exceptions until I am blue in the face.  Here is the above code rewritten using the AssertException class.

                                              /// <summary>
                                      ///A test for ATestMethod
                                      [AspNetDevelopmentServerHost("%PathToWebRoot%\\Learning\\CustomAssertions\\CustomAssertions\\CustomAssertions", "/")]
                                      public void ATestMethodTestWithCustomAssertException()
                                      int actual = MethodsForTesting.ATestMethod("Testing");
                                      //This is a valid, simple but still valid, test of the pass condition.
                                      Assert.AreEqual(1, actual);
                                      //Test of the null argument logic
                                      AssertException.Throws<ArgumentNullException>(() => MethodsForTesting.ATestMethod(null));
                                      //Test of the string is too long logic
                                      AssertException.Throws<InvalidOperationException>(() => MethodsForTesting.ATestMethod("A really looooooooooooooooooooooong string."));

                                      The Throws method has an override that includes the expected error message as well.  I also coded a ThrowsSoapException custom assertion that allows you to look for a specific exception message as well as a specific soap fault code.  You can download the rest of the code, including unit tests of course, here.

                                      posted on Friday, April 03, 2009 5:51:59 PM (Central Standard Time, UTC-06:00)  #    Comments [9]