EF Code First DB Initialization Using Web.Config

The DBContext used by Entity Framework Code First allows you to set a strategy for how your database is updated when your application starts.  While this is a huge time saver for development it is usually not something you want to allow for production.  The last thing we need is to deploy an update to production and have the application drop and recreate the production database.

The following database initialization options are available:

  • DropCreateDatabaseIfModelChanges – This strategy recreates your database only if the Entity Framework model is different from the database or the database does not exist. This is the most common strategy used while developing
  • CreateDatabaseIfNotExists (Default) - If no database is found it will be created according to your Entity Framework Model.
  • DropCreateDatabaseAlways - This strategy always drops the database and recreates it. This is helpful for integration and database test projects where a fresh database with deterministic data is created for each test.
  • Custom – Used to Implement your own strategies or add seed and test data to an existing strategy. This post shows an example of extending the strategy DropCreateDatabaseIfModelChanges and seeding the new database with test data
  • null – Disables the EF Code First Initialization process

Given the following model and context:

public class Wizard
{
	public virtual int WizardId { get; set; }
	public virtual string Name { get; set; }
	public virtual int Level { get; set; }
	public virtual ICollection<spell> Spells { get; set; }
}

public class Spell
{
	public virtual int SpellId { get; set; }
	public virtual string Name { get; set; }
	public virtual int LevelRequired { get; set; }
}

public class FantasyContext : DbContext
{
	public DbSet<wizard> Wizards { get; set; }
	public DbSet<spell> Spells { get; set; }
}

We can create a Database Initializer strategy that will drop and recreate the database seeding it with test data whenever the model changes.

public class FantasyContextInitializer
	: DropCreateDatabaseIfModelChanges<FantasyContext>
{
	protected override void Seed(FantasyContext context)
	{
		var Gandalf = new Wizard
		{
			Name = "Gandalf the White",
			Level = 100,
			Spells = new[]
			{
				new Spell { Name = "Illumination", LevelRequired = 10 },
				new Spell { Name = "Sword of Power", LevelRequired = 50 },
				new Spell { Name = "Lightning Strike", LevelRequired = 60 }
			}
		};
		var Merlin = new Wizard
		{
			Name = "Merlin",
			Level = 100,
			Spells = new[]
			{
				new Spell { Name = "Magical Kinesis", LevelRequired = 10 },
				new Spell { Name = "Blinding Light", LevelRequired = 50 },
				new Spell { Name = "Destructive Blast", LevelRequired = 60 }
			}
		};
		context.Wizards.Add(Gandalf);
		context.Wizards.Add(Merlin);
		base.Seed(context);
	}
}

The canonical example for adding this strategy to the DbContext is by adding a single line to the Global.asax Application_Start method.

protected void Application_Start()
{
	Database.SetInitializer(new FantasyContextInitializer());
	// Other startup stuff goes here
}

However, this makes it difficult to remove the initializer for release builds or to define a different strategy for Integration Tests. Fortunately, you can define the DbContext Initializers in the config file and change or remove them using XLST transformations (For an excellent primer on Web and App config file transformations see Oleg Sych’s article Here).

To use the web.config you must first remove the SetInitializer line from the Application_Start method. Then add the following section in your web.config file.

<appsettings>
	<add key="DatabaseInitializerForType Wizards.Models.FantasyContext, Wizards"
	         value="Wizards.Models.FantasyContextInitializer, Wizards" />
	<!-- Other stuff here -->
</appsettings>

The key starts with DatabaseInitializerForType and includes the fully qualified assembly name for your Context object. The value is the fully qualified assembly name for the initialization strategy object, FantasyContextInitializer in the example. The next step is to add a transformation to the

image Web.Release.config file to remove the initializer when we publish a release build. If you do not have a Web.Release.config file in your project then right click on the web.config file and choose Add Config Transformations. This will add a configuration file transformation for each build type in your solution.  For example, the default debug and release builds will result in a Web.Debug.config and Web.Release.config files added to your solution.


Adding  the following lines to your Release config file will remove the Database Initializer from the web.config

<appsettings>
    <add xdt:transform="Remove"
         xdt:locator="XPath(//add[starts-with(@key, 'DatabaseInitializerForType')])" />
</appsettings>

This transformation states: Within the appsettings section locate an add element that has a key attribute that starts with DatabaseInitializerForType and remove it.

 

Summary

XML Transformations can be a bit tricky at first to setup but, once mastered, can be a powerful tool for setting up your different environments.

 

.

ReSharper and the Method Group Refactor

While writing code similar to the following lines, ReSharper suggested the “Replace With Method Group” Refactoring for Line 2.
 
   1: var names = Directory.GetFiles(@"c:\Program Files").ToList();

   2: names.ForEach(n => Console.WriteLine(n));

The Method Group shorthand is usually found in places where you take the following code

myButton.Click += new EventHandler(myButton_Click);

