View localization with dynamics in MVC3

I ended up doing a good bit of Javascript and Ruby development lately and whenever I go back doing .NET afterwards I feel like things are getting in my way..

For instance the way localization is handled by .NET is a major pain point in all things I’ve been doing lately. WPF is probably the shining example of how not to do it (LocBaml? Serious?), but MVC3 also throws stones your way.

Problem is, that Views are not compiled – so you don’t get access to the static Resources.XXX properties from your Views. This is unfortunate and there are ways around that like using Helpers etc.

But I really grew fond of dynamic in C# for so I decided to simply use that to wrap the usage of my resources so I can write code like this in my Views:

@App.L10n.Product.Name

This is done by hanging my custom dynamic ResourceWrapper onto the dynamic ApplicationContext in Global.asax.

protected void Application_Start() { Application.Add("L10n", new MultiResourceWrapper()); … }

And my MultiResourceWrapper is simply wrapping all Resources existing in the MVC application on startup, and allows access to them through their name:

public class MultiResourceWrapper : DynamicObject { private readonly Dictionary<string, object> resources = new Dictionary<string, object>(); public MultiResourceWrapper() { var assemblyNamespace = this.GetType().Assembly.GetManifestResourceNames(); foreach (var s in assemblyNamespace) { var manager = new ResourceManager(ExtractResourceFullName(s), GetType().Assembly); var name = ExtractResourceName(s); resources.Add(name, new ResourceWrapper(manager)); } }

string ExtractResourceFullName(string s) { var regex = new Regex(@"(.*).resources$"); return regex.Match(s).Groups1.Value; }

string ExtractResourceName(string s) { var regex = new Regex(@"([a|A-z|Z]*).resources$"); return regex.Match(s).Groups1.Value; }

public override bool TryGetMember(GetMemberBinder binder, out object result) { result = resources[binder.Name]; return true; }

public class ResourceWrapper : DynamicObject { readonly ResourceManager manager; public ResourceWrapper(ResourceManager manager) { this.manager = manager; }

public override bool TryGetMember(GetMemberBinder binder, out object result) { result = manager.GetString(binder.Name); return true; } } }

As you can see all I need to do now to have localized strings for something is to add a Resource somewhere in my MVC application and then access it through it’s name from within the View.

One important thing though: I intentionally omitted any error handling code for the case where you mistype something. Nothing is more annoying than WPF bindings that simply don’t work because of typos, so having the app blow up with a YSOD is to me preferrable to a silent failure you have to spot later in deployment. But feel free to expand this to your liking.

The code is also available as a Gist from GitHub: MultiResourceWrapper.cs

Read more →

Redmine extensions

I may have just hit an all-time-low in lines-of-code per hour, but it was fun nonetheless, so I thought I’d share this with you:

A customer had the crazy requirement for his Redmine Ticketing system that users can enter their email address to a ticket and be notified alongside the user that is associated with the user account. (This also means that many users are sharing one user to create Tickets in the System)

The solution was quite simple in the end, but getting there for a total stranger to Rails was a bit challenging.

First I created a custom field in Redmine that is required on all tickets and contains the email address the email should be sent to.

Next I went into app/models/issue.rb and changed the recipients method like this:

# Returns the mail adresses of users that should be notified def recipients notified = project.notified_users # Author and assignee are always notified unless they have been locked notified << author if author && author.active? notified << assigned_to if assigned_to && assigned_to.active? notified.uniq! # Remove users that can not view the issue notified.reject! {|user| !visible?(user)} notified.collect(&:mail) << custom_field_values end

As you can see, all it took was to append the custom_field_values (assuming there is only one custom field!) to the list of emails that should be notified. Once that was done I just had to restart the ruby server and it worked.

If this looks hacky to you: It is. But the requirements didn’t really warrant any more work to be put into this.

Finally: Ruby is a fun language to work with, although it’s also rather hard to understand a complex project like Redmine if you are looking at it without any prior ruby knowledge.

What really got me in the beginning was that ruby has no return statement. Quite simply the last statement of a function is returned to it’s caller. If you don’t know that about the language, trying to understand what a function does get quite challenging :)

Read more →

Troubleshooting project type not supported in Visual Studio

