Leaving Calgary (for a while at least)

On June 19th, I announced to the Calgary .NET User Group that I am stepping down as President of the group because I am leaving the city. I have served on the executive team for over 5 years: 2 years as Speaker Coordinator and over 3 years as President. While leading the group has been challenging and time consuming, I do not in any way regret taking on the role. The experience has allowed me to meet great people from all over North America and has definitely helped me to keep my .NET skills as current as possible.

I want to extend a thank you to all the Calgary .NET User Group members for helping make our group so successful over the last 5 years. The group is 10 years old now and still going strong. The number of talented software developers in Calgary is astounding, and I think the most talented developers are members of the .NET community (although I may be biased).

I also want to thank everyone who has served on the executive with me over the last 5 years. It truly has been a pleasure. Also, best of luck to the future executive members.

Why am I leaving such a great city?

I like Calgary…I really do. There are so many great opportunities for software developers in this city (and contrary to popular belief, those opportunities extend beyond Oil & Gas). Calgary is also very close to the Rocky Mountains, which offers a huge variety of recreational options.


©MarilynJane

However, there are two things that I don’t particularly enjoy about Calgary: winter and traffic. Winter in Calgary is just plain gross. I actually really like winter, but what Calgary gets every year does not count as winter. It’s more like 6 months of dirty melting mess. Traffic is also pretty bad, which can make the daily commute painful. The combination of winter and traffic is aggravating.

Where am I going?

Every winter, my wife and I escape to the Caribbean for at least 1 week. A couple years ago, we started investigating the possibility of reversing our approach. What if we could find a place in the Caribbean where I could live and work year round? After doing some research, we settled on the Cayman Islands. This seemed to offer the best standard of living and opportunity to find work in my field.

As it turns out, we were a little overly optimistic about the job search. Finding a .NET Developer job in the Cayman Islands is not easy, but I finally accepted an offer after nearly 2 years of searching. To say I am excited is a huge understatement (my new office is located across the street from the beach in the picture below), but I am also realistic. I am sure that I will be facing all sorts of unforeseen challenges. The 2 things that scare me the most right now: hurricanes and slow internet.


©Salvatore.Freni

Stay tuned to hear more about my experiences coding on the island.

Entity Framework Presentations at Prairie Dev Con

Thanks to everyone who attended my Entity Framework presentations at Prairie Dev Con in Winnipeg.

Here are a few links to the sessions materials and some blog posts that explore some of the examples from the presentations:

Writing Efficient Queries with Entity Framework

Part 1  - Eager Loading

Part 2 – LINQ Projections

Part 3 – Paging

DbContext Lifetime

Managing your DbContext Lifetime in ASP.NET MVC4

Source code for Social Recipes

Get it on GitHub

Slides

Entity Framework Code First – Download

Code First Migrations – Download

Re-enabling Migrations? Use the Force, Richard

Whenever I do a presentation on Entity Framework Code First Migrations, I always take a moment to point out the helpful error messages provided by Entity Framework. In an industry plagued by nasty error codes and incomprehensible error messages, EF really stands out. It shows that the team took the time to provide helpful error messages. When something goes wrong in EF, the error message typically tell you what the problem was and what you can do to fix the problem. This isn’t always the case in EF, but they definitely have the most common errors covered off.

Here is an example of one of my favourite error messages from EF Code First:

The model backing the ‘xxContext’ context has changed since the database was created. Consider using Code First Migrations to update the database ( http://go.microsoft.com/fwlink/?LinkId=238269).

This message is perfect in so many ways. It tells me exactly what went wrong and provides the solution to the problem, complete with a link to a blog post with detailed instructions.

While Richard Reukema was presenting his SQL session at Windows Azure Boot Camp in Calgary yesterday, I found a new favourite EF error message:

Migrations have already been enabled in project ‘xx’. To overwrite the existing migrations configuration, use the -Force parameter.

Again, a well crafted error message explaining the problem and providing a solution. I fully endorse solution that involves “using the force”.  Well done EF team…well done.  (unless they mean use the negative force, in which case I revoke my endorsement)

Managing Entity Framework DbContext Lifetime in ASP.NET MVC

Managing the lifetime of a DbContext instance in your application is extremely important. A DbContext makes use of important resources like database connections that need to be released. If you do not properly dispose of a DbContext instance, the underlying database connections might never be released back to the connection pool. Anyone who has done any old school ADO.NET programming knows the madness that lies down that path.

In an ASP.NET MVC application, the DbContext instances are typically used inside a controller. For some background, controllers in MVC are created when as a web request comes in and they are disposed of when that request is completed. In ASP.NET MVC controllers, how can we ensure that our DbContext instance is disposed? (Spoiler Alert: You should use option 3)

Option 1) The Using Pattern

