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.


No Code-Behind for MVVM

One of the annoying things when you start working with Model-View-ViewModel in Windows Presentation Foundation (WPF) is the fact that you can’t just delete the code-behind file for your .xaml files.

After discussing the problem with Peter Lillevold, he came up with a solution to our problem. Let’s first discuss the problem and then present the solution.

Initialize Component

When you look at a recently created XAML file, you’ll notice there is a call to the InitializeComponent in the constructor. This is an operation that is not available in the derived type (Window, Page, UserControl) nor is it directly visible in your project. Right-click on the method call and Go To Definition (F-12) opens an generated file you normally don’t see.

The operation is responsible for loading (initializing) the XAML which is embedded as a resource in your application binaries.

Example of a code-behind class:

public partial class MainWindow : Window
    public MainWindow()

Unfortunately the XAML views require this call to InitializeComponent to function properly, if you go ahead and delete the code-behind file you’ll end up with an blank window/user control when they are loaded.

View Base Types

The solution is to provide a view-base for all your top-UI containers, such as Window, Page and UserControl. These view-base types can additionally be used to construct convention-based initialization of View Models in an MVVM-pattern implementation. This is beyond the scope of this post, might be visited in a future post.

Here is an example on how to do this for a Window view:

public partial class WindowView : Window
    public WindowView()
        var initializeComponentMethod = GetType().GetMethod("InitializeComponent",
            BindingFlags.Public | BindingFlags.Instance);
        if (initializeComponentMethod != null)
            initializeComponentMethod.Invoke(this, new object[0]);

First we tries to get an reference to the current instance of the object, which will return the inherited type (for example “ExampleView” type as included in my sample source code). Then we validate if the method actually exists and if it does, we invoke the InitializeComponent method.

Next step is to change the XAML markup so you no longer use the framework type for Window, Page or UserControl, but instead your own custom base view types. At this point you can delete the code-behind of your XAML files, just make sure you don’t delete any existing logic that you might have in your code-behind.

Side note: Having logic in code-behind is not a violation of good practices, even when you’re working with the MVVM (Presentation) pattern.

Open your XAML and add a statement that imports the CLR namespace where your view types are, e.g.


Then change the root-XML-element in your XAML markup file to e.g.


Note that the x:Class element on the root element dictates the name of your view, meaning your XAML file can be named something other than the generated type of the view.

Example Source Code

For a concrete example of this implementation in WPF and how you can avoid the code-behind file altogether is included below. The two examples are ExampleView.xaml and ExampleControl.xaml which both works without code-behind files.

Please use the example with caution and there are no guaranties that the workaround doesn’t change some behavior in your running application. Any feedback is welcome, please leave comments!

Download the NoCodeBehind example in C#.


MSDN Live: Solution Architecture

At the next MSDN Live tour in Norway (in April), I’m doing a talk about Solution Architect and SharePoint 2010 for Developers.

I would like to air some ideas I have for the Solution Architecture talk and hopefully get some feedback, perhaps some tips and hints that can improve my talk.

What’s in a name?

There is no way I’m going to even start to try defining the name architecture or the architect role. It is something different to every single individual, in the same way as I’m never going to define what a developer truly is.

Though we can talk about distinctions between what it means to be a developer and what the role of an architect in comparison could potentially be.

Architecture is primarily about the bigger view of things and the spider web of interactions between humans and systems in an organization and across organizations. There are many forms of architects, from functional architects, enterprise architects, software architects and what I’m going to talk about: solution architects and architecture.

Architect? You make diagrams, right?

Well sure, architects often use tools to draw their ideas and conclusions, even if it’s just on pen and paper. Source code is the primary language for a developer and diagrams is the primary language of an architect. More than that, I’m not going to talk about diagrams. Other than say, they are a good tool for communicating intents, ideas, thoughts and meaning. Architecture is not about diagrams, it’s about everything else.

The Solution Architect Role

When I talk about the solution architect role, think about the role from a technical perspective, not a functional one. Here is a diagram that tries to illustrate some of the interactions that the architect has with other roles in a project.


