TOP

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!

TOP

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 http://sondreb.com/blog/feed

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, sondreb.com.

TOP

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: http://forums.asp.net/t/1580303.aspx

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
    {
        get
        {
            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.
        set.Load();

        // 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\"");
        Response.End();
    }
    
    var repository = new Repository<BlogCatalog>(entityType);
    var result = repository.LoadAll();
    Page.Model = result;
    
    var grid = new WebGrid(Page.Model);    
}

@grid.GetHtml()

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.

Result

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.

TOP

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:

Author

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:

http://url/Admin/EntityTypeName/View/FriendlyNameOrId

One example then, would be for the authors:

http://url/Admin/Author/View/admin

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.

Url

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.

TOP

Code Like A Girl

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 http://www.zazzle.com/code+like+a+girl+gifts.

TOP

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.

cirium:Resource.Key="About"

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.

SimplifyResources_source

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.

SimplifyResources_screenshot

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.

<SupportedCultures>en-US;nb-NO</SupportedCultures>

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 =

            DependencyProperty.RegisterAttached(

                "Key",

                typeof(string),

                typeof(string),

                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 =

            DependencyProperty.RegisterAttached(

                "Tooltip",

                typeof(string),

                typeof(string),

                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);

            }

            else

            {

                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;

        }

    }

}

Notes

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]

TOP

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)
	{
	Response.Write(user["Name"]);
	}
	

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)
	{
	Response.Write(user.Name);
	}
	}
	

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=
res://*/Model1.csdl|
res://*/Model1.ssdl|
res://*/Model1.msl;
provider=System.Data.SqlClient;
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: http://blog.twitter.com/2008/05/its-not-rocket-science-but-its-our-work.html

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.

TOP

Unity as IoC container for Caliburn.Micro

You might have heard about Caliburn, a client framework for WPF and Silverlight. Caliburn is a very rich and featured framework, as a consequence of this the, the great programmer Rob Eisenberg have reset the full Caliburn with a new and fresh one, named Caliburn.Micro.

Caliburn.Micro is smaller, more lightweight and it has a lot of good features that I think are useful when building rich applications for WPF, Silverlight and Windows Phone 7.

Caliburn.Micro have a focus on convention, meaning that it will automate a lot of the tedious tasks you normally have to do when you’re applying design patterns such as Model-View-ViewModel (MVVM, Presentation Model). Actions (commanding) can be achieved simply by naming your ViewModel operations with the same name as your Buttons and other action-controls in the View.

This new framework can reduce the complexity of your applications and make them cleaner and more adaptable to change in the future. Reducing complexity should always be one of the top priorities when building software.

(Note: The content of this article will probably become outdated as the Caliburn.Micro documentation is updated, though at the current time this is the only known example of IoC with Caliburn.Micro)

(Note July 9th 2010: As expected, Rob Eisenberg has updated the Caliburn.Micro documentation with an bootstrapper which uses MEF. If you’re a MEF-kind-of-programmer, check it out. I would still advice on using the Common Service Locator in the bootstrapper as oppose to directly working with the MEF-types. I don’t like binding my types to a specific IoC container, which you are with the MEF-attributes on your types and properties. With some IoC frameworks, you can simply use any custom interface and have your objects injected using Dependency Injection)

Inversion of Control

Inversion of Control is a pattern which helps separate the responsibility of creating objects from the classes which uses them. This can greatly enhance the way you can build a modular application which easier supports replacing existing logic and makes testing a whole lot simpler.

To learn more about IoC, see http://msdn.microsoft.com/en-us/library/ff647976.aspx

Building Caliburn.Micro

At the present time, there is no binary release of Caliburn.Micro available. You have to download the source code and compile it yourself using Visual Studio 2010. Head on over to CodePlex to get the source, http://caliburnmicro.codeplex.com/SourceControl/list/changesets

Caliburn.Micro is released under the MIT license, which means you can basically do almost anything you want with the source, even include it in your own product which is not open source. When you open the Caliburn.Micro solution file, you’ll see three projects, one for Silverlight, one for WPF and a last one for Windows Phone 7 (WP7).

Downloading Unity

Before you can continue to add IoC support for your WPF application, you need to download your favorite IoC framework. My favorite is Autofac, but for this demo I’m using Unity which is developed by the Microsoft patterns & practices group. Get the latest release from http://unity.codeplex.com/

Creating a new WPF project

Go ahead and create a new WPF project or open any existing project you might have. First step is to add reference to the following assemblies: Caliburn.Micro, System.Windows.Interactivity (included with Caliburn.Micro and my sample download at the bottom), Microsoft.Practices.Unity and finally the Microsoft.Practices.ServiceLocation. The ServiceLocation assembly is a common service locator assembly that has been built to provide a unified interface for all IoC frameworks.

Next you should follow the example in the documentation for Caliburn.Micro, it explains how to get the basic application up and working, see http://caliburnmicro.codeplex.com/wikipage?title=Basic%20Configuration%2c%20Actions%20and%20Conventions&referringTitle=Documentation

Creating a Container

If you got your basic application up and running with an empty bootstrapper, it’s time to create your IoC container. Create a new class in your project and name it Container. Create a single method can call it Build, returning IServiceLocator (found in the Microsoft.Practices.ServiceLocation namespace). This makes it possible for you to reuse this container type across other third party libraries which happen to play nice and supports the Common Service Locator.

    public IServiceLocator Build()
    {
        IUnityContainer unity = new UnityContainer();

        // Register our services.
        unity.RegisterType<IFileService, FileService>();

        // Register all the ViewModels in our project.
        foreach (Type t in typeof(ViewModel).Assembly.GetTypes())
        {
            if (typeof(ViewModel).IsAssignableFrom(t))
            {
                unity.RegisterType(t);
            }
        }

        // Return an type which implements the Common Service Locator interface.
        UnityServiceLocator commonLocator = new UnityServiceLocator(unity);
        return commonLocator;
    }

