May 2011 - Posts
Creating a Code First Database Initializer Strategy
Yesterday I helped a colleague with his ASP.NET MVC 3 site deployment.
That colleague implemented the data access layer using EF4.1 Code First. One of the restrictions that he had was that he didn’t have database permissions to create a new database and couldn’t use SQL Express or SQL CE in his application. Instead he had an empty database for his disposal in the hosting environment without a way to run SQL scripts… In such a situation the provided Code First database initializer strategies weren’t sufficient (he couldn’t drop or create the database and couldn’t run scripts). In the post I’ll show an example of how to create your own database initializer and show the strategy that helped my colleague to make his deployment.
The Database Initializer Interface
The first thing you have to get familiar with when you want to create your own database initializer is the IDatabaseInitializer generic interface. The IDatabaseInitializer interface is available in the EF4.1 EntityFramework dll in the System.Data.Entity namespace. It exposes only one method - InitializeDatabase:
namespace System.Data.Entity
{
public interface IDatabaseInitializer<in TContext> where TContext : global::System.Data.Entity.DbContext
{
// Summary:
// Executes the strategy to initialize the database for the given context.
// Parameters:
// context: The context.
void InitializeDatabase(TContext context);
}
}
Creating Database Initializer Strategy
When you want to create your own strategy you will implement the IDatabaseInitializer interface and create your desired initialization behavior. Since all the colleague wanted was to drop the database tables during the application initialization and then to create all the relevant tables here is a sample code that can perform that:
public class DropCreateDatabaseTables : IDatabaseInitializer<Context>
{
#region IDatabaseInitializer<Context> Members
public void InitializeDatabase(Context context)
{
bool dbExists;
using (new TransactionScope(TransactionScopeOption.Suppress))
{
dbExists = context.Database.Exists();
}
if (dbExists)
{
// remove all tables
context.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable @command1 = \"DROP TABLE ?\"");
// create all tables
var dbCreationScript = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
context.Database.ExecuteSqlCommand(dbCreationScript);
Seed(context);
context.SaveChanges();
}
else
{
throw new ApplicationException("No database instance")
}
}
#endregion
#region Methods
protected virtual void Seed(Context context)
{
/// TODO: put here your seed creation
}
#endregion
}
So what am I doing in the code sample?
At first I check that the the database exists if not an exception will be thrown. If the database exists I use a not documented SQL Server stored procedure which is sp_MSforeachtable in order to drop all the existing tables. After that, I get the context’s underlining ObjectContext in order to get the script that will generate the database using the CreateDatabaseScript method. Then, I run the script using the ExecuteSqlCommand method. After that I run the Seed method in order to enable the insertion of seed data into the database.
Another thing that you will need to do is to supply the relevant connection string for the existing database:
<connectionStrings>
<add name="Context" connectionString="Data Source=Server Name;Initial Catalog=Database Name;Persist Security Info=True;User ID=Username;Password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
Pay attention that when such a strategy is deployed whenever the application start over all the database tables will be recreated! This strategy should only run once.
After the deployment with the previous strategy, my colleague deployed the application again with the default Code First database initialization strategy!
Using the Database Initializer Strategy
In order to use the initialization strategy in an ASP.NET MVC application all you have to do is to set the initializer. The best place to do that is in the Global.asax file in the Application_Start handler. You will use the SetInitializer method that exists in the Database class to wire up the strategy. Here is a code sample that show how to wire up the previous strategy:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer(new DropCreateDatabaseTables());
}
Summary
In the post I showed you how to create a new database initializer strategy. The provided strategy isn’t a silver bullet solution for the problem I mentioned in the post’s prefix. The ADO.NET team is working on a migration feature for EF Code First that might provide a solution for such a scenario. In the meantime the strategy presented here helped my colleague to solve his problem.
Sela Dev. Days 2011
Next month, June 26-30, Sela is going to have a mini conference – Sela Dev. Days. In the conference you will have the opportunity to meet Israel and world lead experts and learn about the new and coming Microsoft technologies that everyone will talk about in the next following years. The conference includes 25 one day workshop in subjects such as Silverlight 5, Parallel programing, Windows Phone Mango, ASP.NET MVC 3 and more.
In the conference I’m having the following three workshop days:
- ASP.NET MVC 3, EF Code First integration, and Razor: Oh My!
ASP.NET MVC is a mature Microsoft web platform that enables the creation of quality web applications by using the MVC pattern. ASP.NET MVC 3 facilitates separation of concerns, total control over content generation using its built-in view engines and full support for test-driven development. In this one day tutorial you will get to know the framework and how to use it. - HTML 5
HTML is the markup language that every web developer uses to structure and present content in the Internet. HTML5 is the standard that is being shaped and developed currently. It extends and improves the last HTML4 standard and takes it to the next level with multimedia, communication support and more. In this one day tutorial you will get to know what is HTML5 and how you can use it even now in your web applications/sites. - Entity Framework 4.1 and Code First
Entity Framework is the new ORM and data access technology introduced by Microsoft. Entity framework provides an easy and efficient mapping from relational data into business entities. It is easy to use and it is integrated with many other Microsoft technologies. The ADO.NET Entity Framework is designed to enable developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. This one day tutorial will deep dive into EF4 and will also include an introduction to EF4.1 with Code First approach.
I recommend to attend all the workshops in the conference but these are the workshops that I would have chosen if I could attend the conference as an attendee:
I hope to see you there!
Quick Tip – Including Empty Directory While Deploying a Web Application
During this week I had to deploy an ASP.NET MVC 3 web application to a host environment using web deploy. The problem I faced was the deployment of an empty directory which is being used by the application. By design, when using web deploy tool in Visual Studio it skips empty directories when packaging a web application.
So How can you deploy this empty directory and overcome this problem?
The solution is to put an empty stub file in the directory you want to deploy.
Just create an empty text file in the directory and Visual Studio will deploy the directory.
Just to share a thought - This solution is a workaround to a Visual Studio problem which IMHO need to be solved. If a developer is adding an empty directory, VS need to give him/her the ability to choose whether to deploy it or not and not to omit the directory from the deployment package.
Visual Studio 2010 Image Optimizer Extension
One thing that caught my attention while
watching the session that Mads Kristensen had in MIX11 was the Image Optimizer extension he is writing. This extension can be very valuable when you are trying to optimize your ASP.NET application (whether it is Web Forms or
MVC 3).
The Image Optimizer Extension
The extension adds the opportunity to use industry proven algorithms such as SmushIt and PunyPNG for optimizing the images in the solution. This is enabled by a new set of menu items that are being added when you use the right button click in the Solution Explorer. You can optimize a single image file or an entire images folder. The optimization won’t affect the quality of the images so you don’t need to be afraid to use it. The currently supported image types for optimization are PNG, GIF and JPEG. In order to use the extension go to the extension manager and search the Image Optimizer in the online gallery. Another way is to download the Image Optimizer extension and install it.
Lets look at a use case scenario:
![Optimize Images Menu Item_thumb[3] Optimize Images Menu Item_thumb[3]](http://blogs.microsoft.co.il/blogs/gilf/Optimize-Images-Menu-Item_thumb3_thumb_01654217.png)
As you can see in the figure above, I point to the images directory inside my ASP.NET MVC 3 project and then I use the Optimize images menu item to optimize the images. The optimization summary will be written in the Output Window:
![Optimization in Output Window_thumb[3] Optimization in Output Window_thumb[3]](http://blogs.microsoft.co.il/blogs/gilf/Optimization-in-Output-Window_thumb3_thumb_22B4C1E6.png)
Another feature that the extension is supporting, currently in beta, is the ability to convert images to base64 strings for stylesheet embedding. Embedding base64 strings instead of using the image Url can decrease the amount of HTTP requests that your application produces. This of course should be used with caution since creating base64 strings from images should be done on small images. In big images the produced string can be very long and you will get a slower download rate for your web page.
Here is a use case scenario for base64 strings for stylesheet embedding:
![Base64 Embedding_thumb[4] Base64 Embedding_thumb[4]](http://blogs.microsoft.co.il/blogs/gilf/Base64-Embedding_thumb4_thumb_0EF7B285.png)
In the stylesheet file place the mouse on the image Url and use the Embed image in stylesheet menu item in order to replace the Url into a base64 string. The output of this operation:
div
{
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAABkCAYAAAD0ZHJ6AAAAXElEQVRo3u3OAQ0AAAgDIO3f5CW1hnOQgE4ydVgLCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKfgkubNIrSDutzqcAAAAASUVORK5CYII=)
}
Summary
The Image Optimizer extension is a promising extension if you are looking to optimize your application. It can help to reduce the size of the images you use or to embed small images as a base64 string in the stylesheet. I encourage you to play with it and see whether it can help you in your current or next application.
A Tough Nugget – NuGet Package Manager
Once upon a time when a .Net developer wanted to install a third-party/open source
component the amount of work he had to do was enormous. Things like downloading the component with all its dependencies, installing the latest component version, saving the component into source control, deploying the component with the application and more made this mission very hard and cumbersome. In other platforms such as Java and Ruby there were solutions for this problem which wrapped components into packages and deploy those packages. NuGet is an open source package manager that is integrated into Visual Studio 2010 and helps to do exactly that. If you are a .Net developer and you didn’t hear about NuGet then I hope that this post will help you to get started with it.
What We Strive?
These days, building large applications include a lot of parts/components or third party packages. For example, when you start writing a web application you’ll probably want to integrate jQuery, Modernizr and other components that will help you to build a better application. When you want to add an assembly you also want to add all the dependencies that it include. Without the dependencies (such as configuration files, images and etc.) the component won’t work at all. But there you start to hit a wall. How to download the latest component version? How to get all the dependencies? How to manage the whole thing? Not doing a good job in these issues can lead to a messy application that holds out of date dependencies that break it apart. This is why NuGet is so important.
NuGet Package Manager
NuGet is a package manager that is integrated into Visual Studio 2010. It is an open source project that can be downloaded from CodePlex but it can be added to Visual Studio also through the extension manager as you can see in the next figure:

When you install NuGet you will have the ability to use it in two main ways:
- The Package Manager Console – use a PowerShell console with commands that help to do the package management.
- The Add Library Package Reference Dialog – use a VS dialog in order to manage the packages.
The Package Manager Console
From the two option management options this is my preferred one. The Package Manager Console is a PowerShell console that helps to manage the packages that you install into your application.

If you can’t see the console after the NuGet installation you can go the Tools menu in VS –> Library Package Manager –> Package Manager Console in order to open it. There are a few PowerShell commands in NuGet that you will have to know such as:
- Get-Package – Gets the set of packages available from the package source. The default source is the current project. If you like to get a package that doesn’t exists in your project then use the following syntax:
Get-Package [package-name] -ListAvailable
- Install-Package – install a package and all its dependencies.
- Update-Package – updates a package and its dependencies to the latest package version.
- Uninstall-Package – uninstall a package that you installed in your solution.
There are other commands as well such as Add-BindingRedirect but the main ones were written previously. Here is an example that shows how to get the available packages in the solution and how to install the Modernizr package:

You can explore the commands and their syntax using the PowerShell Get-Help command. After you install the packages NuGet will add a packages.config file into your project that will include the details of the package name and version that are available in the project. Here is an example of such a file:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Modernizr" version="1.7" />
<package id="jQuery" version="1.6" />
</packages>
Also it will do all the relevant integration for you. For example adding a Scripts directory in your application and adding the full and minimized version when you install Modernizr. Another thing that can help a lot is the ability to build PowerShell script files that manage automatic installation of packages. Then, you can add the solution to source control with those files and when other developers get the latest version they can run the script and get all the packages and their dependencies.
The Add Library Package Reference Dialog
This is a graphic dialog for doing the same thing like in the Package Manager Console. When you install NuGet it adds a new menu item into the menu items of the project. You can point the project name, press right mouse button and select the “Add Library Package Reference” to invoke NuGet's package management dialog:

In the dialog you can see the installed packages, get packages from the online packages gallery, update the packages to their latest version and more.

Summary
NuGet is a great extension to Visual Studio’s stack of extensions. It helps to manage the open source component packages and their dependencies and by that decrease the amount of cumbersome work that the developer will need to do. One of its better qualities is that it is so simple and easy to use. If you ask me, this is a must know tool for .Net developers.
Not Just a Designer: Code First in Entity Framework Article on VS Magazine
Lately I wrote an article about Code First approach
in Entity Framework 4.1 for Visual Studio Magazine. The article was published a few days ago and you can read it here.
Enjoy!
Geolocation API and Client-Side Maps Frameworks
During the wrap up of the HTML5 course that
I’m currently co-authoring, I’ve created two examples of using Geolocation API with Google Maps and with Bing Maps (I didn’t want to deprive any of them
). This post won’t introduce the frameworks or the APIs. On the other hand try to find the differences of doing almost the same thing in both of the client-side maps frameworks.
Google Maps and Geolocation API
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API with Google Maps</title>
<style type="text/css">
html
{
height: 100%;
}
body
{
height: 100%;
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js" type="text/javascript"></script>
<script src="modernizr-1.7.min.js" type="text/javascript"></script>
</head>
<body>
<div id="mapElement" style="width: 100%; height: 100%">
</div>
<script type="text/javascript">
$(document).ready(function () {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(function (e) {
var location = new google.maps.LatLng(e.coords.latitude, e.coords.longitude);
var options = {
zoom: 12,
center: location,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map($("#mapElement")[0], options);
var pin = new google.maps.Marker({
position: location,
map: map,
title: 'Your Current Location',
draggable: true,
animation: google.maps.Animation.BOUNCE
});
});
}
else {
alert("No Geolocation support in your browser!");
}
});
</script>
</body>
</html>
Bing Maps and Geolocation API
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API with Bing Maps</title>
<style type="text/css">
html
{
height: 100%;
}
body
{
height: 100%;
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js" type="text/javascript"></script>
<script src="modernizr-1.7.min.js" type="text/javascript"></script>
</head>
<body>
<div id="mapElement" style="width: 100%; height: 100%">
</div>
<script type="text/javascript">
var map = null;
var layer;
$(document).ready(function () {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(function (e) {
generateMap(e);
createLayer();
addPushPin();
});
}
else {
alert("No Geolocation support in your browser!");
}
});
function generateMap(e) {
map = new VEMap('mapElement');
var location = new VELatLong(e.coords.latitude, e.coords.longitude);
map.LoadMap(location, 10, VEMapStyle.Hybrid);
}
function createLayer() {
layer = new VEShapeLayer();
map.AddShapeLayer(layer);
}
function addPushPin() {
var shape = new VEShape(VEShapeType.Pushpin, map.GetCenter());
shape.SetTitle('The Current Location');
layer.AddShape(shape);
}
</script>
</body>
</html>
Enjoy!
WCF Data Services Processing Pipeline
First I must confess.
Even tough I like OData and WCF Data Services, in the last couple of months I didn’t have the chance to work or use them. This is why when .NET 4 was shipped I haven’t noticed a new and interesting extension point in the framework – the processing pipeline. In the last MIX11 I got a little introduction to that extension point in Mike Flasko’s session. In this post I’ll explain what is the WCF Data Services' server side processing pipeline.
WCF Data Services Processing Pipeline
In the past I wrote about the Interceptions mechanism that is built inside WCF Data Services. One of the advantages of using that mechanism is the ability to wire up business logic such as custom validations, access policy logic or whatever you like to insert in the queries/change sets pipeline. The problem starts when you need a generic behavior for all the entity sets interceptions. In the first release of WCF Data Services there were no extension points to use that will help implement generic things. But now, in .NET4, you can use the processing pipeline in order to do that. The new DataServiceProcessingPipeline is a class that is being used as a property of the DataService class (which every data service inherits from). It exposes four events that you can hook to:
- ProcessingRequest – The event occurs before a request to the data service is processed.
- ProcessingChangeset – The event occurs before a change set request to the data service is processed.
- ProcessedRequest – The event occurs after a request to the data service has been processed.
- ProcessedChangeset – The event occurs after a change set request to the data service has been processed.
These events enables the developer to write code that is performed during the process of WCF Data Services pipeline before and after things happen.
Using WCF Data Services Processing Pipeline
Here is a simple example of how to use the processing pipeline events to write to the output window that the events were called:
public class SchoolDataService : DataService<SchoolEntities>
{
public SchoolDataService()
{
ProcessingPipeline.ProcessedChangeset += new EventHandler<EventArgs>(ProcessingPipeline_ProcessedChangeset);
ProcessingPipeline.ProcessedRequest += new EventHandler<DataServiceProcessingPipelineEventArgs>(ProcessingPipeline_ProcessedRequest);
ProcessingPipeline.ProcessingChangeset += new EventHandler<EventArgs>(ProcessingPipeline_ProcessingChangeset);
ProcessingPipeline.ProcessingRequest += new EventHandler<DataServiceProcessingPipelineEventArgs>(ProcessingPipeline_ProcessingRequest);
}
void ProcessingPipeline_ProcessingRequest(object sender, DataServiceProcessingPipelineEventArgs e)
{
Debug.Write("Processing Request was called");
}
void ProcessingPipeline_ProcessingChangeset(object sender, EventArgs e)
{
Debug.Write("Processing Change Set was called");
}
void ProcessingPipeline_ProcessedRequest(object sender, DataServiceProcessingPipelineEventArgs e)
{
Debug.Write("Processed Request was called");
}
void ProcessingPipeline_ProcessedChangeset(object sender, EventArgs e)
{
Debug.Write("Processed Change Set was called");
}
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
As you can see in the service constructor I wire up all the events. This is simple sample but as I wrote you can put in the event handlers logic that perform generic behaviors such as security policies, validations and etc.
Summary
In .NET 4 there is a new feature inside WCF Data Services that enables to wire up events into the service’s processing pipeline. This is very helpful in scenarios such as business logic that you want to impose on the service execution behavior.