I was tasked with fixing an old legacy component that has been developed for Windows Mobile. Although the source code was available, I was unable to open up the solution due to my Visual Studio not supporting the project type.

Initially I spent hours downloading and installing SDKs for Pocket PC hoping to fix the issue, but after exhausting every SDK from Windows Mobile 2003 through 5 to 6.5.3 I finally gave up.

I took a closer look at the .csproj file, trying to determine how to find out what project type I am missing.

Turns out the project type is saved as a GUID in your .csproj file and you can simply google for that project type to find out what tool/sdk it’s associated with.

Turns out, my Visual Studio was missing a 3rd party designer component, preventing me to open up the whole project in VS.

Anyway, in your .csproj search for the <ProjectTypeGuids> – You should see GUIDs seperated by semicolons that specify exactly what project types have to be present in your Visual Studio.

This clearly goes into the category named: “Stuff I wish I knew 5 hours ago”

Read more →

Required files to bin-deploy ASP.NET MVC3

I’ve been awfully busy writing a MVC3 application for a customer over the last month. Suffice it to say that there is a great deal of goodness in MVC3 that I really like. Especially the addition of some dynamic sugar to the overly strict and rigid MVC stack is a welcome change.

Anyway, when it came to bin-deploying MVC3 I was scratching my head a bit until I found Scott Hanselman’s post on what files are required. This has changed since beta so here is an updated list:

  1. Microsoft.Web.Infrastructure.dll
  2. System.Web.Helpers.dll
  3. System.Web.Mvc.dll
  4. System.Web.Razor.dll
  5. System.Web.WebPages.Deployment.dll
  6. System.Web.WebPages.dll
  7. System.Web.WebPages.Razor.dll

All of these files can be found in the following locations and can simply be copied to the /bin folder of your deployment output.

  1. C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies
  2. C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies

Although I really like what the guys did with MVC3, this sort of deployment is pretty sub-optimal. Having that many late-bound assemblies that you just need to deploy while not having any reference to it is a problem for me. That requires me to write custom deployment scripts that copy that stuff over, and I really don’t like that.

Let’s hope they include something in Visual Studio SP1 that lets the deployment wizard copy these files for you to the output directory.

Read more →

Eliminating SELECT N+1 in NHibernate without getting duplicate root entities

NHibernate makes it easy to do a lot of things in a natural and OO way without having to constantly think about tables and rows.

It just falls short on some occasions when you do something in your domain model that is fine from a design and OO standpoint but kills you in terms of database performance.

I ran into this problem with a fairly common use-case: Iterating over a list of orders and calling a method on them that operates on their OrderLines collection. Everyone knows: you don’t do that. Whenever you run that method, NHibernate knows you haven’t fetched the OrderLines collection yet and will issue a single SELECT query to get them for you so you can do your calculation.

In traditional systems this is the perfect place to use a stored procedure and push the calculation logic into the sproc. It’s just not something I fancy doing. You end up with your code scattered around the system, and at times your calculations simply don’t work inside the database.

Putting code in the database also makes it even harder to deploy the application because you have to think about deploying the database code too.

Well, now back to topic. If you run the following query on a Order table that has many OrderLines NHProf will warn you that you are doing a SELECT N+1.

var orders = session.CreateCriteria(typeof (Order)) .List<Order>(); foreach(var order in orders) { order.DoSomethingWithOrderLines(); }

The way to prevent this is to tell NHibernate explicitly to fetch all OrderLines through a Join.

session.CreateCriteria(typeof(Order))
    .SetFetchMode("Lines", FetchMode.Eager)
    .List<Order>();

This works, but you’ll end up with duplicate orders being returned by NHibernate. This is due to the query you are running that will join each OrderLine with it’s order, resulting in one Order per Orderline (with a lot of duplicates).

But NHibernate is smart, and the information you are getting from the query is enough to construct the right objects, although some unnecessary data is coming over the wire. As with most things, you only need to tell NHibernate how to do it right. In our case that’s to only return distinct orders instead of duplicates through a result transformer:

var orders = session.CreateCriteria(typeof(Order)) .SetFetchMode("Lines", FetchMode.Eager) .SetResultTransformer(new DistinctRootEntityResultTransformer()) .List<Order>();

