Database Provider Factories: EF + SQL Compact

Now that Entity Framework 4.1 has been released and SQL Compact Edition 4.0 was released a while back, you can start using those technologies in your projects. I was working on a MVC 3 project when I discovered a NuGet package for SQL Compact Edition.

You have three option to install SQL Server Compact 4.0, using the Web Platform Installer, direct download, or you can add it as a NuGet package. I would suggest using the NuGet option, as that includes the required files with your source code. Make sure you get the documentation as well.

SqlServerCompact package:

With this package, you can start building code that queries and stores data in a file-based database. Yet, you still need one more package to make it work properly together with Entity Framework 4.1. Luckily, there is another NuGet package for this, EntityFramework.SqlServerCompact.

The SqlServerCompact package will try to modify your web.config/app.config with the following keys:

      <remove invariant="System.Data.SqlServerCe.4.0" />
      <add name="Microsoft SQL Server Compact Data Provider 4.0" 
  description=".NET Framework Data Provider for Microsoft SQL Server Compact" 
  type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, 
  Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

Also included in the package is the binaries for SQL Server Compact 4.0, located at the same level as your Visual Studio solution file, you should find this folder and within it all the assemblies needed to run: packages\SqlServerCompact.4.0.8482.1. Inside the lib folder is the System.Data.SqlServerCe.dll, which is the .NET assembly you need to work against SQL Server Compact.

The other package includes the assembly System.Data.SqlServerCe.Entity.dll, which contains code that generates proper queries against the SQL Server Compact. Additionally, it will add a source code file to your project inside the App_Start folder, that contains this code:

using System.Data.Entity;
using System.Data.Entity.Infrastructure;

