I blog whenever I C#

A really nice feature in Resharper 5 is the ability to adjust namespaces for code files in a directory. When you move files around in your project or between different projects the namespace no longer matches the directory structure. Updating the namespaces in the code files by hand is quite tedious and error prone. This is especially true when you move user controls or web pages that consists of a XAML file or ASP.NET page with a code behind class that needs to match.

You can adjust the namespace for all files in a directory by simply right clicking the folder in Visual Studio and select “Refactor->Adjust Namespaces…”:

image

This will give you the following dialog where you can see the changes that Resharper suggests:

image

Quite handy I think!

The Managed Extensibility Framework is a new wonderful addition to .NET 4 and Silverlight 4. The main purpose of MEF is to handle the extensibility and plug-in capability of an application. It features a very simple and elegant method for creating objects and resolving dependencies by decorating your code with import and export attributes.

Managing and resolving dependencies and creating objects is pretty much what a simple IoC (Inversion of Control) container does. So, can we use MEF for this?

The MEF man Glenn Block once said that ”you should use MEF to manage your unknown dependencies and an IoC container to manage your known dependencies.” However, I have found that MEF can work pretty well as your one stop solution for all dependencies. It is especially nice if you are building a Silverlight application that already uses MEF (for example to download XAPs dynamically). Why include a separate third party IoC container when there is one built in already?

Here is a short guide for those who want to use MEF for dependency injection in Silverlight.

MEF libraries

First of all, you need to add a reference to the MEF libraries. They are included with Silverlight 4:

image

System.ComponentModel.Composition – You need this reference anywhere you use the basics of MEF such as importing and exporting.

System.ComponentModel.Composition.Initialization – You need this reference where you actually initialize and configure the container.

ServiceLocator class

To use MEF for resolving dependencies I have built a simple class to set things up and provide a way to create or retrieve instances. This is the code for a simple version of this class:

    public static class ServiceLocator
    {
        private static CompositionContainer _container;
        private static AggregateCatalog _catalog;

        public static void Initialize()
        {
            _catalog = new AggregateCatalog(new DeploymentCatalog());
            _container = CompositionHost.Initialize(_catalog);
        }

        public static T GetInstance<T>()
        {
            return _container.GetExportedValue<T>();
        }
    }

The Initialize() method sets up an AggregateCatalog and feeds it with a DeploymentCatalog. The AggregateCatalog can contain many MEF catalogs that are added at runtime. Using an AggregateCatalog is not absolutely necessary in this simple example but it is a preparation for loading dependencies dynamically in the future.

The DeploymentCatalog is used in Silverlight for working with XAP files. It is a very handy class for loading external XAPs if your application is split up in modules. Creating a DeploymentCatalog without any parameters will create a catalog for the main application XAP file and this will allow us to access the exported types in all the assemblies of our main XAP file.

When we call CompositionHost.Initialize() our assemblies will be scanned by MEF and all exports are discovered. We are then ready to call the GetInstance<T>() method whenever we need an instance of an exported class.

Exporting types

Traditional IoC containers often involve configuring components using either XML or registering them using code. With MEF you simply put an [Export] attribute on your class to indicate that it should be available for composition:

    [Export]
    public class Car
    {
        ...
    }

This will expose the type Car to MEF and lets you retrieve it in IoC fashion like this:

    var car = ServiceLocator.GetInstance<Car>();