The result-transformer will eliminiate all duplicate root elements (in our case Order) while populating the child-collection accordingly. Resulting in only one query being run.

Read more →

Displaying different screens with ContentPresenters in Silverlight

In WPF you can use a ContentPresenter with DataTemplate to display different Views for different ViewModels. And although writing those DataTemplates gets old pretty quickly (and you resort to frameworks or roll your own code to alleviate that problem), I do like to use them in small demo apps at times.

Silverlight does not support DataTemplates with types on them, so you can’t use ContentPresenters like you would in WPF.

But in this case it helps to understand what a DataTemplate is doing in WPF to easily replicate that behavior in Silverlight. DataTemplates (in this case) are little more than Converters that take objects and supply a template that is then used to display that object to the screen.

Once you know that, it gets rather simple: Simply implement IValueConverter and return a Silverlight UserControl in the Convert method.

You can even write something as simple as this:

public class ViewConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.GetType() == typeof(NewCustomerViewModel))
        {
            return new NewCustomer();
        }
        if (value.GetType() == typeof(CustomerListViewModel))
        {
            return new MasterDetail();
        }
        return null;
    }

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }

Once your Converter can translate ViewModels (or any object) into Views you can then bind your ContentPresenter to use that Converter:

<ContentPresenter Content="{Binding ActiveScreen, Converter={StaticResource ViewConverter}}" />

You would obviously not want to use the code above, but rather hook your ViewConverter into your Inversion of Control container or something similar (or just use Caliburn.Micro).

There are a number of UI frameworks out there that make writing complex MVVM applications a lot easier. Caliburn, Caliburn.Micro and Prism. I tried some of them and I really liked them, but I found that you should really learn how Silverlight/WPF works before you resort to these Frameworks, as most of their features only start making sense once you start understanding the problems those frameworks set out to solve.

Read more →

Theming controls in WPF

My biggest grief with WPF is the way how twisted XAML works. It takes a lot of time getting used to it, and it’s by no means obvious how to do stuff.

So this is the story of how to change the appearance of a control from some common resource for controls.

Styles and Setters

Most of the things you’d consider styling (as known from CSS) can be done via Styles that contain setters.

Inside a ResourceDictionary you can define styles for all controls of a type, or have them be applicable by a key. This is pretty similar to CSS where you can apply settings either via class (by key in WPF) or by elementType (TargetType in WPF)

Let’s look at some code:

.highlight {
	color: Red;
} 

translates into the following XAML:

<Style x:Key="highlight"> <Setter Property="Foreground" Value="Red" /> </Style>

Inside a <Style> you can change any property on the target element, in our case the Foreground property that accepts a display brush.

Note that omitting the TargetType property limits you to only properties on FrameworkElement so you might want to define something more specific like TargetType="TextBlock" etc.

If you don’t specify a x:Key the style will be applied to all possible elements matching the TargetType.

Let’s look at CSS and XAML side-by-side:

span { color: Red; }

is roughly the same as:

<Style TargetType="TextBlock"> <Setter Property="Foreground" Value="Red" /> </Style>

Templates

Now we know how CSS (at least in a way) maps to XAML. Things are still pretty different and one of the things that you need to wrap your head around in XAML is templates.

Every control you drag to the surface is usually a collection of borders, shapes and other lower level framework stuff that makes up your control.

So if you want to modify the appearance of your control, you do that via the ControlTemplate. And this is where I am still not 100% sure what the common theme is, but I am getting better at it.

ControlTemplates can be applied either directly to the element, or via a Style inside a Setter.

<Style TargetType="TextBox"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TextBox"> <!-- Your Template goes here --> </ControlTemplate> </Setter.Value> </Setter> </Style>

As you can see, all you do inside a <Setter> is pretty much the same as you would apply to the element itself in markup. If you have non-trivial values to set you can use the as you can do with almost all things in XAML.

This is actually an interesting concept that took some getting used to. In XAML you can specify each and any attribute of the element by using the <Element.AttributeName> syntax in case it’s not expressable by a simple literal value.

Now let’s assume I want to change the appearance of a TextBox to have a flat border. If you come from WinForms like me you’ll spend a fair amount of time hunting for a BorderStyle property that’s simply not existant in WPF.