[assembly: WebActivator.PreApplicationStartMethod(

namespace InTheBoks.Test.Integration.App_Start {
    public static class EntityFramework_SqlServerCompact {
        public static void Start() {
            Database.DefaultConnectionFactory = 
              new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

What happens here is that the default connection factory of the Entity Framework is changed to the provider specified in the web.config/app.config. While I was working on the previous builds of SQL Server Compact 4 and Entity Framework 4.1 CTPs, I did not have the provider changed in the web.config. The new key in the config made me wonder for what reasons it removed and added the provider again. So I investigated with an integration test project to see what really happens.

The default connection factory is SqlConnectionFactory. That means that we need to change the connection factory in the start up of our application, which is done with the code inside the Start method displayed above, which changes it to SqlCeConnectionFactory.

To investigate what the default configuration is, I had to access a list of factories using the API: DbProviderFactories.GetFactoryClasses(). This will give you a data table with rows for all the factories. I did this to figure out why the NuGet package made the changes to my web.config/app.config and to see if there was any difference to my already installed factory and the one added in the config. Conclusion was, there is no difference. The reason why the package adds the provider, is probably because the factory is not registered on the computer if you don’t install using the manual or Web Platform Installer – so it have to add it manually in the config. My suggestion is to keep the configuration key in place, this ensures that your application will work without the need to install SQL Server Compact.

Reference Table for DbProviderFactory Classes.

Name Description Invariant
Odbc Data Provider .Net Framework Data Provider for Odbc System.Data.Odbc
Type System.Data.Odbc.OdbcFactory, System.Data, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
OleDb Data Provider .Net Framework Data Provider for OleDb System.Data.OleDb
Type System.Data.OleDb.OleDbFactory, System.Data, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
OracleClient Data Provider .Net Framework Data Provider for Oracle System.Data.OracleClient
Type System.Data.OracleClient.OracleClientFactory, System.Data.OracleClient, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
SqlClient Data Provider .Net Framework Data Provider for SqlServer System.Data.SqlClient
Type System.Data.SqlClient.SqlClientFactory, System.Data, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
Microsoft SQL Server Compact Data Provider .NET Framework Data Provider for Microsoft SQL Server Compact System.Data.SqlServerCe.3.5
Type System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91
SQLite Data Provider .Net Framework Data Provider for SQLite System.Data.SQLite
Type System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=, Culture=neutral, PublicKeyToken=db937bc2d44ff139
Microsoft SQL Server Compact Data Provider 4.0 .NET Framework Data Provider for Microsoft SQL Server Compact System.Data.SqlServerCe.4.0
Type System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91

(Foto by Tim Morgan)


InTheBoks v2 Preview

I’m currently working hard on the next version of InTheBoks. I wrote about it earlier on my blog, at which time I built it using Silverlight.

New version is being built entirely on HTML 5 and is using the latest of technologies available.

Here is a video preview of the new version, which demonstrates how I’m using AJAX to call the REST API to delete items in your movie catalog.

This new version will be released as open source and be a hosted service, that means you could build your own service just like InTheBoks and there are plenty of good code examples on how you can build modern HTML 5 applications on ASP.NET MVC 3.

Technologies and libraries in use:

  • Entity Framework 4.1 RTW (Code First)
  • SQL Server Compact Edition 4
  • ASP.NET MVC 3 (Razor syntax)
  • WCF 4 REST
  • jQuery
  • jQuery UI
  • jQuery Templating
  • Knockout JS
  • Facebook SDK

You can follow the progress on the Facebook page:

Remember to also check out the official website where the new version will be released, hopefully sometime in 2011.


Try Windows Azure for free

You can now try out Windows Azure for free, without credit card. Head over to and signup for a 30 day pass. This should get you started on developing cloud apps and you’ll quickly realize just how easy it is, if you already know how to develop web apps.

Use the promotion code: CRMIKEA

If you have any questions regarding Windows Azure, please feel free to leave a comment. Additionally, if you live in Norway and have a interest in cloud computing, have a look at the Cloud Computing group at The Norwegian Computer Association:


Microsoft Office 365

Microsoft is about to release it’s latest Office product, the Microsoft Office 365, which is a cloud-based solution that delivers some of the integrated Microsoft Office tools with their server product offerings, such as Microsoft SharePoint and Microsoft Lync.

For small businesses and new startups this is a great product, which gets you started with collaboration tools within minutes, as oppose to expensive investement in servers, software, installation and maintenance. It even integrates

Go and visit the website to signup for the beta!


Blogging with WordPress

WordPress logo

Recently I started using WordPress for my blogs and today I launched this blog on WordPress, and all my blogs will soon be running on WordPress. It’s a decent blog engine that has been around for a while and is pretty stable. It takes some work to import all your existing items, ensuring permalinks are intact and that photos still works. I imported 77 blog posts from the older blog and I hope all photos should work properly.

Recently I have been using Microsoft WebMatrix for some of my web development needs and for all new WordPress site I’m building, I start out with WebMatrix. It’s simply the easiest and fastest way to get started building your own custom blogs on WordPress.

Unfortunlately the FeedBurner service doesn’t link back to the permalinks but a combination that uses the GUIDs. Unfortunlately that means all the old links in my old feed URL won’t work, but the feed contained the full posts so it shouldn’t really matter much. The new feed URL will be

Importing from BlogEngine.NET using the BlogML format does not do categories properly, but it does import comments. Unfortunlately I had to use the RSS import and thus all my old comments on this blog are now gone. I might consider writing a script that imports them sometime in the future, but there was a majority of spam comments so hopefully it’ll be alright.

Until next time, you can take a look at my new front page which is also running on WordPress,


Doing Web Development Better Part 2

Since last time, I have come further in the research on how to have more dynamic loading of entities using reflection and I’m displaying the different actions using partial views from my themes folder. That makes it possible for individual themes to override the layout of the generated pages.

Current Status

So the current status is that I have fully dynamic rendering for list of items and details on individual items. I have not yet added support for editing. The end results of what I’m working on, might be somewhat similar to the ASP.NET Dynamic Data technology from Microsoft. It does scaffolding of your data automatically. The difference obviously will be that mine are built on ASP.NET Web Pages and next version of Entity Framework. Other than sharing some general concepts, there are no similarities between my code and ASP.NET Dynamic Data.

Status Quo

Mikael Söderström made a good example on how you can combine Entity Framework and ASP.NET Web Pages, so I won’t bother doing the same. Check a bit down on this thread:

What I want to avoid is the specific repositories, I want a single repository that is dynamic and can handle any entity type. I also want to avoid any logic inside the .cshtml that relates to the creation/reading of the entities. His example is still decent for those who want to go the “new, old route” of doing web development with Web Matrix. I’m on a mission to simplify this pattern.

Get Started

What I want to show today is how to dynamically create an instance of your entity and return that from your database. Create a new empty WebMatrix website and start writing some code.

Before we begin, make sure you have the latest version of Microsoft WebMatrix, SQL Server Compact Edition and Entity Framework CTP.

First you need to go through the example by Mikael that I linked too earlier, but you can replace the GuestbookRepository.cs with the code below and the default.cshtml will be different as well.

1. Create a new interface and call it IEntity. Just keep this empty for now.

2. Create a new class and call it Repository. Copy the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Helpers;

/// <summary>
/// Generic repository for all of your entity types.
/// </summary>
public class Repository<TContext> where TContext : DbContext
    private TContext _context;
    private string _entityTypeName;
    private Type _entityType;

    public Repository(string entityTypeName)
        _entityTypeName = entityTypeName;

    public TContext Context
            if (_context == null)
                _context = CreateContext();

            return _context;

    private TContext CreateContext()
        _entityType = Type.GetType(_entityTypeName);

        // Make sure that only IEntity objects are returned for security reasons. You don't want
        // code that allows users to initiate any objects on the server.
        if (!_entityType.Implements(typeof(IEntity)))
            throw new ApplicationException("The specified entity does not implement the required IEntity interface.");

        // Create an instance of the DbContext.
        var context = Activator.CreateInstance<TContext>();

        return context;

    private dynamic GetSet()
        // Get an instance of the DbSet.
        var set = Context.Set(_entityType);

        // Load all the values.

        // Get the query values.
        return set.Local;

    public void Load(IEntity entity)

    public void Add(IEntity entity)

    public dynamic LoadAll()
        return GetSet();

    public void Delete(IEntity entity)

Unfortunately this code only does listing of all the entities, through the LoadAll method. In one of my later blog posts, I will provide example that does all the normal CRUD operations for your entities.

3. Create a new .cshtml file and call it what you want. Paste the following code into the new file:

    var entityType = UrlData[0];
    var action = UrlData[1];
    var id = UrlData[2];
    if (string.IsNullOrEmpty(entityType))
        Response.Write("There is nothing to see here... - Jim Carrey, \"Lifeguard on Duty\"");
    var repository = new Repository<BlogCatalog>(entityType);
    var result = repository.LoadAll();
    Page.Model = result;
    var grid = new WebGrid(Page.Model);    


The code has been simplified a bit, it doesn’t handle multiple types of listing. The “BlogCatalog” is the DbContext you created in the example by Mikael. Change that to whatever your own context is named.

Screenshot of the end result, this is the listing of my Author table.


The Beginning of By Convention

That’s the early beginning of the framework that will make it even easier and better to develop web apps using Microsoft WebMatrix and ASP.NET Web Pages. The combination of ASP.NET Web Pages with Entity Framework and doing the code by convention, gives us a powerful tool where we avoid duplicate code and we don’t have to repeat yourselves too often.


Doing Web Development Better Part 1

For a while now, I have been developing my own blogging framework using Microsoft WebMatrix and ASP.NET Web Pages. As these technologies are still in beta releases, I’m not prepared to release any beta version of my own blogging framework. What I would like to do, is share some of my experience writing the web app on this new platform. This is the first post in a series where I will explain some of my experience and hopefully give some pointers and hints.

In The Beginning

Initially I was amazed with the incredible speed and power of the ASP.NET Web Pages Razor syntax and the Microsoft WebMatrix editor, in combination with the new IIS Express. Modifications was super quick to do, no compilation involved, it just worked and it rendered fast. I started out prototyping the web app and wrote lots of code inside the .cshtml files. Even included SQL code straight in the view files, this was the beginning of web development for me when I started out on classic ASP (Active Server Pages). After a while, I moved most of my SQL queries into classes that I kept in my App_Code folder. The Microsoft Data Helpers relied heavily upon the new dynamic type. All methods returned just a dynamic type, which I initially consider to be great and powerful, I could easily extend my types with any additional properties.

It was both easy and powerful to build my web app in this manner, but as my web app kept growing I realized I needed to make some improvements. From early on, I made a very conscious decision to not rely on any ORM (Object Relational Mapping). I didn’t want the requirement to compile or generate any code. Generated code is always bad. So there was no LINQ to SQL or Entity Framework for me… but that was until…

A New Beginning

… Microsoft released a CTP (Customer Technology Preview) for the next version of Entity Framework (EF). And off I went refactoring my code into relying on the Code-First capabilities of EF CTP. Instead of manually writing my SQL scripts, which I had done up until now, I relied on the Entity Framework to generate my tables automatically. Instead of writing SQL statements, I now wrote entity types, just simple Plain Old CLR Objects (POCO). For me, it’s much more natural to write simple C# objects than SQL statements and I get better type safety which avoids some bugs, but obviously removes the benefits of working with dynamic types as I did earlier.

Here is a typical example of one of my earlier entity types:


As I continued with my refactoring, a pattern started to emerge in my code base. I had my entity types, I had my catalog objects (DbContext), I had my static helper methods for all my entities and I still had a bunch of logic inside my .cshtml files to handle new elements, editing of existing elements, deletion of elements, validation of the model (user input) and often some other parts, such as the notification text to display when a save succeeded.

I started thinking that this is pointless, no developer should ever be put to write tedious repetitive code. I have lots of entities that I need the standard CRUD (Create, Read, Update, Delete) actions for and there is no chance I’m willingly going to write every single page for all of my entities. There is not legacy database, no legacy object types and no legacy requirement of any sort in my blogging framework, so I figured it was time to do more by-convention.

Don’t Repeat Yourself

So I started out thinking about how I could avoid repeating myself. I needed a convention for URLs, I came up with this current solution, will possibly change in the future, but for now it sticks:


One example then, would be for the authors:


The type of actions I added was View, Edit, Delete, Create. View was planned to be used in the future if I add permission control that disabled the ability to edit the entity, but it’s not used much in the administration interface. Some of the guidance from REST is added here, but not all the concepts. The Delete action is only possible to do when you do a POST (or HTTP DELETE).

Here is a really simple example on how you can get the 3 input values from the URLs. All you have to do is create an Admin.cshtml file and then the above URL pattern will work just fine. UrlData won’t throw exceptions when you try to access index values that doesn’t exists, so there is no need to validate before you read the URL input.


Final Thoughts

One obvious question would be why I didn’t choose to do this in ASP.NET MVC 3? It already supports the HTTP verbs, good separation of views, models, etc. The simple answer is that I think ASP.NET Web Pages in combination with WebMatrix is simpler and I wanted to do this project to learn the new technologies. I’m already doing lots of ASP.NET MVC development on my daily job, so this was a fun experience to learn something new.

I’m currently researching how I can automate the views for all my entities, by configuration or simply by reflecting over my DbContexts? Right now, I’m investigating with reflection over my DbContext types, I’ll keep you updated in the next part on this blog series.


Code Like A Girl


It’s a well established fact that our industry (software development) has a majority of male programmers. I think it’s important that we all promote the software engineering field towards girls, ensuring the future will have a higher percentage of girls who write code.

Today, the majority of software are developed by 20+ year old boys who develops software used by approx. 50% female users, often at twice the age of the developers. It’s one of the root causes of a lot of user frustration.

Writing Beautiful Code

Software developers care to little about beauty and elegance. We often stretch ourselves towards writing good unit tests and follow established object oriented best-practices. But we rarely think about how to make our architecture, design and code look beautiful. It’s not exactly in our nature, sort of speak.

As you can read in the excellent post on the same topic on the Creating Passionate Users blog:

“Because caring about things like beauty makes us better programmers and engineers. We make better things. Things that aren’t just functional, but easy to read, elegantly maintainable, easier–and more joyful–to use, and sometimes flat-out sexy. “

We should never forget that we rarely look at our own code more than once or twice, but eventually the code we write will be read by many others. It’s important to always recognize this fact and position ourselves in the minds of our fellow programmer.

Simplicity and Beauty

One of my mantra’s whenever I communicate with people through presentations and in my daily job, is to focus on simplicity. Making things simple is important, as a means to reduce complexity and improve communication.

Though it’s important to not forget about beauty and making things beautiful is similarly as hard as making things simple.

If you achieve simplicity and beauty you will be successful.

So from now on, try more to Code Like A Girl!

(This post is not meant to be sexist in any way, it’s a natural fact that females have a genetic advantage on beauty, one which we can learn from.)

Get your Code Like A Girl stuff from


Simplifying Text Resources in Silverlight

Here is how you can simplify the way you work with resources in Silverlight 4. The normal procedure to bind against resources is writing an binding statement in the .Content or .Text property of your elements. I will explain how you can use a dependency property to extend your Silverlight controls with an Resource.Key (ResourceKey) property and one for Resource.Tooltip.

The sample also includes a way to enable live language switching in your application, enabling the user to see language-change effects in real-time without restarting the application.

Markup differences

The binding syntax in XAML is somewhat awkward and it uses a lot of bracket ({  }). I wanted to avoid this and make it cleaner and more understandable. Have a look at this example on how you normally bind the content of a button to a static resource, which should be your generated resources class that the .resx file generates.

Content="{Binding About, Source={StaticResource Resources}}"

What this does is bind against the resource property About. You register the Resources property in your App.xaml file like this.

<resources:ApplicationStrings x:Key="Resources" />

What we want to do instead, is a syntax like the following example.


This is obviously much cleaner and communicates better than the first example. Resource.Key is a dependency property defines in the Cirium Application Framework. You don’t need to use Cirium to achieve this behavior, I have included the source-code below.


What’s the catch?

Obviously there are some small issues. The current implementation does not support resource text with format parameters (eg. “Welcome {0}”), I’m considering adding this in a future update.

Important: For this behavior and sample to work, you are required to modify the generated code-behind for your .resx file. You need to modify the constructor of your class and make it public, by default it becomes internal. You also need to modify the class to be partial, for the auto-magic update of all bindings to work properly. If you don’t do this, you can’t register your resource directly in the App.xaml.

You also need to manually add support for any controls I have not added in the dependency property class, currently it supports Button, TextBlock, TextBox and CheckBox. If you use any Silverlight Toolkit/SDK controls, you need to modify to specify which dependency property to bind against.

How does it work?

There is a simple class named Resource that handles the binding of controls with your resources. It’s important to notice that we use binding of the property instead of just setting the content directly from the resource. You might want to reconsider changing this if your application is not going to support multiple languages, but mine required to support multiple languages and be able to dynamically and quickly change between them without restarting the application or reloading the views.

There is one single requirement and that is that you register all your resources in the applications static resources collection under the name “Resources”. You can obviously change this in the class file as you see fit for your own project. Here is a screenshot that shows the sample application running, with localized content and tooltip.


Enabling your project for localization

When I first starting localizing my Silverlight application I was surprised how hard it was to figure it all out. It’s not enough to simply add the different .resx files to your project, you need to manually (even in Silverlight 4 with Visual Studio 2010) edit your project file with the proper languages you want to support. Unload your project, edit the content of it, locate the SupportedCulture XML element and add the languages you want to support. This example is for English and Norwegian.


To add multiple languages to your application, start by adding one .resx file to your project if you don’t have one. Fill it out with some values. Copy the .resx file to the same location in your project, and rename by adding the language (culture) code before the .resx file-ending. E.g. ApplicationStrings.nb-NO.resx or ApplicationStrings.en-US.resx.

Tip: You can localize the Out-of-browser settings by making multiple OUtOfBrowserSettings.xml files, just name them in the same way as your .resx files.

Tip: You can disable the code generation for your extra languages, Visual Studio won’t generate any content in your code-behind when you have multiple languages, only for the main language, so disabling the code generation in the extra .resx files will avoid generating empty files in your project.

Source Code

Below is the source code, it’s a simple working application in Silverlight 4, configured to run out-of-browser. It’s important to notice that you need to manually configure SupportedCultures if you need more languages than what’s in the sample.

Download the SimplifyResources sample project.

Here is the full source-code of the Resource.cs:

namespace SimplifyResources


    using System.Windows;

    using System.Windows.Controls;

    using System.Windows.Data;

    using System;

    public static class Resource


        /// <summary>

        /// A dependency property for attaching a resource key to the element.

        /// </summary>

        public static readonly DependencyProperty KeyProperty =





                new PropertyMetadata(OnKeyChanged)


        public static string GetKey(DependencyObject obj)


            return (string)obj.GetValue(KeyProperty);


        public static void SetKey(DependencyObject obj, string value)


            obj.SetValue(KeyProperty, value);


        /// <summary>

        /// A dependency property for attaching a resource key to the element used in the tooltip.

        /// </summary>

        public static readonly DependencyProperty TooltipProperty =





                new PropertyMetadata(OnTooltipChanged)


        public static string GetTooltip(DependencyObject obj)


            return (string)obj.GetValue(TooltipProperty);


        public static void SetTooltip(DependencyObject obj, string value)


            obj.SetValue(TooltipProperty, value);


        private static void OnKeyChanged(DependencyObject targetLocation, DependencyPropertyChangedEventArgs args)


            SetupBinding(targetLocation, args, false);


        private static void OnTooltipChanged(DependencyObject targetLocation, DependencyPropertyChangedEventArgs args)


            SetupBinding(targetLocation, args, true);


        private static void SetupBinding(DependencyObject targetLocation, DependencyPropertyChangedEventArgs args, bool isTooltip)


            if (args.OldValue == args.NewValue) return;

            FrameworkElement element = targetLocation as FrameworkElement;

            if (element == null)


                throw new Exception("Resource.Key can only be set on framework elements.");


            // Load the resources source from the application’s StaticResources collection.

            // This will only work if you have added it to your App.xaml.

            var dataSource = Application.Current.Resources["Resources"];

            Binding binding = new Binding((string)args.NewValue);

            binding.Source = dataSource;

            if (isTooltip)


                element.SetBinding(ToolTipService.ToolTipProperty, binding);




                element.SetBinding(FindDependencyProperty(element), binding);



        private static DependencyProperty FindDependencyProperty(DependencyObject control)


            DependencyProperty property = null;

            if (control is Button)


                property = Button.ContentProperty;


            else if (control is TextBlock)


                property = TextBlock.TextProperty;


            else if (control is TextBox)


                property = TextBox.TextProperty;


            else if (control is CheckBox)


                property = CheckBox.ContentProperty;


            return property;





If you get exception similar to this one, you need to modify the generated resources class.

No matching constructor found on type ‘SimplifyResources.Assets.Resources.ApplicationStrings’. [Line: 9 Position: 46]


Trying to understand Microsoft.Data.dll

Here is my analysis of the recently “released” (embedded) Microsoft.Data.dll assembly, the namespace and the types it includes. It’s been the topic of a lot of heated debate recently, with viewpoints I’m unable to relate to and understand just from reading, so I needed to understand.

The debate is stemming from a blog post by David Fowler and his example that shows how some data-related tasks have a simpler syntax with Microsoft.Data and the ASP.NET WebPages with Razor Syntax.

What is inside the Microsoft.Data namespace?

There is very little code inside the namespace and the assembly. It’s simply some helper types that makes life's a little bit easier. It’s not a new data access framework, like Linq to SQL or Entity Framework.

It contains the following classes: ConfigurationManagerWrapper, ConfigurationConfiguration, Database, DbProviderFactoryWrapper, DynamicRecord, IConfigurationManager, IDbFileHandler, IDbProviderFactory, SqlCeDBFileHandler and SqlServerDbFileHandler. Of which only Database and DynamicRecord are public available, the others are internal.

All data access inside the Microsoft.Data types are using the common ADO.NET types, not the providers specific for any SQL platform. This means it’s not restricted to SQL Compact Edition nor SQL Server. It relies on DbConnection, DbTransaction, DataTable, etc.

Microsoft.Data on ASP.NET Web Forms

While Microsoft.Data.dll is currently not accessible in the Add References dialog, you can find it by looking on your computer, it’s located in the Global Assembly Cache (GAC). Microsoft probably don’t want us to use it outside of WebMatrix in the current release… but if you just take a copy of the assembly out of the GAC, then you can reference the assembly in any .NET project and it will load it from the GAC (you just need the file so you can add a reference).

In my project I added a database to my App_Data folder (which you normally would never do, unless you are working with a local read-only cache in a large-distributed system or working with SQL Compact Edition) and added the following code to my web form, to make it render the Name column of my Users table.

	var db = Database.OpenFile("Database1.mdf");
	var users = db.Query("SELECT Id, Name FROM Users");
	foreach (var user in users)

Take notice of the OpenFile parameter, it’s simply the filename on disk. I don’t have to care about any specific details of the connection string, nor how to figure out where the App_Data folder is.

Obviously though, if you added an entity framework (EF) model of your database, you would have very similar example to achieve the same and you don’t have to care about the connection string, at least not in theory.

	using (var db = new Database1Entities())
	var users = db.Users;
	foreach (var user in users)

The two big distinctions betweens these examples is that the first one is dynamic, I can modify the database schema whenever I want and it won’t (necessarily) break my web app, while the latter example with EF will need to refresh the entity types based on the database model.

The other distinctions is that the first example doesn’t require a connection string, while the latter generates one for you automatically, a rather cryptic looking one.

<add name="Database1Entities" connectionString="metadata=
provider connection string=&quot;
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;
Integrated Security=True;
User Instance=True;
MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />


While all of this are peanuts for me and anyone who’s been developing on .NET for a while, I think that making things simple where possible is positive, rather than negative. It doesn’t mean we will stop using NHibernate, do proper n-tier and layered architectures just because Microsoft makes some tasks simpler for beginners. It also means some of us probably will eventually have to maintain and possibly migrate solutions built on Microsoft WebMatrix, but does that give us any right to restrict beginners the privilege of building their own solutions and feeling the immense joy of realizing their dreams?

Other’s feedback and comments

Ayende Rahien comments on his blog on the example, where he mentions the use Response.Write within the loop. Understandable this is probably not the best way to do this, but it’s understandable with the sample in question, which was already using Response.Write. There are slightly better examples available out there. He also points out that having the SQL queries directly in the view code is an open invitation for SQL injection. Using proper parameterized queries will reduce this potential security problem. Looks like David updated the sample to use parameters after the initial reactions. After the security push at Microsoft some years back, they really cleaned up their practices with examples in the MSDN documentations, I think we should expect the same level of security thinking on employee blogs as well.

Ayende quotes David, which (David) made the assumption that Microsoft.Data is tied to Sql Server in any way, which my investigations has shown is not correct.

David tried to respond to some of the feedback on embedding SQL directly in the view, with hacking around to get the new dynamic keyword to work properly with LINQ. To me, this defeats the whole purpose of simplicity with Microsoft WebMatrix, Razor and Microsoft.Data.

KristoferA comments on the post and suggests generating Linq to SQL datacontext using a page-level directive, which would essentially give the developer entity objects to work with (and query against). This again defeats the purpose of simplicity, and now you can no longer change the database scheme without “recompiling” your web-app.

The namespace naming is another sour point for some, and I can agree that there is little point is “abusing” the Microsoft.Data namespace for such a trivial little helper, perhaps Microsoft.WebMatrix.Data or Microsoft.Data.Connection?

Who is this for?

Microsoft WebMatrix (and ASP.NET WebPages) is not a tool built for “professional” programmers, additionally is it not a fully generic framework for building everything. It’s a domain specific language that is optimized for building simple web applications without to much resources.

It is not meant for enterprise applications that handles millions of transactions. Will it be used for that? Yes, it probably will! We’ve seen plenty of classic examples of websites that starts with simple web-frameworks and find themselves in big trouble when their services become popular. Services like Twitter and Facebook was not built to scale to their current levels, yet they started as simple concepts and services and has grown to become important services which affects global policies and real-life social interactions.

It's Not Rocket Science, But It's Our Work:

And obviously, it’s for those of us who still miss the old days with ASP Classic, here is a pretty good (and funny) read, 8 Reasons to Stick with ASP 3.0 in 2006 (and 2007).

Final thoughts

It’s very clear that Microsoft WebMatrix (and related technologies) are primarily is focused towards beginners and it’s a great tool to build simple websites. I wouldn’t advice anyone to use this if you already know ASP.NET MVC and want to build complex web solutions, ASP.NET Web Forms, MVC or other more general purpose frameworks would probably be more fit.

Additionally I think it’s important to remember that WebMatrix is primarily focused on SQL Compact Edition for data access, the built in editor doesn’t allow you to modify SQL Server database. So the question (and response to some of the comments) is how many layers do you want to wrap your data access logic for a SQLCE database?

Been a while since Microsoft did a push towards simplifying development for beginners, when we went from VB6 to VB.NET, everything was more complex and the entry level for VB.NET is on-par with C#. With the release of .NET Framework 4, the complexity and total amount of features is mind blowing. I for sure welcome tools, languages and frameworks that simplifies how we develop software.

Simplicity is hard and it's something we should strive towards in all that we do.