Often you want to expose a certain interface that your type implements. You can do this by supplying the type in the [Export] attribute like this:

    [Export(typeof(ICar)]
    public class Car : ICar
    {
        ...
    }

The default behavior in MEF is to treat exports as singletons. That is, if you don’t specify anything to override this behavior you will only get one instance of the Car object in your application no matter how many times you call GetInstance<Car>(). Actually, if the exported type does not specify anything the default is to allow either singleton or non shared so it is up to the caller to decide what he wants.

If you want unique instances to be created every time you retrieve an instance of your type you can specify this using an extra attribute on your class:

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class Car
    {
        ...
    }

Dependency injection

Of course an application is seldom built with only a single class. Most likely you have many parts that fit together and you want to use the IoC container to resolve everything smoothly for you using dependency injection. MEF can do this as well, but you have to decorate the constructor to use with the [ImportingConstructor] attribute:

    [Export]
    public class Car
    {
        [ImportingConstructor]
        public Car(Engine engine)
        {
        }
    }

    [Export]
    public class Engine
    {

    }

When retrieving a Car instance MEF will automatically create and inject the Engine in the constructor of the class just like an ordinary IoC container would.

All in all, those 20 lines of code is all you need to get started with MEF as an IoC container. You can now retrieve instances of your objects with injected dependencies and that’s pretty much what you need in most cases.

Conclusion

I wanted to keep this example as simple as possible and have deliberately left out topics like object lifetime, dynamically loading XAPs and so on. I am planning to write about those things in upcoming posts.

I think MEF provides a great alternative to the traditional IoC containers. It is very easy to setup and get started with. I also like the fact that all configuration sticks with the class, which makes it easy for newcomers in your project to pick things up quickly and write new components simply by looking at an existing class.

I believe MEF is going to be central in all .NET 4 development. Don’t miss out!

image I’m finally back home after a crazy and wonderful week visiting MIX10 in Las Vegas. It was a great conference and I really had a good time watching the sessions and meeting people. I got the chance to talk to Brad Abrams, Nikhil Khotari and Colin Blair about WCF RIA Services, chatted with the devs working on Bing, talked to Pete Brown about his cool C64 emulator built in Silverlight, met Roland Weigelt who created the wonderful GhostDoc add-in for Visual Studio and got a tip about Sonic File Finder from his friend. All in all the atmosphere was great and a lot of the speakers and people from Microsoft were hanging around chatting with people all the time which I think was great.

So what impact did MIX10 had on me personally? Well, after doing some thinking I want to present the five most important things that made an impression on me:

1 – Windows Phone 7

image

Microsoft is really pushing the new version of their mobile phone OS. Yeah, they have stolen a lot of ideas from Apple but it’s not the first time Microsoft does that. Copying a successful concept is also a way of making business. However, they’ve introduced some really great innovations as well, improved some of the shortcomings of the competitors and I must say that the phone UI feels really slick and modern. I could actually see myself using this instead of my Iphone! :)

What made me really interested in the phone is the fact that it seems so simple to get started with developing for it. Since it runs Silverlight it is really easy to get an application up and running if you’re familiar with .NET development. This is radically different from developing for the Iphone or Android for me. It also supports writing applications in XNA which is a great framework for developing more advanced applications like games.

Additionally Microsoft has released the tools for free so you can build apps with no up-front investment at all. That’s a pretty nice deal for such great tools as Visual Studio and Blend.

http://developer.windowsphone.com/

2 – OData

image The Open Data Protocol (or OData for short) is a pretty awesome concept that Microsoft presented at MIX10.

Many successful internet businesses today enable their users a rich web API that is used to access their service in many different ways with various clients. The web browser is only one type of client in a larger ecosystem of mobile phones, desktop applications and other devices that wants to work with data over the web. Twitter is an example of this, where they only provide a rudimentary interface on the website and the entire experience is greatly enhanced by a large variety of clients available for different platforms.

OData is a REST based API that aims to be a standard way of accessing services over the web. Microsoft enables you to easily expose an OData interface from your ASP.NET application as well as client libraries for consuming OData from various environments. They obviously provide a .NET and WP7 client libraries, but surprisingly they have developed libraries for accessing OData also from PHP, Java and Iphone. That’s really neat!

Another cool thing is a service that goes by the name Codename “Dallas”. This is Microsoft’s solution for people to expose and make money off their data. Even if you’re a small one man business you can take advantage of this and make money if you have something interesting to share. One guy I met in the “RIA Services suite” had a lot of historical baseball data that he wanted to share and I think he could make some money with data.

Check out the keynote from day 2 at about 59:00 for a demo of this stuff:

http://live.visitmix.com/MIX10/Sessions/KEY02

3 – Azure

I saw some demos of Azure at MIX10 and it is starting to look really smooth. I haven’t really had the time to try it out yet but it is looking more and more compelling. Previously I’ve heard that it’s been quite instable and buggy but it looks like that has been straightened out. Maybe it is finally time to start building stuff for the cloud now! :)

I really like that you can test your stuff out in the “DevFabric” which is a simulated cloud environment on your dev machine. Then you can for example start by moving up your data storage to the cloud while still running the code on your dev machine and continue testing your solution, and when you’re ready you move it all up into the cloud. It all seemed really simple and all you need to do to get started is to install the Azure SDK which is available from here:

http://dev.windowsazure.com/

4 – IE9

image Microsoft is really taking a leap forward with version 9 of Internet Explorer. IE has lost a lot of users the past years and Microsoft is really committed to improving its performance and standards compliance. It was interesting to see a demonstration of cases where the new IE version really shines in a head to head comparison with other browsers, especially Google Chrome (which is one of the fastest browsers at the moment). Competition like this is really good for the browser market. At the same time Microsoft is really trying to help out its competitors by setting up this website with test cases that they can run to check their performance.

Some notable things about IE9 is the GPU accelerated HTML5 and better standards compliance, for example with rounded and dotted CSS borders…Examples can be found at this address: http://www.ietestdrive.com/

Also check out the keynote from day 2 where they start off talking about the new IE9 engine: http://live.visitmix.com/MIX10/Sessions/KEY02

5 – MVVM

The Model-View-ViewModel design pattern has been around for a while but it is now finally gaining more and more attention among Silverlight developers and most importantly in the tools coming from Microsoft. The new version of Blend will have some really useful features for working in a MVVM oriented way like for example being able to generate sample data based on a ViewModel class in your project.

I watched a couple of great sessions about MVVM at MIX. If you want to learn more you can check out the introductory session by Laurent Bugnion:

http://live.visitmix.com/MIX10/Sessions/EX14

I also saw the session by Rob Eisenberg and was deeply impressed by his elegant solutions and ideas:

http://live.visitmix.com/MIX10/Sessions/EX15

Conclusion

Okay, so that’s a list of things that I found most important at this conference. Of course, there was a lot more going on so I recommend that you take a look at all the videos that have been released and find the things of interest to you:

http://live.visitmix.com/Videos

Feel free to comment if you think I’ve missed something significant!

Just recently we had some problems compiling XAML files in our Silverlight project. The files had been copied from one project to another class library and after renaming and refactoring the namespaces we still got compilation errors. The error we got was something like this:

The name ‘xxxxx’ does not exist in the current context

Visual Studio was complaining about code in our codebehind file. Apparently it could not find the controls that we had in our XAML although we were absolutely sure that they were there…

It turned out to be quite simple to solve. When we copied the files between projects Visual Studio changed the build action to “ApplicationDefinition”. This is clearly not right (may be a bug in VS2010). User controls should have a build action set to “Page” like this:

image

I hope this helps!

Here’s a little tip for those of you looking for a good diff/merge tool. It works quite well with both TortoiseSVN and Git Extensions and I’m sure it works with other applications as well.

Some of you may have heard of Perforce. It’s a pretty expensive source control system that is used by Google among others. I have never used it myself but I guess it’s ok. What I do know is that they have a great tool called P4Merge for merging and checking file differences. Best of all is that you can use it for free!

This is what a comparison looks like:

P4merge file comparison

Installing

To use P4Merge you need to install the Perforce Visual Client which is available as a free download from the Perforce download page. Make sure you get the right version for your system.

When you install it you can uncheck all the other tools and just install P4Merge:

P4merge installation

TortoiseSVN setup

To use P4Merge with TortoiseSVN you need open the TortoiseSVN settings and configure Diff Viewer and Merge Tool like this:

Diff Viewer:
“C:\Program Files\Perforce\p4merge.exe”  %base %mine

Merge Tool:
“C:\Program Files\Perforce\p4merge.exe” %base %theirs %mine %merged

Here’s how it looks for the Merge Tool setting:

TortoiseSVN settings

Git Extensions

It’s pretty easy to configure Git Extensions to use P4Merge. All you have to do is to open up the settings and choose “p4merge” in the Mergetool dropdown. The correct paths should be filled in automatically for you.

Git settings

That’s it – now you can enjoy a pretty nice tool for free!

I have a grand vision.

In my vision I have a single unified interface to my entire music collection of favorite songs and artists. This may be music that I have access to on my local disk, on Last.fm, Spotify or whatever. I can play whatever I want whenever I want and I don’t have to keep track of where the songs are located.

You see, the important thing is not where the music file is physically located but the information you have gathered around it. Information that is personal to you, like your ratings and tags, and rich meta data that can be retrieved from the internet.