The way to go here is: You guessed it, Control Templates.

The ControlTemplate allows you to replace the visual tree of your object and roll your own that suits your needs (makes it powerful, but rather hard to figure out). My naive approach to this was to simply define the border in WPF like this:

<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border Name="Border"
	BorderThickness="1"
	Padding="4,2"
	Height="Auto"
	BorderBrush="#FFCCCCCC">
</Border>
</ControlTemplate>

What happened was that I turned my TextBox into a border. No text entering, nothing. I changed the visual tree of the object to only contain a border, and that’s what I got.

It then took me a little while to figure out that you can’t simply change the tree without putting back in an element to write the text to. Apparently for textboxes you have to put in a ScrollViewer named PART_ContentHost.

So the correct way here is:

<ControlTemplate TargetType="{x:Type TextBoxBase}"> <Border Name="Border" BorderThickness="1" Padding="4,2" Height="Auto" BorderBrush="#FFCCCCCC"> <ScrollViewer x:Name="PART_ContentHost" /> </Border> </ControlTemplate>

This then gives us a nice flat border with 1 pixel thickness and a nice shade of gray instead of the gradient brush WPF uses by default.

Triggers

Another very important concept (at least to me) was triggers. Assuming we made our control look pretty, we may want to change it’s appearance once you mouseover it or focus it.

If you try like me using the VisualFocusStyle to do that you’ll soon notice that VisualFocusStyles are not applied when a user clicks the element, only when he navigates to it by keyboard. It was meant to provide UI hints for keyboard navigation, not to indicate focusing in any way.

The correct way to do stuff like OnFocus and OnMouseOver is by using Triggers. With triggers you can do something whenever a property matches a certain value. So in our case we can create a trigger that changes the border color whenever the IsFocused property contains the value True.

I am applying the trigger to my ControlTemplate we defined earlier:

<ControlTemplate.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter TargetName="Border" Property="BorderBrush" Value="#FF00A9DA" /> </Trigger> </ControlTemplate.Triggers>

This trigger now only works with one Property/Value, IsFocused. But there is a way to verify that two conditions are met before the trigger fires using the MultiTrigger.

The concept is the same:

<MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsMouseOver" Value="True"></Condition> <Condition Property="IsFocused" Value="False" /> </MultiTrigger.Conditions> <Setter TargetName="Border" Property="BorderBrush" Value="Black" /> </MultiTrigger>

This MultiTrigger will only apply the black BorderBrush if IsFocused is false and IsMouseOver is true. Thus making sure the IsFocus style is not overridden and flickering whenever the user waves the mouse around.

DataTriggers

Triggers are only good for one thing: Firing if properties on the Visual Tree change. If you want to do something when something in your DataContext changes you need DataTriggers. These work by defining a Binding and a Value, but in essence work pretty much like normal Triggers, only that they work on anything you can bind to.

DataTriggers also come along in MultiDataTrigger and DataTrigger flavors.

DataTriggers are also the answer to most questions concerning MVVM asking “How can I show X from my ViewModel.”. The answer here is usually: "Define some boolean property (with INotifyPropertyChanged) and set up a DataTrigger to it. (This works for starting animations etc.. Everything.. This is crazy powerful!)

And that’s about all the stuff I spent most of my morning figuring out. I hope you get any useful information out of it. Because I quickly became frustrated with the content that’s out there.

Read more →

New website for dotless is up at www.dotlesscss.org

After some trouble with our previous hoster the old domain www.dotlesscss.com went offline.
Chris tried to resolve this issue, but things didn’t work out so the website was offline for almost 2 months now.

We where not completely offline since, I migrated the website to GitHub Pages some time ago and all documentation was moved over to the new GitHub Wiki. But we were still missing our shiny domain name we could point people to.

So I finally decided to give up on waiting for our old domain to come back and registered a new one:

http://www.dotlesscss.org

The old site is now available at the new name and we are trying to update all references to the new .org domain.
(And .org is more fitting for an OSS project anyway).

As for the project itself, I am planning a 1.2 release fairly shortly that should incorporate a ton of bug fixes and some improvements we made since version 1.1.

Please spread the word about this domain change. Thanks!

