Best practices of the Dictionary class

It’s important to know how the standard classes behave so that your code gets optimized, not performing unnecessary checks or making unnecessary calls.

Here are a number of issues I’ve seen time after time:

Fetching a value from the dictionary only if it exists

In the first version (bad) there are two dictionary lookups performed. It’s like walk in to a public library asking the librarian whether a certain book is in – and when the librarian comes back and says “yes, it’s in”, you ask again saying “Good, could you please get it for me?”. In real life it’s pretty obvious that this is a silly behavior, but in the computer world it’s not that apparent.

  🙁
In the second version (good), only one lookup is performed:
  🙂

Accessing all the keys and values

I’ve seen many real-life cases where access to both the key and value is needed in a foreach-loop, and the iteration is performed over the Keys-properties while the value is accessed by a lookup:
  🙁
If you want both the key and the value simultaneously it’s better to iterate over the dictionary as KeyValuePairs:
  🙂
(Obviously; if you want only the keys you should use the Keys-property, and if you want only the values use the Values-property)

Overwriting a value

  🙁
There is really no need to remove a key before assigning a new value to it:
  🙂

Removing a value

Once again, the following implementation leads to two lookups:
  🙁
The Remove-method is actually very kind. It doesn’t crash if you try to remove something that is not there but returns a bool telling the result of the operation:
  🙂

When may my call fail?

The call… …fails when
Never (*)
The value will be added if it’s not already in the dictionary, and it will be replaced if it does.
 
When the entry “key” does not exist.
 
When the entry “key” already exists.
 
Never (*)
 
Never (*)
(And the call returns false if the entry “key” does not exist.)
(*) Well, you get an ArgumentNullException if the key is null…

Fixing the assembly hopping between WP7 and WP8

If you want to develop an Windows Phone app that can run on both WP7 and WP8 you can simply submit one built for Windows Phone 7. But if you want to take advantage of some of the new feature of Windows Phone 8 you will need to submit two versions of it (one for 7 and one for 8). This means that you will have to maintain two copies of the project file — but you obviously don’t want two copies of each source code file.

This can be solved by putting the code in a Portable Class Library and then reference it by the two projects. There are however some limitations using a Portable Class Library, and you might find yourself stuck between a rock and a hard [coded] place trying to use it.