Depending on the scale and form of a project, the architect is often involved early in the process – and hopefully part of the project until the final delivery date. Unfortunately the identity of the architect have been put on some negative weight. Some people see the architect as someone distant from the project, someone that makes decisions that developers feel the pain from. And this can be true for some projects, and that is a bad position to be in, both for the developers and the success risk of the project.

It’s important that the solution architect is closely involved with the project all the way. Initially they work with the client to gather all the requirements, depending on what type of architect and his or hers responsibilities, they might be both functional and non-functional requirements. Initially often with project leaders and members on the client side and often the upper-management often has a stake in the project and unfortunately sometimes do technical decisions ahead of involvement of others, often after reading an report by Gartner… So often the architect and developers have to work with pre-existing decisions, most of the time, this works out fine though.

The green person in the illustration is the clients network and system administrator, who often have requirements and demands regarding security and deployment. If you’re lucky to be on a project with a designer, the typical black-suite guy using a Mac, they often have insane demands on the interface. I say this with a sense of humor, as usability experts and designers are very important individuals for the success of a project.

Then you have all the others, which are different individuals from inside and outside the organization. Computer security experts might be utilized to do reviews of the architecture and eventually the complete solution.

Users of the final solution is very important, it’s for those we do what we do. If we can’t satisfy them, then there is little point in going forward with a solution.

After a project has been planned, contracts have been agreed upon and signed, the project starts with the project team. Depending on the size, the project team could include advisers, project leaders, developers and others.

The architect often have interactions with all of these roles in a project and their focus and responsibility is often the quality of the overall delivery. Architects are not the individuals who manages the projects and it’s resources, which is a whole different and challenging arena, which luckily as an solution architect, you normally avoid directly. Though it’s a constant battle to ensure the developers get the time, knowledge and tools they need to ensure the quality of a delivery, which is not compatibility with the goal of a project leader who first and foremost want to deliver on time.

Topics for the talk

These are some of my other potential topics on the agenda for my talk, there are so much to talk about on the subject of solution architecture, though I have only an hour and I’m interested in finding the topics that gives most value for my audience.

Topics: Security, Infrastructure, Products or Custom, Cloud Computing, Frameworks, Scalability, Tools, Why you should care about architecture, Become an solution architect.

What do you want to hear about?

Come to MSDN Live!

If you haven’t signed up for MSDN Live yet, it’s about time! The tour starts with Stavanger the 16th of April and ends 26th of April in Oslo.

I work as a senior solutions architect at Steria, who’s one of the partners for MSDN Live. Check out our stand at MSDN Live!


Service Orientation

One of the things that intrigues me with robotics and home automation in regards to software development, is the way things are more clearly defined and boundaries are very clear, compared to business or consumer software.

Doing business software often involves a lot of unknown factors which often are not clear until far into the development cycle. Requirements and functionality are often non-logical to a software programmer, and software are to often tweaked toward existing business models and processes.

While many (companies) strives toward a better future with service orientation in their business software, this is a process that takes time and is very exposed to some of the non-logical requirements from physical business processes that have been implemented in the organizations.

Service orientation in the field of home automaton and robotics is not as exposed to these problems. It is a lot easier to clearly define and build services that wraps easily understood physical concepts and products.

Take for example a lamp that is connected to an X10 switch. If it supports dimming you might have a integer value from 0 (off) to 100 (full) that controls how much light it should produce. You can easily write a HTTP based service for this, either using REST or SOAP protocol. When you have done so, you can forget about that service. The requirements doesn’t change, the business processes does change and inflict change in the service. The service implementation will be very stale, which is exactly what we want in a service oriented architecture.

When you have implemented service interfaces for some of your home appliances, you can begin the orchestration of your home to make it intelligent. If a person wakes up at 3 am the light should only be turned on with a value of 10%. You’ve obviously woken up in the middle of the night, perhaps by a nightmare :-)

As the same person wakes up at 8 am, the light should maybe turn on to 80% as it’s time to wake up and get ready for work.

I’m currently implementing a Web Service that allows me to remote control my Windows Media library from my mobile phone or my laptops. The service allows me the list my music albums with album arts and everything, and I can either playback the media on my local device, or tell it to play it directly on my Media Center PC which is hooked up to the stereo system.