I want to manage my favorite artists, songs and albums in one place. I want to keep statistics of my listening habits in one place. I want my player to play the music I like, regardless of whether it’s available online or locally. I want to be social and share music. I want recommendations, surprise selections, intelligent mixing, rich information and smart guiding…

All in all, I want my music library in ONE place – is that too much to ask?

Audius is born

Ok, that’s a lot of desire in one paragraph…So, what do you do when thoughts like this keep spinning around and around in your heard?

Well, I just had to do something about it. I wanted an application that could manage all my music for me but I couldn’t find it. Every music player I have tried lacked one or more of the features that I felt were essential.

In my opinion the player has to satisfy these requirements:

  • It must provide a unified personal music library that is ignorant of where the music is stored
  • It must be fast and resource efficient
  • It must support online music services
  • It must show rich information about the music
  • It must be able to handle ratings and track the songs I play
  • It would also be nice if it could generate playlists intelligently (similar to Last.fm) but based on everything I have access to and the artists I like

When I couldn’t find something that matched all my requirements I had only one thing to do – I had to write my own player.

That is when Audius was born.

But why?

Yes, I know what you are thinking. There are plenty of music players out there…Why not just be satisfied with what we have?

Well, most popular music players were built ages ago. They don’t provide access to any of the music services available online today, or they struggle with a bogged down interface that is filled to the brim with unnecessary junk.

I listen to Spotify alot. It’s a great service but often I can’t find the music I want to hear. They simply don’t have it. It’s also very uninspiring when it comes to finding new music.

Last.fm is great for finding new unsigned artists and music that is a little bit out of the mainstream. I really like it, but their player application is quite boring and limited.

On my Iphone I have music from my own library. It’s great, I like it. But I have to sync it with Itunes. Since this also updates play count in Itunes I have started using Itunes to play music on my desktop too. I hate it. Itunes is probably the worst music player I have ever used. (I probably need another article to describe all its flaws.)

Winamp has been a long time favorite player for me, but in the recent years it has turned into a hopeless piece of bloatware suffering from an incoherent GUI.

For some time I used Windows Media Player. It’s quite nice, but it does funny things with your library and it does a lousy job with retrieving meta data. And of course, it cannot play music from any of the online services that I like.

The worst thing of all is that since I’m using three different players on my desktop (because they are all good at different things) I end up having to manage tags and album covers in all of them because they fail to cooperate. That really makes me sick of it all. The player should be able to work these things out without my help! Please.

Finally

So there you have it. Audius was born out of frustration with the currently offered products for playing music. When I’m writing this I am not ready to release anything public yet. I have a working alpha version that a few friends are trying out. It works, but it is far from polished. Hopefully I will be able to push something out in the upcoming months, but we’ll see.

This is my vision. It will not be easy to accomplish it, but I’m willing to give it a try. For my own sanity. I need it. Now.

I learned a new Visual Studio trick today. I’m currently working on a hobby project in C++ and since the plan is to make it cross platform I’m using the excellent Juce framework.

Juce has its own string type which is very nice. It handles Unicode, reference counting and so on. Its like the CString type but cross platform. Some people may prefer the standard lib string std::string but personally I think the std lib is a bit awkward.

Anyway, so what’s my problem then? Well, the thing is that when you debug your program in Visual Studio you really want to see the contents of strings easily. By default you get this when using the juce::String type:

image

Visual Studio has no knowledge about the juce::String type so it just takes a guess at what we want to see and shows us some of the private members in the type. Not very helpful…

Autoexp.dat
So what can we do about it? Well I found some info about a little file containing debugger settings for Visual Studio. It’s default location is under C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger and the file is called autoexp.dat. This file controls how VS displays different types during debugging. Interesting!

If you are running Vista/Win7, make sure you edit autoexp.dat as administrator because it’s protected since it’s in your program files. Otherwise you end up writing to a file that gets placed in your VirtualStore and it won’t work (yes, I did this myself..doh!)

Note that you can change the autoexp.dat file anytime. It will be reloaded when the debugger starts, so you don’t have to restart VS.

Now lets see what we can do… Open up the file autoexp.dat and scroll down a bit to a section called [Visualizer]. This section controls the VS visualizers for STL, ATL and other stuff. This part has a large DO NOT MODIFY text so we won’t touch that part (make a backup if you’re scared…)