Each time I was facing the dual project problem, I ended up with using linked source code files instead, i.e. making one of the projects the “main” project, and then simply linking all the source code files into the other project (i.e. “Add As Link” rather than “Add” when adding “Existing Item…”). An annoying problem with this solution is however that each time you rename a source file you will need to remove and add the linked file again. Aaarrgghh! :[ But for me this actually was less painful than using the Portable Class Library.

Anyway, this way you will only have to maintain one copy of the code files that are identical on both platforms. For the ones that differs a bit, you either use compiler switches (e.g. “#if WP7 [...] #endif“) — or totally different classes (i.e. non-linked code, if there are “too much” differences to make use of #if‘s).

But when it comes to XAML you are in more trouble. For instance, if you are sharing the same implementation of a page in both WP7 and WP8, you will notice that the home of the Pivot (and Panorama) has changed between the two platforms. Ouch.

In WP7 your page declaration looks like this:

but your WP8 projects want this line:

As you can see above, the assembly name has changed.

This makes you yearn for the following (illegal) construction:

But unfortunately compiler switches are not allowed in XAML… So the above will NOT compile. 🙁

There is however a pretty simple solution to this. Create the following two classes:

This file can be linked across the two platforms intact without any need of #if‘s (since it wasn’t the namespace that was changed, “just” the assembly).

Now you simply use the MyPivot wrapper classes (instead of the Pivot directly) in your XAML, and you’re good to go:

 

Running a “Hello World” written in C# on a Raspberry Pi for Linux n00bs like me

A while ago I found myself in the possession of a Raspberry Pi.

O the joy of a new toy! But what to do with it?

Well, being a C# developer of course I would like to be able to install and run my own applications on it — and I wanted to do that remotely from my regular laptop.

The biggest problem was that I have no Linux skills what so ever. I’ve been living a comfortable (well, hm… you know…) Windows life ever since the days of the Amiga and Commodore 64. But how hard could it be?

The following are the steps I had to go through to make it work. It’s a hodgepodge of wisdoms found all over the internet. So; disclaimer: It worked for me, but I can’t promise it will work for you!

 

Here we go…

 

Step 1. Formatting the SD card

To do this properly you’ll need to use the SD Formatter 3.1 application.

Install it and launch it having your SD card inserted. Simply press the Format button. It’s enough to just do a quick format.

Important note!

If you are repeating this step later on, your SD card might appear to have lost a few gigabytes, only showing something like 56MB! This is due to that Windows cannot see the Linux partitions, and the 56MB is just some left-overs that Linux didn’t claim.

You have at least a couple of options to reclaim the full space in Windows:

  1. Find yourself a camera or any other non-windows device and try to format it in there. I first tried my age-old compact camera, but it just said that the card was bad. Then I tried my somewhat newer video camera, and it formatted it nicely and I got back my gigabytes. Phew…
     
  2. Use the dreaded (?) Flashnul (blog post) tool. I haven’t tried this one since my first option worked for me. Be careful…

 

Step 2. Installing a Linux distribution on the freshly formatted SD card

I used the Raspbian “wheezy” image. (I was somehow drawn to its tag-line “If you’re just starting out, this is the image we recommend you use”.)

To write the image to the card you’ll need the Image Writer for Windows application. There is no installation required; just download and launch the Win32DiskImager.exe. Launch it, click the blue little folder-button and point out the image file. Then press the Write button to start writing. This will take a few moments, depending on the size and speed of your SD card.

 

Step 3. First launch

After preparing the SD-card it’s time for the first launch.

Insert the SD card into the Pi and plug in an ethernet cable (with internet access), a USB keyboard and a monitor/tv (hdmi). Finally plug in the micro USB power adapter to boot it up. You will see a whole lot of text burst out on the screen. You do not need to read it all. 🙂

After a while a classic ASCII-artish gray popup appears, entitled Raspi-config.

Here you can for instance set your keyboard layout. When you’re done, use the tab key to move to the Finish button, then press enter to access the console.

This popup is shown only the very first launch time. The following times you start the Pi you will need to enter a user name and password to access the console. The default user name is “pi” and the password is “raspberry”.

 

Step 4. Optional: Setting the keyboard locale

If you didn’t change the keyboard layout in that first popup (which only will show up upon the first launch), you can do it using the following command:

sudo nano /etc/default/keyboard

Where ‘sudo’ means ‘run this command as super user’, ‘nano’ is a text editor and ‘/etc/default/keyboard’ is the file to edit.

Now the text editor appears, and you may change the ‘XKBLAYOUT’ to whatever you like. I chose ‘se’ for Sweden.

Save with Ctrl + O (!) and exit with Ctrl + X.

Reboot. This can be done by pulling the power cord or by issuing the command

sudo reboot

 

Step 5. Set a fixed IP-address

Since you want to remotely connect to your Raspberry Pi you might want to give it a fixed IP-address. This step is of course optional.

If you want to know the current network settings on your Pi, execute the following command:

ifconfig

(No, that is not a typo. It should be an ‘f’, not a ‘p’…) You will see the current IP-address under the section ‘eth0’, on the line starting with ‘inet’. (The MAC address is found after the word ‘HWaddr’.)

Edit the network settings by executing:

sudo nano /etc/network/interfaces

When the editor appears, replace the line

iface eth0 inet dhcp

with these lines (the #-mark means that the line is commented out.)

#iface eth0 inet dhcp
iface eth0 inet static
address 192.168.1.200
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1

Obviously you will need to fill in your preferred numbers here…

After saving the file you’ll need to reboot. The best thing is of course to check your new settings by executing the ifconfig-command again, after rebooting.

 

Step 6. Ensure the SSH service is started at boot time

This is necessary for connecting remotely. It was however already active on the image I used, but I’ll keep this step here anyway.

The command to execute is

sudo mv /boot/boot_enable_ssh.rc /boot/boot.rc

which means to rename/move the file/directory specified. I got the following error message:

mv: cannot stat `/boot/boot_enable_ssh.rc’: No such file or directory

which I interpreted that the SSH service was already active for me.

 

Step 7. Connect remotely from your favorite Windows PC

Download PuTTY.

There’s no installation here, just an exe-file. Launch it and fill in the IP-address to your Pi (and the port, which defaults to 22) and connect with the Open button.

You will get a warning of a potential security breach the first time you connect, because your PuTTY instance (obviously) does not recognize your Pi.

I guess it is quite harmless to press the Yes button here.

Now the Pi console window greets you by asking for your username (pi) and password (raspberry). You’re in!

 

Step 8. FTP

In addition to execute command on your Pi you will also need to transfer files to and from it. Use your favorite FTP client, for instance FileZilla. Simply connect to the correct IP address, port 22, user “pi” and password “raspberry”.

 

Step 9. Install the C# compiler and .net exe-executer

To be able to compile and execute C#-code on the Raspberry Pi, you will need to install Mono.

This turns out to be pretty simple. Just execute the following command to install the dmcs (4.0 mscorlib) C# compiler:

sudo apt-get install mono-dmcs

This will take a while to process, the files requested will be downloaded from the internet and installed by some magic Linux fairy. Please note that in the beginning you will get a “Do you want to continue”-question. After saying Y + enter you might want to get a quick cup of coffee (or a beer since this is most probably done off-business hours). It will take a couple of minutes.

 

Step 10. Compile and run your program.

Now, I wanted the full monty and even compile the C# code on the raspberry. So, in order to make it as simple as possible, I put all the code into one file (HelloPi.cs):

 

Using the FTP client, transfer your ‘HelloPi.cs’ source file to a suitable folder. Compile the source file with the dmcs-command:

dmcs HelloPi.cs

Since it’s not a very large application, it will be compiled pretty much instantly. Launch it with the mono-command:

mono MyApp.exe

Joy to the world, my app has launched! Laughing

Important note!

You might as well do the compilation on your PC (which is Much. More. Convenient.) and just transfer the exe-file to the Pi instead.

 

Some useful links

  

Good luck! Wink