and replace it with this.

myButton.Click += myButton_Click;

The C# compiler can infer the usage of the EventHandler class, giving you cleaner, less noisy code.

Letting Resharper apply the Method Group refactoring produces the following code.
   1: var names = Directory.GetFiles(@"c:\ProgramFiles").ToList();

   2: names.ForEach(Console.WriteLine);

 
I was pleasantly surprised by the results. Apparently, I don’t have to explicitly declare the intermediate lambda variable ‘n’ just so I can pass it into the WriteLine method. The compiler is smart enough to infer this for me.  Although a little confusing at first, this shorthand notation is pretty nice.  I doubt I would have realized this without ReSharpers’ refactoring suggestions, one of the many reasons I’m a R# Junkie.

Moved my Blog

Moved my blog to a new server to support the latest ASP stack.  Also took the time to upgrade the software from an old version of dasBlog to WordPress, very happy with WordPress so far. Had to write a simple redirector to redirect the old permalinks to the new WordPress links.

Please be patient as I update the formatting of previous posts.

Installing VS 2010 in XP Mode

Although installing Visual Studio 2010 B2 and 2008 on the same machine is supported, Microsoft does NOT recommend installing beta software of your development machine. Installing Visual Studio 2010 beta in a Virtual environment is highly recommended but it does, however, have some drawbacks. Fortunately, with Windows 7 there is a hybrid approach that allows you to install VS 2010 on a virtual operating system but interact with it as though it were running on your host machine.

What you need:

  1. Windows 7 Professional or higher for the host machine
  2. Windows XP Mode and Windows Virtual PC ( download here)
  3. An operating System supported by VS2010 for your Virtual environment
    • While XP Mode comes with an XP Image already setup you can use just about any MS Operating system.  I chose to use Windows 7 instead of XP
  4. Visual Studio 2010 Beta 2 can be downloaded here.

Installing Visual Studio

Once XP Mode and Virtual PC are installed the next step is to install a virtual OS to host Visual Studio 2010. You can find instructions for this here. It is very important that the user you created for your virtual machine has a password.  Integration Services cannot be enabled without a password and no error message is displayed.

“By enabling ClearText in your Virtual Machine, text in Visual Studio will look much better when viewed in XP mode.”

Next, while the virtual machine is not running go to the settings dialog

VPC Settings Image

Make sure “Automatically Publish” is checked. This will allow applications that are installed to automatically show up in your host’s start menu.   

image

Start the Virtual Machine and Enable Integration Services.  You’ll be prompted for a user name and password, use the same credentials you used to log into the virtual machine.

image

Finally, install Visual Studio 2010 B2 on the virtual machine. (this may take awhile)  After you’ve finished shut down the Virtual machine.

Setup Host Machine

Back on your Windows 7 host you will now have Visual Studio 2010 on your start menu.  In my case I called the Virtual Machine VS2010B2 so visual studio 2010 can be found at start-> Windows Virtual PC –> VS2010B2 Applications –> Microsoft Visual Studio 2010

image

Clicking on VS2010 will first start the Virtual Machine.  If you are prompted for credentials use the same administrator login and password you used to setup the VM.

image

After a few moments, Visual Studio 2010 will appear on your desktop.  Any application on your desktop that is running in a VM will have (Remote) appended to the title in the task bar. 

image

The integration is so complete even the ASP.NET Development Server and Internet Explorer bleed through to your desktop.

thumbnailCA5S9XXL

TFS Basic Version

  tfs

Team Foundation Server 2010 Beta 2 has a new Basic version targeted for smaller shops.  According to Brian Harry’s Blog, this new version will be “as cost effective” as SourceSafe.   Not sure what “as cost effective” means but lacking any specifics I think it’s safe to assume that it will be much cheaper.  TFS Basic version is targeted for small shops but includes a large number of features. So what does it give you and, more importantly, what does it lack.

 

 

PRO’s

  1. Can use SQL Express or an existing SQL Server Instance
  2. Can be installed on Server AND Client Operating Systems including Vista and Widows 7 (32 & 64 bit versions).  Brian successfully tested the installation on a netbook!
  3. You get Version Control (of course)
  4. You get Bug Tracking (no mention of other work item types)
  5. You get Automated Builds!  (Continuous Integration!)
  6. As your needs grow, you can reconfigure TFS Basic to include more features.

CON’s

  1. Lacks Sharepoint Portal
  2. Lacks Reporting Services

thumbnailCA6CSF7D

 

While the Portal and Reports are nice, for a small shop they are not that valuable. My experience has been that even large shops tend to ignore these features.  I am looking forward to getting my hands on this version and seeing first had what it can do.

-Randy

Windows Azure Commercial Release this year!

WindowsAzure

