VS2010 checklist

WE all share the joys of bleeding-edge tech, but we pay the price in tears of blood. 
Well, I do.
Here's my Visual Studio 2010 checklist of things to install to get a working visual studio 2010 environment, as well as some nice addons

MVVV views / viewmodel WPF mediator : how to tame a grid without any codebehind

So we're all doing WPF/MVVM by now, great, at least we get some nice declarative UI paradigm, where everything is concise and cleanly separated, your XAML doesn't have any codebehind and all is well.

That's until you start using third-party components in your views (say, a grid for example). Most vendors don't ship MVVM-friendly WPF controls, so to interact with these controls, you ususally have two choices:
  1.  Wrapping your control, this never ends nicely
  2. Add event handlers in your view to take care of your components.
I am not satisfied by either method, as wrapping a grid can only end in tears of blood, and event handlers sprinkled all throughout your view will break separation of concern, your view, on top of having an ugly codebehind, now potentially has to pamper serveral controls. And these event handlers will end-up being copypasted everywhere.

Let's see if there isn't a third way we could use, where we still get the benefits of custom event handling without anything seeping in the view itself.

See loaded assemblies and .Net performance counters with Process Explorer

The latest version of the Windows SysInternals ProcessExplorer now shows the list of loaded assemblies and appdomains as well as a view of the .Net performance counters.


Exploring loaded assemblies of any .Net process


For this to work, you will need Administrator rights, so right-click on processxp.exe and select the Run as administrator entry.

Then select any .Net process, double click to view its details view and select the .Net Assemblies tab.
You will then be treated to the process structure, which is defined this way:

{CLR Version} > {AppDomain} > {Assembly}

For each item you'll see the flags that are set. In this case, I'm running Visual Studio 2010 on a multicore machine so the Concurrent Garbage Collector is enabled. Seems like this app is well-behaved and doesn't load any 2.0 assemblies, and also load the whole 2.0 .Net CLR side-by-side with 4.0 .Net CLR.

You can also see for each assembly where the assembly was loaded from, which can shed light on all your GAC issues.

I'm also using Resharper 5 beta for Visual Studio 2010 and you can see there's a lot of managed assemblies in there. That would explain the huge memory footprint. Can we have One  Assembly To Rule Them All please? 

If you want to create your own appdomain to test



How lazy am I? Very.

Very interesting analysis of the over-use of the term 'Lazy' by El Skeet that exposes the cognitive spaghetti living in most developer's mind (including mine).

On a side note, it is my belief that the true tell-tale sign of a good developer is his laziness.

On that criteria, I am an awesome developer ;)

INotifyPropertyChanged pattern wrapper using LINQ Expressions for Silverlight / MVVM scenarios


Here's a little time-saver when writing  any kind of notifying property, namely MVVM ViewModel classes for Silverlight, or anything implementing the INotifyPropertyChanged interface. The problem is that its implementation pattern is very strict and verbose, hence being a prime candidate for code reuse or copypasta.