Just below the part with the STL and ATL container stuff add the following:

juce::String{
    preview     ([$e.text->text,su])
    stringview  ([$e.text->text,sub])
}

This will tell VS about the Juce string type and explain how we want to view it. The ‘preview’ bit controls what to show in the watch window and the ‘stringview’ bit controls the popup string viewer that allows you to view the string as text, XML or HTML. Very handy feature!

The expression refers to the variable being viewed as $e and then you simply access its members as you would in normal code watch expressions. The ‘su’ part means that the value should be treated as a null terminated string in Unicode format. The ‘sub’ means that the string should be shown using “bare representation”. In this case it will display the string without the surrounding quotes (I only use this in the string viewer, as this seems to be the common practice).

Here is a screenshot of how it looks now:

image

Neato! Now we see the strings easily while debugging. We can also click the magnifying glass to examine the string in a popup window, even show it as formatted XML. Now the Juce type is even more juicy! Great isn’t it?

These debugger expressions can do a lot more. You can read more it here: http://www.virtualdub.org/blog/pivot/entry.php?id=120

Happy coding!

image

I’m using TortoiseSVN for source control both at work and at home. Lately I’ve been having some problems with it though because the icon overlays that show the status of files are not displayed. That kind of takes away one of the great features of the program so it quickly drove me nuts.

It turned out that it was not hard to fix. After some searching I found out that the problem is that Windows only supports a maximum of 15 registered overlay icons. Of those it uses 4 itself so that leaves us with 11 icons to play with. What happens if more icons are registered? Well, those extra icons are simply not shown. According to the TortoiseSVN FAQ this is taken into consideration when Tortoise is deciding which icons to use and I’ve never had any problems with it until now. Maybe it is not working as intended when running in Windows 7 (64-bit)?

So how does Windows decide which icons to use? Well there is a special key in the registry where everything can be found. It’s under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers.

This is how my registry looks:

image

Windows reads this list in alphabetical order which is kind of lame. I have some icons from Dropbox, some from Tortoise and some other that I suspect belong to Windows or Office. It seems that this list of 15 icons should work but it doesn’t. It’s more likely that only 11 of these icons are used because I’m missing the most common Tortoise icons (Modified and Normal) which happen to fall just outside the range.

The great part here is that each of these keys only contains a GUID which tells Windows where to lookup the actual icon information. In fact, we can change the names of the keys without breaking anything which gives us an easy way of rearranging the list!

This is a simple way of fixing it and making sure that the Tortoise icons gets a higher priority:

image

As you can see I renamed the icon identifiers and prefixed them using numbers which will ensure they are sorted before the other icons. I skipped the “TortoiseUnversioned” icon because it’s usually not of interest to me. Maybe I could skip some of the other icons too but I wanted to make sure it worked first.

After doing this little rename operation you have to restart your computer (yea, it’s Windows isn’t it?) and then the icons should show up nicely again. Quite sweet isn’t it…

image

It’s working! :)

Welcome!

I finally decided to move my blog to a new home! It was about time to move to another blog platform and WordPress seems to be a popular choice these days. In fact, it’s a quite comfortable solution for creating a minimal personal site which I’m intending to do.

I will import some of my most useful posts from http://pontusm.spaces.live.com/ so they can be found here too. I’m hoping to write more frequently here about new technology and things that interest me at the moment.

Over and out!

I don’t use Microsoft Excel very often but when I do I always find myself looking for the keyboard shortcut for inserting a new line. To me it seems impossible to find this information in Excel itself easily so I always have to resort to Google searching. And when I do that I have to wade through at least 5-6 pages talking about irrelevant shortcuts that don’t do what I need, which is simply to insert rows quickly. Now I figured that if I blog about it I can at least have a tiny chance of remembering the shortcut next time!

Anyway, the easiest way I have found to add a new line in Excel is to first hit SHIFT-SPACE. This marks the entire line that the cursor is on. After that you can just hit CTRL and + as many times you like to get new lines. Similarly CTRL and – will delete a line.

(As a side note I sometimes use Microsoft Project which uses the INSERT key as a shortcut for inserting new rows. Perhaps Microsoft could someday standardize the keyboard shortcuts in the Office applications please?)

Follow

Get every new post delivered to your Inbox.