One option is to use the using pattern:

using (EmployeeContext context = new EmployeeContext())
{
return View(context.Employees.ToList());
}

The using pattern ensures that the EmployeeContext is disposed of at the end of the using block. It is basically shorthand for a try{… } finally{…} block where the context is disposed of in the finally. This pattern will ensure that the context is disposed, but it makes it difficult to share a context instance in different points of the application. You may find yourself creating more DbContext instances than you intended. It also adds some noise to your controller logic. While it is much cleaner than a try finally, it does still add noise.

Option 2) The Dispose Pattern

Another option is to implement the dispose pattern in your controller:

public class EmployeeController : Controller
{
private EmployeeContext _context;

public EmployeeController()
{

_context = new EmployeeContext();
}

public ActionResult Index()
{

return View(_context.Employees.ToList());
}

protected override void Dispose(bool disposing)
{

if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
}

Again, this pattern ensures that the EmployeeCotenxt is disposed of when the controller is disposed of at the end of the request. Much like the using pattern, this option adds noise to your controller and it makes it difficult to share an instance of a context with different points in your application. It also relies on all developers on the team to properly implement the dispose pattern (one of the most misused patterns in the .NET world).

Option 3) Dependency Injection

This is the option that I choose. It is the cleanest possible option and it relieves the controller any responsibility for the lifetime of the DbContext instance. When you think about it, the controller requires an instance of a DbContext, but it really shouldn’t care about where it comes from or where it goes when it is done with it.

Start by adding a constructor that requires an instance of the DbContext.

public class EmployeeController : Controller
{
private EmployeeContext _context;

public EmployeeController(EmployeeContext context)
{

_context = context;
}

public ActionResult Index()
{

return View(context.Employees.ToList());
}
}

Since this is the only constructor, we know that the EmployeeController cannot be created without an instance of an EmployeeContext. It is no longer the responsibility of the controller to create the DbContext, which means it is no longer responsible for disposing of it either. Notice how simple the controller is now?

But wait! If the controller isn’t creating the context, then who is? This is an MVC application, who is creating the controllers? How can I be sure that the context is actually being disposed?

IoC Container to the Rescue!

Luckily,there are a number of dependency injection / IoC containers that have hooks in to MVC to help us with this. My favorites is NInject, but I have also had good luck with Autofac and others.

To get started with NInject, simply install the NInject.MVC3 nuget package.

Install-Package Ninject.MVC3

The nuget package will add a NInjectWebCommon.cs file to your application’s App_Start folder:

The important line in this file is the line that registers the OnePerRequestHttpModule:

DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));

You also need to add the following line to the CreateKernel method in NInjectWebCommon.cs

kernel.Bind<EmployeeContext>().ToSelf().InRequestScope();

With this configuration, NInject will recognize that your controller requires an instance of an EmployeeContext and do the following for you:

  • Create an instance of the EmployeeContext
  • Pass the instance in to the EmployeeController constructor
  • Dispose of the EmployeeContext at the end of the Http Request

Because we are using OnePerRequestHttpModule, the default behaviour is to create a new instance of the EmployeeContext for each Http request. That means different requests will never share an instance of a context. It will also ensure that no more than one EmployeeContext is created, even if the request ends up hitting 3 controllers that all require an EmployeeContext. In other words, the lifetime of the context is tied to the life of the request. This is a good thing and is definitely the recommended approach for Entity Framework. Use it!

Update 1: Updated to add the very important NInject configuration that ensures instances of the EmployeeContext are actually disposed properly. Thank you to my friend Robson (@TowTweets) for pointing this out!

Extending AngelaSmith’s Fluent API

AngelaSmith is a package that can intelligently fill objects with random data (See Go Beyond Lorem Ipsum). In my last post, we saw how to extend AngelaSmith by implementing custom property fillers. In this post, we will see how to extend the fluent API.

The Fluent API

Just a quick over of AngelaSmith’s fluent API. The API allows you to tell AngelaSmith more information about how to fill a specific property of an object. For example, if you had a property named EmailAddress that you wanted filled with email addresses from a particular domain, you could configure AngelaSmith using the AsEmailAddressFromDomain method:

var person = Angie.Configure<Person>()
.Fill(p=> p.EmailAddress)
.AsEmailAddressForDomain(domain)
.Make<Person>();

Extending the API

Writing your own extension methods for the API is fairly straight forward. Here is the code for the AsEmailAddressForDomain method.