After conferring with several Microsoft Windows Azure Speakers and Azure Project Managers at TechEd last week, I was able to ferret out a tentative release schedule for Windows Azure.

  • Azure Platform and Services – Commercial Release on track for PDC this year (Nov 2009)
  • Visual Studio 2010 – On track to be released at PDC this year.  (Nov 2009)
  • Window Azure pricing and Service Level Agreements on track for a July 2009 announcement.
  • SQL Server Data Services Relational Data  – Beta this summer, release expected by the end of 2009.
  • Visual Studio 2010 Public Beta – Available in the next couple of weeks.

This is good news.  In just a couple of months we’ll have a good idea of what “Cloud Services” will cost and this will determine it’s viability for Small, Medium and Enterprise customers.  Without this information, it becomes impossible to plan ahead or convince potential customers to invest in Cloud Services development.   Also,  with a release date in sight and, hopefully, a stabilization of features, we can focus the the potential uses for this new technology instead of looking into the ever changing feature list.

Keep in mind that these dates are speculative and may change depending on bug feedback to Microsoft.  However,  each Speaker or Project Manager that would give me a timeline stated that Azure and VS 2010 was on track for release around PDC this year.

Orlando Code Camp 2009 – Unity Presentation Slides and Code

 

With over 500 attendees and 11 tracks to choose from, the Orlando Code Camp was once again a huge success!   Congratulations to all of the volunteers that helped organize this event.

I gave a presentation on an introduction to the Unity Application Block – Understanding Inversion of Control and Dependency Inversion Principles by introducing the Unity Application Block into an existing application.  You can download my presentation slides and code samples here

 

I enjoyed meeting everyone in Orlando,  hope to see you next year.

Randy Patterson

Speaking at the South Florida Code Camp

 

I have the privilege of giving two presentations at the South Florida Code Camp February 7th in Miramar Florida

 

Visual Studio Team System 2008 Development Edition

This session will cover the advanced tools available in Visual Studio 2008 Professional and Development Editions. We will quickly dive deep into using Code Metrics to facilitate Unit Testing and help improve code quality. Then we’ll dig into the details of Code Coverage, Static Analysis and Profiling to round off the tools at your disposal.

 

Introduction to the Unity Application Block

This session will focus on understanding Inversion of Control and Dependency Inversion Principles by introducing the Unity Application Block into an existing application. We will decompose an application into several loosely coupled components and demonstrate how Unity is used to locate and load your dependencies. Numerous code examples will cover Unity configuration, Unit Tests and object lifetime management. We will also demonstrate how the Unity Application Block helps facilitate the Open-Closed Principle and the Single Responsibility Principle (SRP) using Decorator Chains.

 

You can register for the event HERE.   Hope to see you there.

Call for Speakers

SFCodeCamp2009

 

The South Florida Code Camp 2009 has opened Speaker Registration for the February 7th Free Code Camp in Miramar Florida.  Code Camps are a great opportunity for local developers to give presentations to their peers. If you’ve ever wanted to give speaking a try, Code Camps provide an excellent environment to do so.

Beginning ReSharper

I’ve been using ReSharper for nearly 2 1/2 years now and I can’t imagine trying to program without it.  However, one of the greatest challenges to being productive with ReSharper is learning the daunting list of keys.  Many of the Resharper features are highly discoverable using visual indicators such as icons “squiggly” lines but most refactoring and navigation activities require memorizing numerous key presses….or does it?

Refactor This

There are dozens of key presses used for Navigating and Refactoring your code and many are only valid in certain contexts.  For Example, it doesn’t make sense to attempt the Introduce Variable (Ctrl+Alt+V) refactor when your cursor is on a method signature.  Fortunately, ReSharper has an aggregate key press that will show you all of the refactorings appropriate for the current context. 

image

You no longer have to remember that Ctrl+F6 allows you to change a method signature you simply remember to press  Ctrl+Shift+R and select the Change Signature refactor.

image

As you can see “Refactor This” shows all the refactorings appropriate for the current context but it also includes the key presses for the ones that have mappings.  As you find yourself using certain items over and over you will slowly remember those keys and learn them at your own pace.  Furthermore, those refactorings that do not have a mapping are still available using this aggregate key. I often use “Pull Members Up” to “pull” a new method into the class’s Interface saving me time from the tedious cut and paste. This is a huge win for discoverability as I would never have known this refactoring existed without “Refactor This”.

Navigate From Here

ReSharper offers an aggregation key for Navigating your code that is just as powerful as Refactor This.

image

 

image

Using these two keys you gain access to most of what ReSharper has to offer and allows you to discover which Refactoring and Navigation features you like most, without the hassle of learning everything first. 

Now What

When beginning ReSharper there are a few steps I highly recommend.

  1. Download the ReSharper Key Map file
  2. Print the Key Map and hang it near your monitor where you can easily find it
  3. Highlight the “Navigation From Here” and “Refactor This” keys
  4. Highlight a few other important keys so you can quickly locate them when needed

 

Below is a link to the ReSharper map containing keys I find most useful highlighted for you.