Ps: On a technical side, the new website is now powered by Jekyll on GitHub and the source is contained in the gh-pages branch on our GitHub repository.

Read more →

Getting System.BadImageFormatException and no clue what&apos;s wrong?

What’s the default target platform on the .NET environment? Yep, it’s AnyCPU, meaning that a flag is set in your assembly file that specifies “this IL code can be either compiled into x64 or x86”, and the executing .NET framework will then decide what platform to choose based on the OS that’s running.

If you are running on a Win7 x64 machine you’ll execute a native x64 application, if you run on a 32 bit Windows you’ll run a 32 bit application.

When in doubt you’ll want to default to AnyCPU and only switch to x86 or x64 explicitly if you are doing some native P/Invoke or other weird stuff. So for 90% of developers AnyCPU is the perfect target platform and they don’t even know what goes on behind the scenes. They just compile once and run on any Windows with a .NET framework.

Now they screwed it up!

Whenever you create a new Project in VS2008 it will default to AnyCPU, everyone is happy.

Fast forward, VS2010 comes along and changes this default behavior:
In Visual Studio all class libraries default to AnyCPU, but all WPF Applications and Console Applications default to x86

Do you see the implications here? You start out with a clean AnyCPU solution like this one:

Once you add a Console Application you end up with:

As you can see, for no good reason (it’s only two blank projects after all) Visual Studio changes the platform to Mixed and sets the ConsoleApplication to x86!

Why is this so bad?

Well, if you are running on a x64 machine, and try to run unit tests inside your library project (as most of us do) you end up running a x64 process that is linked to a x86 assembly!

You don’t need to be a genius to figure out that this is not going to work. You’ll see a System.BadImageFormatException pop up with no good explanation. (Apparently the Platform dropdown in the Toolbar was also removed in VS2010!)

The “reason” for this crap

This is the explanation DJ Park (C# IDE, Program Manager) gives on Microsoft Connect about the change of the defaults:

To provide some context, the motivation for the change is to alleviate the pain that customers are feeling when developing on a 64-bit OS – some examples being Edit and Continue (EnC) and P/Invoke scenarios. To elaborate on the EnC example, EnC is supported on a 64-bit OS provided that you’re debugging a 32-bit process. However, by defaulting to AnyCPU, processes are automatically run as 64-bit, which means that EnC will not work unless you change the platform target to be x86

Have you ever used Edit and Continue? Hell I mostly run without a debugger attached and they are doing stupid things like that because they want to allow me to change code while I debug a program. Are you kidding me?

Not to mention the hilarious post quoted that tries to argue that AnyCPU is usually not worth it. Listing reasons 99% of programmers don’t care about at all.

Just to round this up: If you compile something to x86, you can still run it on a x64 Windows. Windows features a x86 “emulation layer” called Windows on Windows (it’s inside your C:\Windows\SysWOW64 folder) that allows you to run x86 applications on a 64 bit operating system. It works, but why would I want an abstraction layer if I could just as easily run a native 64 bit application on my 64 bit OS?
We are talking about a change of runtime characteristics for a tiny facilitation in development, and that’s not good in my opinion.

Read more →

Measure execution time in PowerShell

I have no idea why, but although having been a Windows user for most of my career, I know the unix commandline pretty well. In fact, one of the best things in Powershell was the ls alias to the Get-ChildItem command.

Naturally, Microsoft could not include an alias for every unix command out there, so I spend a fair amount of time hunting down the Powershell equivalents to Unix commands whenever I need one.

This time it’s the time command that allows you to measure how long the execution of a particular command took. The Powershell equivalent is called Measure-Command and does exactly the same thing, returning a System.TimeSpan.

For example, to measure the execution time of a git checkout:

Measure-Command { git checkout gh-pages }

Switched to branch ‘gh-pages’

Days : 0

Hours : 0

Minutes : 0

Seconds : 0

Milliseconds : 344

Ticks : 3448544

TotalDays : 3,99137037037037E-06

TotalHours : 9,57928888888889E-05

TotalMinutes : 0,00574757333333333

TotalSeconds : 0,3448544

TotalMilliseconds : 344,8544

I considered creating an alias for Mesaure-Command to just time, but the usages are so rare that it’s not really necessary.

Read more →