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

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

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

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!