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

TOP

Complexity that rules us all

4184803610_ca1bcc685c_o Complexity is the number one cause [1] of failures on IT-projects. It’s probably the number one reason for any type of project failure. Failed projects and bad software makes our customers and users unhappy.

What are the reason we initiate IT-projects? It’s all about reducing complex problems to meaningful tasks that can be completed by humans.

Law of Software

Let’s focus on software development and what value software have for the users. Building software is what I and thousands of others are doing every single day, and we’re not exactly becoming better at what we’re doing, we’re actually only able to successfully complete aprox. 30% [2] of the projects that are initiated.

According to David S. Platt’s 3 Laws of Software, the software we build have zero value in and of itself. It doesn’t matter how technically good your code is, the only individual who cares are you and your own mother.

Platt’s 3 Law of Software [3] says the following:

1. Your software has zero value in and of itself. Only value it ever has is how it enhances the happiness of the user.

2. Software can increase users’ happiness in one of two ways. It can help a user accomplish a task that she wants done or it can give the user pleasure. Example: Outlook helps you read and write emails, HALO on the Xbox gives you pleasure and fun.

3. The users should not think about your computer program. At all. Ever.

(Click the link above to read the full law, I’ve just included the highlights)

What is writing software?

Writing software is the undertaking of understanding any arbitrary complex problem and writing software instructions to solve those complex problems.

The goal of writing software should be to reduce complex problems to simple tasks. Simple tasks that humans can initiate, often without requiring much need for thinking. The less the user is required to think, the happier and more productive they will be.

Thinking simple

When you have a complex problem you want to solve, what do we tend to use as mechanisms to solve them? It’s obviously not thinking in simple terms, this is pretty obvious when you look at the software we’re building.

As our understanding of a complex problem increases (as we work out the details of a software design), we can’t seem to be able to come up with simple solutions, we often take this route of thinking: Complex problems requires complex solutions.

This is wrong, and it’s the root cause of so many software project failures.

We need to start thinking simple. We need to figure out how we can reduce the complex details of a design, until we have an design and architecture that is as simple as possible and still delivers the value for our users.

Our goal should be: Least complex architecture possible [4].

There are many reasons why something ends up being complex, one important factor is the amount of functionality we put into our software. According to Robert L. Glass [5] in his book Facts and Fallacies of Software Engineering, the fact is as following, 25% increase in functionality increases complexity by 100%.

Next time you are faced with a complex problem that someone wants to be solved using software, start by thinking about the users and how you can increase their happiness. Then start reducing the initial complex solution of the complex problem, into the most simple solution you can which still achieves the goal: Making your users happy!

References

[1]: http://www.objectwatch.com/white_papers.htm#ITComplexity

[2]: The CHAOS report by The Standish Group (http://www.standishgroup.com/)

[3]: http://msdn.microsoft.com/en-us/magazine/ff646970.aspx

[4]: http://sondreb.com/blog/post/MSDN-Live-Solution-Architecture-Slides.aspx

[5] http://www.robertlglass.com/

[Photo]: http://www.flickr.com/photos/kodomut/

TOP

Extending Authentication on Facebook SDK

Using the Facebook Developer Toolkit (Facebook SDK), you can quickly get started building applications of any kind that integrates with the social networking service, Facebook.

I’m currently using this for the coming version of InTheBoks, which will from now on use Facebook Connect for authentication. While working on this integration, I realized that the Facebook Developer Toolkit never raises any events back to the Silverlight application when it loads the first time and tries to look for a persistent cookie. Learn how you can extend the toolkit so you can improve the user experience of your Silverlight applications that integrates with Facebook.

This post does not describe how to get started with the Facebook Developer Toolkit and Silverlight, this is just a quick way you can improve the authentication processes with Silverlight.

Requirements

First you need to get the source code for the Facebook Developer Toolkit. We need this so we can extend the BrowserSession.cs file.

BrowserSession

Start by extending the BrowserSession class with an event handler and one method that will be executed from the fblogin.js JavaScript file. Since we are editing an existing framework, we don’t want to change any existing implementations of code so we’ll add an extra event handler like this:

public event EventHandler NotAuthenticated;

The next step is to add an method that is called from JavScript:

[ScriptableMember]
public void NotLoggedIn()
{
    if (NotAuthenticated != null)
    {
        NotAuthenticated(this, EventArgs.Empty);
    }
}

fblogin.js

Open the fblogin.js file that is included with the Facebook Developer Toolkit and should be at the root of your web application that hosts your Silverlight app.

Find the function isUserConnected, which should look like this:

function isUserConnected() {
    FB.ensureInit(function () {
        FB.Connect.get_status().waitUntilReady(function (status) {
            var plugin = document.getElementById(‘_sl_facebookapp’);
            facebook_getSession();
        });
    });
}

Replace the above function with this updated one:

function isUserConnected() {

    FB.ensureInit(function () {
        FB.Connect.get_status().waitUntilReady(function (status) {

            var plugin = document.getElementById(‘_sl_facebookapp’);

            switch (status) {
                case FB.ConnectState.connected:
                    facebook_getSession();
                    break;
                case FB.ConnectState.appNotAuthorized:
                case FB.ConnectState.userNotLoggedIn:
                    plugin.Content.FacebookLoginControl.NotLoggedIn();
            }
        });
    });
}

That’s all you need to change to enable a way to get a callback when the JavaScript have checked if the user is authenticated or not.

Notes on the UI

With this additional event, you can now hook up to three events to update your UI. Here is the code from the constructor in my ViewModel.

_session = new BrowserSession(ApplicationKey, new Enums.ExtendedPermissions[] { Enums.ExtendedPermissions.offline_access });
LoginButtonText = "Loading…";
_session.NotAuthenticated += new EventHandler(Session_NotAuthenticated);
_session.LoginCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(Session_LoginCompleted);
_session.LogoutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(Session_LogoutCompleted);

I have a single HyperLinkButton that have it’s content bound to a string property named LoginButtonText. This is displaying “Loading…” when the app is loading, then depending on which event is raised, I change the LoginButtonText to “LOGIN” if the NotAuthenticated event is raised, “LOGOUT” if the LoginCompleted is raised and back again to “LOGIN” if the user logs out.

TOP

MSDN Live: Solution Architecture Slides

Here are the slides from my talk on Solution Architecture at MSDN Live in the spring of 2010. The slide decks alone isn’t enough to appreciate the presentation, so I have included all notes that was written for the presentation. This means you can read through the presentation and the points I made when delivering it in Stavanger, Bergen, Trondheim and Oslo. Download the full presentation or watch below.

For more background on the presentation, also read my blog post that I wrote during the preparations. The final result is very different than I initially planned and I didn’t deliver what was promised in the agenda. I still hope the presentation gave enough value to those who attended and I hope it inspired to enable change and sparked a move towards simpler solutions with reduced complexity.

Enjoy!