INotifyPropertyChange pattern implemented manually

    public class MainPageViewModel : INotifyPropertyChanged
    {
        private bool _isOldAndBusted;
        public bool IsOldAndBusted
        {
            get { return _isOldAndBusted; }
            set
            {
                if (_isOldAndBusted != value)
                {
                    _isOldAndBusted = value;
                    PropertyChanged(this,new PropertyChangedEventArgs("IsOldAndBusted"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }


Note that this pattern should be used for each property in a type that supports notification. That's a bit verbose for such a common pattern, and this has a very nasty side-effect, as the string identifying the property in the argument must match the property name under pain of runtime exception. This is going to be an issue with :
  1. Typos : We're all lazy / tired at some point and more often than not "Property" will end-up being typed "Proprety".
  2. Refactoring : Refactoring tools can change the name of a property and even sometimes change string bearing the same name, but the process needs to be checked as some tools will rename the string in totally inrelevant places, thus requiring precious developer attention-span
  3. Me : I'm a typo-prone lazy developer with the attention span of a gerbil and I have a sanctified hatred of copypasta code.
So in order to foolproof notifying properties, as well as save some precious keystrokes that will, over the years, greatly favor the lifespan of your keyboard and fingers, let's find how we can use a typesafe way of extracting a property name, and automagically encapsulate the check/assign/raise pattern of INotifyPropertyChange implementations.


Apple keyboard mappings for Windows

The apple keyboard with numpad is incredibly good.

Reminds me a lot of the Apple 2GS keyboard and it's really a joy to use, to the extent which I ditched my DAS for this one when coding. Here's a pic* ; the keyboard is huge and feels much nicer than the MBP keyboard.

There is one issue though, the insert key is nowhere to be found. Fear not, here are the (sometimes less than obvious) apple keyboard bindings for windows.

In my case: Function+Enter -- well that's going to be easy for CTRL-ALT-Insert in Resharper...

* Stormtrooper included for size

Incredible MVVM talk for SilverLight

This is a very good talk, really illustrates the strength and weaknesses of Silverlight (especially its command binding shortcoming) and mixes the Async Enumerator coroutine trick with the Silverlight Async IO model. N-E-A-T-O !

Installing windows 7 64 on an iMac 27'' or any ATI-powered Mac

So if you don't want to spend 2 hours re re re reinstalling for nothing, here's the scoop:

After rebooting your Mac, the win7 bootloader will show the animated win7 logo, then the screen will turn blank.

That's because the driver for your ATI video card on win7 64 isn't compatible with Mobile Radeon 4xxx, so just pop the win7 cd (or boot in safe mode) and delete the following file:

C:\WINDOWS\SYSTEM32\DRIVERS\ATIKMDAG.SYS>

That's a lot of thanks to the PCWorld writers from me then. Here's the step by step guide to installing win7 64 on an iMac from pcworld.

Cheers then!

Yeah, I got a 27'' i7 Jumbotron and I can't stop drooling. I'm a fanboy, there. At least I can pretend it's for running BSD :D

Quick compiler optimization sample

A quick question from a mate about debugging and code optimization

Here's the code he sent me, and he wanted to know what the compiler would end-up doing in different modes.

using System;

namespace Frankenstein
{
 internal class Program
 {
  private static bool TestPotimization()
  {
   Random r = new Random();

   string str = null;
#if DEBUG
   str = "debug";
#else
   str = "!Debug";
#endif
   Console.Out.WriteLine(str);

   if (r.Next() < 0.5d) return true;
   if (r.Next() < 0.8d) return true;
   return false;
  }

  private static void Main(string[] args)
  {
   TestPotimization();
  }
 }
}

And here is reflector's output for the release dll:
private static bool TestPotimization()
{
    Random r = new Random();
    string str = null;
    str = "!Debug";
    Console.Out.WriteLine(str);
    return ((r.Next() < 0.5) || (r.Next() < 0.8));
}

So yes, there is a decent amount of optimization done at compile-time, even before the JIT kicks in at runtime :)

What every dev must know about URL Encoding.

I recently stumbled on one of Stéphane Epardaud's tech notes on URL encoding pitfalls and can't recommend it enough.

Let's see how this translates in the .Net world.


Open letter to whoever uses DebuggerStepThroughAttribute

AA+ Coder, would debug again. 

Or not actually. The [DebuggerStepThrough] attribute will, true to its name, instruct debuggers not to step through code contained in the method or constructor it is applied on. This can lead to hours of fun when debugging poorly documented code.

But Florian, you silly monkey, you will see this in the method signature! Will readers interject, to which I would have to reply "not if the method is more than a screen-long and I'm just checking uses of another type/method using Resharper or any fancy code-navigation tool."

The [DebuggerStepThrough] attribute has been there since day 1 of the .Net framework, but should have been kept internal to mscorlib as were 99% of the nice-to-have-but-very-dirty classes that make up most of the .Net framework. This attribute was used to prevent Visual Studio from stepping into the framework and either requesting the source code or treating you to some nice IL. Now of course the .Net framework is released under a shared-source license so you can step through it (most of it, mscorlibs, which accounts dor 75% of the core distribution).

Another misleading friend is the [DebuggerDisplay] attribute, which, when applied on a field or property, will change the name/value reported in the watch window. Apart from cheeky attempts at obfuscation and a slew of practical jokes (turning an int to NaN would be a good one on the top of my head), one would be tempted to use a formatting string with no arguments to protect from famous cases of the debugger auto watch causing side-effects when calling property getters (another form of Heisenbugs).

One way to do this would be :


using System;
using System.Diagnostics;

namespace OneKStrongOxen
{
 public class Runner
 {
  public static void Main(string[] args)
  {
   DebuggerDemo me = new DebuggerDemo();
   Console.Out.WriteLine("Breakpoint set " + me);
  }
 
 }
 class DebuggerDemo
 {
  
  [DebuggerDisplay("These are not the droids you're looking for")]
  public string DangerousProperty
  {
   get
   {
    Console.Out.WriteLine("Property getter invoked with side effects");
    return "DangerousProperty";
   }
  }
 }
}
But sadly, although the display string doesn't contain any reference to the "{DangerousProperty}" format string, the property getter is still invoked...Long story short, if you consider using Debuger*Attribute you're either:

  1. Misled
  2. Overly confidend in the frameworkyness of your code and its quality.
  3. A Microsoft employee working on a non-shared-source API.

One of my current clients used to employ the services of a #2. Emphasis on used.
The solution to the above Heisenbug is either


I prefer the former.

Avoid boxing of structs implementing an interface


Structs are often used in situations where performance is critical, and are very powerful, but as the wise men say, with great power comes great responsibility and for value types, the responsibility is on the developer to make sure no boxing will occur.

The CLR states that when a value type is assigned to an interface reference, it will automatically be boxed, and boxing value types is bad.

This is what occurs in the following snippet (and how to solve this performance conundrum)


Stuck in 2.0 : Use Extension methods in .Net Framework 2.0

Some projects are still stuck in a 2.0 world and can't be upgraded to 3.5 due to weird build issues, does that mean you cannot use your String.Format shortcut extension method? Most assuredly not, thanks to an old trick to make the .Net 2.0 c# compiler accept extension methods.

In the name of all of us who occasionaly have to stare back to the past, "Thanks Daniel!"

.Net 4.0 profiling hurdles

Very good article about profiling in the .Net 4.0 framework by David Broman.

It seems like most profilers will have to release a CLR 4.0 update to their products,
JetBrain is actively testing alphas of DotTrace, still waiting for an official release date.

C# benchmark tool

After the last post on .Net 4.0 StringBuilder vs .Net 2.0 StringBuilder I realized I often ended-up testing different strategies for efficiency and I'm a little bit tired of rewriting the same .Net benchmarking framework, so here it is.

I use this when I need to check the execution speed and memory consumption of a piece of C# code, usually with pretty consistent results. The idea is to have a piece of code running in an environment where timing and memory use are monitored, and making sure the data collected isn't skewed by the JIT kicking-in or the GC stalling everything.

Here's the StringBuilder post rewritten to use this framework. Each method in the loop will be passed the object the initer fired, and the current iteration/max iter values.


.Net 4.0 StringBuilder implementation change : StringBuilder is now a linked list


An interesting change in the .Net 4.0 framework is the new System.Text.StringBuilder implementation. The .Net 1.0-era version has been ditched (it was basically an unsafe string* with an exponential memory allocation strategy on append).


The new implementation is actually a linked list of StringBuilder instances, with the current instance pointing to the last part of the string. This strategy favors insertion speed as the list always point to the latest piece of data that was inserted (it's a reversed linked list if you will).

Let's dig deeper in the implications of the .Net 4.0 System.Text.StringBuilder implementation.


HOWTO: Add Syntax Highlighting Code on Blogger using Google Code Prettify

I am going to start a series of posts where I am bound to publish lots of code (and hopefully some comments). In order to make the posts more palatable I will add syntax highlighting to the posts.

What better way to start this series than with a Syntax Highlight using Google Code Prettify on Blogger.com
  1. Go to your blogger.com control panel
  2. Choose your blog and go to the  Layout / Edit HTML menu as shown in the screenshot below.
  3. In the Edit Template section, locate the following code:
    </b:skin>
  4. Add the following snippet after the last tag </b:skin> and before the </head> tag. This will ensure that the latest version of the Google Code Prettify  JavaScript and Stylesheets are loaded:

    <link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/>
    <script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/>
  5. Locate the <body> tag and replace it with <body onload="prettyPrint()">
  6. Save your changes by pressing the 'Save Template' button then
  7. Start a new post, or edit an existing post, and in any section containing code, switch to the EDIT HTML view and surround your code with the following code:

    <code class="prettyprint">
    ... code goes there ...
    </code>

  8. If you have any issues saving your post, click on the Post Options link and make sure the Compose Settings are set to Show HTML literally as shown below:
  9. Save your post and preview it, you should have something along those lines :



    @synthesize window;
    @synthesize tabBarController;


    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Add the tab bar controller's current view as a subview of the window
    [window addSubview:tabBarController.view];
    }



You can find more info on the Google Code Prettify website and until next time...

Happy Blogging!

iPhone 3g Woes in London


Let's talk 3G coverage in London. Here's one polite way to describe it:
"It's abysmal, really."

I am currently located a stone throw from the City in London, on the south side of the Thames and it is virtually impossible for me to use my iPhone for anything else but as an overly priced hand-warmer.

The situation is the following, since June 2009, all iPhone users in the area are boasting full 3G reception on their devices, yet no calls can be made, and SMS, Voicemail and emails never reach the devices. To add insult to injury, in these recurrent scenarios, the iPhone gets very hot and actually drains battery faster than the USB cable can charge it! Which means that I get a very hot block of plastic connected to my computer during the day, and a phone with no battery when I am back at home.

Lovely.

Some iPhone users have banded together and formed a defence committee and are trying to get O2 to fix this issue but so far O2 isn't acknowledging the issue and won't try to fix it. What it is doing though is proposing to buy-back the contracts of the most vocal users, how nice.

I paid for a service I am not getting, and I will not let the provider (O2) weasel its way out of it.

What really irks me is that in days of bad weather, when lots of people telecommute, or after tea time, when everyone's off at the pub, the service works wonders. Which seems to indicate that the infrastructure (or the radio bandwidth? Some radio engineer please correct me here!) is not adequate for the device concentration, and don't tell me the 3G tower logs can't show this to the provider (O2 UK).

The issue might actually be broader than initially thought, as seen from the last three paragraphs of this Arstechnica article about iPhone 3G meltdown in the US.

It looks like no-one wants to point-out the elephant in the room : O2 UK iPhone coverage sucks, and it might very well be unsolvable if it's a 3G protocol flaw.

iPhone screenshot courtesy of James S.