public static AngieConfigurator<T> AsEmailAddressForDomain<T>(this AngieStringConfigurator<T> configurator, string domain) where T : new()
{
    CustomFiller<string> filler = new CustomFiller<string>(configurator.PropertyInfo.Name, typeof(T), () => Jen.Email(domain));
    configurator.Maggie.RegisterFiller(filler);
    return configurator;
}

Since this method is intended for String properties only, this extension method is for the AngieStringConfigurator<T> class. Other options include AngieIntegerConfigurator<T>, AngieShortConfigurator<T>, AngieDateTimeConfigurator<T>, and AngieDecimalConfigurator<T>.

 

The method simply registers a custom filler for the specified property (that’s the property that was specified using the Fill method of the fluent API), and returns the configurator that was passed in. Now, AngelaSmith will use this custom filler for the specified property on type T instead of using the default built in property filler.

 

Notice that the return type is AngieConfigurator<T> instead of AngieStringConfigurator<T>. This is important because it ensures that we do not chain 2 String methods together. If we chained 2 String methods together, the second method call would always overwrite the previous method call.

What’s next?

You can find AngelaSmith on GitHub and on Nuget. Give it a try and let us know what type of extension methods you write. Feel free to submit a pull request on GitHub. We are happy to accept contributions from the community.

Install-Package AngelaSmith

Extending AngelaSmith with Custom Property Fillers

AngelaSmith is a package that can intelligently fill objects with random data (See Go Beyond Lorem Ipsum).

Under the hood, it does this by inspecting the properties on your object.  For each property, it looks for a PropertyFiller that matches based on the name of the class, the type of the property and the name of the property. Once a matching property filler is found, AngelaSmith asks for a value from the property filler and uses that value to fill the property.

AngelaSmith has a number of built in property fillers, but as Simon Timms pointed out: It would be nice if we could extend AngelaSmith by plugging in our own custom property fillers. For example, if you are working in the oil industry, you could create a set of fillers to deal with Wells, Rigs, Production, etc.

I want tasty ingredients…not that gross stuff!

Let’s take a simple example. Assume we are working on a domain that contains Recipes. A Recipe has a list of Ingredients, and we would like to fill the Ingredient’s Name with realistic looking data. By default, AngelaSmith doesn’t know anything about ingredients so it will use random text. I don’t want to bake a bicycle, a parachute and a pair of shoes. That sounds disgusting.

public class RecipeIngredient
{
public string Name { get; set; }
}

To create a custom property filler, create a class that inherits from PropertyFiller<T> where T is the type of the property you will be filling. You will need to do 2 things.

1) Call the base constructor, passing in these 2 parameters:

•    objectTypeNames – A list of names matching the class name of objects this filler is targeting

•    propertyNames -  A list of names matching the property name of the property this filler is targeting

2) Implemented the GetValue() method, which should return a value that will be used to fill a property

public class IngredientPropertyFiller : PropertyFiller<string>
{
    public IngredientPropertyFiller()
        : base(new[] { "recipeingredient", "ingredient" }, new[] { "name" })
    {
    }

    private static readonly string[] IngredientsList = new[]
        {
            "Salt", "Pepper", "Olive Oil", "Basil", "Chicken Broth", "Cloves", "Garlic", "Onion", "Eggs",
            "Tomatoes", "Chicken Thighs", "Chicken Breast", "Pork Ribs", "Mozzarella Cheese", "Parmesan Cheese",
            "Butter", "Nutmeg",
            "Fettuccine", "Parsley", "Orange Zest", "Whipping Cream", "Cranberries", "Tomatoe Paste", "Mushrooms",
            "Cambozola Cheese",
            "Green Onions", "Flour", "Bran", "Green Beans", "Lima Beans", "Vinegar", "Mustard", "Water", "Raisins",
            "Corn", "Tabasco", "Cashews", "Celery", "Ground Beef", "Rib Steak", "Asparagus", "Cooking Oil",
            "Soy Sauce",
            "Ketchup", "Round Roast", "Beef Tenderloin", "Pork Tenderloin", "Pork Ribs"
        };

    public override object GetValue()
    {
        return Jen.GetRandomValue(IngredientsList);
    }
}

Now just call use AngelaSmith like you normally would and magically, your ingredients are now filled with actual ingredients….yum!

List<RecipeIngredient> ingredients = Angie.FastList<RecipeIngredient>(100);
foreach (RecipeIngredient ingredient in ingredients)
{
    Console.WriteLine(ingredient.Name);
}

In case you are curious, we implemented this using MEF to discover implementations of IPropertyFiller in the current app domain directory.

What Next?

You can find AngelaSmith on GitHub and Nuget. Let us know what you think, and try building your own fillers. We are actively adding more fillers and we would be happy to include yours!