Finishing the Bootstrapper

If you followed the example on the Caliburn.Micro site, you should have a empty bootstrapper. I called mine ClientBootstrap and it loads my ShellViewModel as the root element.

There are four operations you need to override to add your custom IoC container, they are Configure, BuildUp, GetAllInstances and GetInstance. If your Container class returns an IServiceLocator, you already have similar methods available. The only thing missing is the BuildUp. Unfortunlately there are no operation in the Common Service Locator interface for BuildUp, so either you have to revert to returning the IUnityContainer from your Build operation, or you might make it without the BuildUp override.

This is how my bootstrapper ends up looking.

    public class ClientBootstrap : Bootstrapper<ShellViewModel>
    {
        IServiceLocator _container;

        protected override void Configure()
        {
            Container container = new Container();
            _container = container.Build();
        }

        protected override void BuildUp(object instance)
        {}

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _container.GetAllInstances(service);
        }

        protected override object GetInstance(Type service, string key)
        {
            return _container.GetInstance(service, key);
        }
    }

Source Code

You can download the sample source code here. This sample is named “Flickr Downloadr” for the simple reason that I’m rewriting my popular photo download utility to WPF4, check out the existing version at http://flickrdownloadr.codeplex.com/

TOP

View Model Loading by Convention

Following up on my previous post on how you can achieve no code-behind for your WPF or Silverlight application, I will explain one possible way of doing view model instantiation using any Inversion of Control container and using a naming convention to do it automatically.

MVVM Project Structure

InTheBoks_structureOne of the first things you learn when searching for training material on MVVM in the context of Silverlight and WPF, is that many developers tends to chunk all their View Models and Views into a single project folder. This might work for a small project that has a minimal set of views, but for any bigger projects this will quickly become a mess so my advice is to avoid it altogether, you never know if your project will expand beyond your initial plans.

Either create a root-folder for all of your functional areas, or create a root-folder that contains all your features. I like to use the convention of a folder named simple “Features”. Within this folder, I create another folder for each distinct functional area of my app. Each functional feature can easily contain one or multiple views and view models.

On the right you can see an screenshot of the current structure for my InTheBoks project, where the ViewBase.cs from my previous blog post is stored under a Framework section.

With this structure, your View (e.g. MainView.xaml) and your View Model (e.g. MainViewModel.cs) will end up under the same .NET namespace, which is important when we want to load the view model by-convention.

What does by-convention mean? It’s simply figuring out the full type-name for the view model by following a defined project structure where we no longer need to manually connect the view and the view model.

Expanding the ViewBase

It’s time to expand the ViewBase we first defined in my previous post on No Code-Behind for MVVM. Inside the constructor of my PageView, UserControlView, WindowView (WPF) and ChildWindowView (SL), I set the DataContext with a call to an ViewBaseHelper class. This is done right after the InitializeComponent has been called using reflection.

DataContext = ViewBaseHelper.Instance.LoadViewModel(GetType());

The full source for my ViewBaseHelper is of course included in the sample download at the bottom, but here is the essential part that tries to load your View Model automagically:

internal object LoadViewModel(Type viewType)
{
    if (viewType == null)
    {
        return null;
    }

    var viewModelTypeName = viewType.AssemblyQualifiedName.Replace(viewType.FullName, viewType.FullName + "Model");

    var viewModelType = Type.GetType(viewModelTypeName);

    if (viewModelType == null)
    {
        return null;
    }

    return Container.Resolve(viewModelType);
}

In my example code I have relied upon Autofac as my choice for Inversion of Control container. The code that handles dependency injection is fairly small and can easily be replaced with an alternative IoC container.

What about design-time?

The method I’ve explained for convention based view model loading doesn’t work for design-time, which fortunately we have a solution for.

While this method does break somewhat with the idea of not directly binding the view to any view model type, this is only for design time and it can be very useful as you have a finer degree of control on which type you bind your view against and how you want it to be initialized.

All you need to do is add an d: element (which is ignore during compilation) which specifies the view model type and whether you want to create an actual instance of the VM or not. Here is an example from my MainView. First you need to import the namespace on which the view model is located and then set the d:DataContext attribute. IsDesignTimeCreatable is used to indicate if you want an object instance of the VM type.

xmlns:Feature="clr-namespace:InTheBoks.Features.Main"
d:DataContext="{d:DesignInstance Type=Feature:MainViewModel, IsDesignTimeCreatable=True}"

asd

Create new Feature

One of the additional things I’ve done for InTheBoks, is to create templates for new features which creates the view and the view model with proper inheritance, namespace imports, and design-time binding. To do this yourself, simply add the correct .zip file with your template items in the following folder:

\Visual Studio 2010\Templates\ItemTemplates\Silverlight

I won’t go into further detail on this today, though this is a good thing to do if you’re working on a big project that has many views. This is how it can look when you customize your items with icons and illustrations.

InTheBoks_feature

Download the Source Code

While my previous example was built around WPF, this new one is built using Silverlight. As this concept and code is built around InTheBoks, the name of the sample and the namespace is “InTheBoks”.

The sample doesn’t include any advanced MVVM-technologies such as commanding, only the one that is built into Silverlight 4 which is binding. For the purpose of clarity, I removed any other external dependency than Autofac.

Here is the download: InTheBoks-2010-06-20.zip.

TOP

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()
    {
        InitializeComponent();
    }
}

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.

xmlns:NoCodeBehind="clr-namespace:NoCodeBehind"

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

<NoCodeBehind:WindowView 

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#.