Archive for July, 2007

Send and receive Win32 messages in managed code by using the MessageWindow class

Tuesday, July 31st, 2007

The System.Windows.Forms namespace is a wrapper around the native Win32 GUI functionality provided by the operating system. The .NET Framework does a pretty good job at hiding the specifics of the Win32 APIs from managed developers, providing them with a more object orientated programming model. However the managed wrappers do not provide access to all features present in the underlying OS. This is especially true of the .NET Compact Framework. One technique to access native functionality which is not supported by the .NET Compact Framework is to send window messages. This is the subject of this blog entry.

This blog entry is specific to .NET Compact Framework v2.0 or higher. Although most of the concepts are usable in .NET Compact Framework v1.0, you will need to do some additional work, since some of the properties utilised in the samples are not directly available in the older version of the .NET Compact Framework.

To get the code samples within this blog entry to compile within your projects, you must:

  • Include a reference to the Microsoft.WindowsCE.Forms assembly
  • Include a “using Microsoft.WindowsCE.Forms” statement at the top of your source code file

What is a Window and what is a Message?
The Win32 GUI platform is built around the concept of “windows”. A window is a rectangular section of the screen. Any window can also have additional child windows, which are windows contained within the rectangular space allocated to their parent.

The concept of a window is an overloaded term. The Win32 Operating System APIs not only consider Forms to be windows, but also controls you commonly place on a form such as TextBoxes or Labels. What differentiates the behavior and look and feel of these different windows is their “window class”.

Within the Win32 GUI API windows communicate with each other via the concept of messages. Messages are sent to a specific window to inform them whenever events such as typing, or tapping on the screen occur. Other window messages are of a more house keeping nature and indicate that a window should repaint itself etc.

For the purposes of the Win32 GUI APIs a windows message has the following properties:

  • Message Type – used to differentiate between different types of messages
  • WParam – a value, the meaning of which depends upon the type of message
  • LParam – essentially the same as WParam, another message type dependent field

Within the .NET Compact Framework, a window message is represented by the Microsoft.WindowsCE.Forms.Message class.

Finding a Window Handle
In order to send a message to a window you must obtain it’s handle. A handle is simply a special value which uniquely identifies a particular window to the native Win32 GUI APIs.

In many cases you can easily obtain a window handle for a control within your application by querying the Handle property of the desired control. This property is available on all the GUI controls (including forms), because they all eventually derive from the Control base class.

The following example demonstrates how you may obtain the window handle of a textbox placed onto your form:

private void button1_Click(object sender, EventArgs e)
  // Obtain the window handle for a textbox control
  // called 'textBox1' which we have placed onto the form
  IntPtr hwnd = textBox1.Handle;

By convention window handles are typically referred to as HWNDs, this is Hungarian notation for “Handle to a Window” and can be traced back to the days when C developers prefixed their variables with a description of the variable’s data type.

Sometimes you need to send a message to a window created by another application. In this scenario you do not have a Control instance to query the Handle property. In this case you need to ask the operating system to search for the window given it’s name.

The .NET Compact Framework does not support this, so you will need to Platform Invoke a native Win32 API called FindWindow, as the following example demonstrates:

using System.Runtime.InteropServices;
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
private void button1_Click(object sender, EventArgs e)
  // Find a window with the name "Test Application"
  IntPtr hwnd = FindWindow(null, "Test Application");

Fabien Decret mentions in his blog posting titled “Find a Window Handle” how you can use the Remote Spy utility to determine the name and window class of a particular window.

Sending a Message
To send a message to a window we simply create an instance of the Message class and configure it’s properties to the desired values. We then pass the message along to the MessageWindow.SendMessage static method to have it sent.

The following example demonstrates how to send a WM_CLOSE message to the File Explorer application, which will have the effect of closing it.

// Define the window message we want to send
const int WM_CLOSE = 0x10;
// Find the window we want to send the message to
IntPtr hWnd = FindWindow(null, "File Explorer");
// If the window was found, ask the application to close
if (hWnd != IntPtr.Zero)
  // Create a WM_CLOSE message (it doesn't use the lParam
  // and wParam fields so we set them to zero) and send the
  // message to the window
  Message msg = Message.Create(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
  MessageWindow.SendMessage(ref msg);

The documentation for the WM_CLOSE window message can be found on MSDN. This documentation explains the interpretation of the lParam and wParam parameters, as well as outlining at the bottom of the page, which header file we need to look in to obtain the value of WM_CLOSE (i.e. 0×10).

There is also a MessageWindow.PostMessage method, which is utilised the same way as SendMessage except that unlike SendMessage it does not wait for the message to be processed by the window it is sent to before returning.

Receiving a Message
On the desktop, the Control class provides a WndProc method which can be overridden to process any window message sent to the control. The Compact Framework however does not provide the WndProc method for us to override, so there is no (easy) way to see window messages sent to a control.

The .NET Compact Framework instead has a special class called MessageWindow which enables the creation of a hidden window that provides a virtual WndProc method which can be overridden to process any window messages sent to it.

To make use of this class applications must derive a class from MessageWindow and then override the WndProc method so that messages sent to the window can be processed.

The following code sample shows how to derive a class from the MessageWindow base class:

public class MyMessageWindow : MessageWindow
  // The window message type we want to process
  public static readonly int WM_USER = 0x400;
  // This method gets called for every window message this
  // window receives.
  protected override void WndProc (ref Message m)
    // Check if it is a message we want to handle
    // based upon it's message type
    if (m.Msg == WM_USER)
      // This is a message we recognise, so lets
      // process it. In this case we'll display a message
      // box
      MessageBox.Show("Hello - i received a window message");
    base.WndProc (ref m);

Because this is a managed application, there is no definitions available for the standard window messages such as WM_USER. A glance at the MSDN Documentation for WM_USER will confirm that the definition can be found within the C header file winuser.h, managed developers need to duplicate this definition in their own applications, as the code sample demonstrates. WM_USER is a good message number to utilise, since Microsoft defines this message number as the starting point for user defined messages.

Once we have defined our MessageWindow subclass we simply need to create an instance of the class to create the hidden window. The class has an Hwnd property which provides the window handle we need to send messages to in order for them to be processed by this window.

The following code sample demonstrates how to create an instance of the MyMessageWindow class, and then send a window message to it.

// Create the hidden window
MessageWindow msgWindow = new MyMessageWindow();
// Send a message to it
Message msg = Message.Create(msgWindow.Hwnd,
    MyMessageWindow.WM_USER, IntPtr.Zero, IntPtr.Zero);
MessageWindow.SendMessage(ref msg);

The previous code sample is not a typical use case of a message window. Typically the window will be created by one part of an application, and a message will be sent to the window from an unrelated part of the application (or even another application entirely). This leads to a problem, since the code which sends the window message will typically not have access to the window handle (Hwnd property value) to know where to send the message.

In this case you may like to set your MessageWindow’s Text property to something uniquely identifiable as your application. You can then use the FindWindow approach mentioned previously to find the window handle by passing in the same string.

Practical Uses
Sending window messages can be utilised for a number of purposes, but they are mainly utilised to interface to external applications. The following references are to real life situations where sending window messages is useful:

Sample Application
I have put together a small sample application to demonstrate some of these techniques. the easiest way to play with the demo is to open up the “SenderApplication” and “SecondApplication” projects into two instances of Visual Studio 2005. You will then be able to follow the “demo script” below:

  1. Start the “SecondApplication” in the debugger (press F5)
  2. Start the “SenderApplication” in the debugger (press F5 – also ensure you select the same emulator/device)
  3. Click the “Click another button” button and notice how the application behaves as if the “Show a Message Box” button was pressed. This is because a button click window message is being sent to the message box button whenever the first button is clicked.
  4. Click the “Display message in another app” button. Notice how the second application pops up and displays a message box stating the current state of the checkbox in the first application. This is because the “SenderApplication” has sent a window message to the MessageWindow created by the “SecondApplication”.
  5. Dismiss the message box and minimise the “SecondApplication” to return to the “SenderApplication”.
  6. Change the state of the checkbox and click the “Display message in another app” button a couple of times to see how the two applications are communicating the state of the checkbox.
  7. Press the “Close other app” button, and notice that the “SecondApplication” application shuts down (which will cause Visual Studio to stop debugging that project).

This blog entry neatly covers some of the background theory on something I have been working on quietly in the past few days, hopefully early next week I’ll have an interesting application to blog about….

Visual Introduction to .NET Micro Framework

Monday, July 30th, 2007

Confused about the .NET Micro Framework and what scenarios it enables? Or wondering how it compares to the .NET Compact Framework? Finding the documentation heavy going?

The following videos may help explain the differences, and give you some neat ideas for possible applications of the technology.

.NET Micro Framework resources

Sunday, July 29th, 2007

Over the weekend I have found some more .NET Micro Framework developer resources available on the Internet.

  • Kudzu World – “Programming is an art form that fights back”. This is the personal website of Chad Z. Hower, which has a .NET Micro Framework related section. It is essentially an index to blogs, development boards and other resources Chad has discovered.
  • .NET Micro Framework for Dummies – This is a promising new blog by an unknown developer (I could not find any contact details on the blog) who is in a similar situation to me. He has brought a Tahoe development board, and is blogging about his experiences learning to develop for the new platform.
  • Jens Kühner – “Geek stuff about the .NET, Compact and Micro Framework”, a reasonably new blog by Jens Kühner who is currently writing a book about the .NET Micro Framework. He promises to provide further tips and tricks as his book writing continues.

It will be interesting to see how these resources develop over time, many are at an earlier stage of their development (similiar to my own blog).

Another link of interest is a presentation titled “.NET Micro Framework – Brining .NET to smaller embedded devices” which appears to be developed by Microsoft. This is a worthwhile read, for those wanting to get a good overview of the platform. Sorry about the link (it points to a random PDF on someones website), but I discovered it via a Google search results page, and have not managed to find a better page to link to.

Simon Tatham’s Portable Puzzle Collection for Windows Mobile

Sunday, July 29th, 2007

Screenshot of Galaxies puzzle game running on a Windows Mobile deviceLast week I came across Simon Tatham’s website via a blog posting by Jon Skeet. One of the interesting finds on his website was his Portable Puzzle Collection. This is a series of approximately 27 puzzles which have been architected to be easily ported to new platforms. At present Mac OS X, Unix (using GTK as the GUI toolkit) and Windows builds are officially supported.

Dariusz Olszewski has contributed patches for the existing Windows build to target Windows Mobile (Pocket PC 2003 or higher). I recently submitted a small patch to improve the Windows Mobile port to cope with devices which can dynamically change screen orientation. I have also locally modified the build script to compile with Visual Studio 2005 rather than Embedded Visual C.

I particularly like the Galaxies puzzle, it’s very simple, but addictive at the same time. It also exercises the right side of the brain, as you try to determine if a particular shape will have rotational symmetry.

These games are well worth a look at, and I encourage any C developer with a little spare time to look into improving the Windows Mobile port (source code can be obtained from a SVN repository at svn:// These puzzle games are an ideal way to fill in a few spare moments of time.

Windows Mobile Tip: Peeking inside CAB files

Saturday, July 28th, 2007

CAB files are the standard installation mechanism for Windows CE powered devices. Have you wondered what files have been installed by a given piece of software? Or what registry settings may have been overwritten during installation? If so, then this tip is for you.

CAB File Formats
A Microsoft CAB file is similar in nature to a common ZIP, or TAR file. They are a form of archive which contain one or more files. The individual files within a CAB file may have been compressed to reduce the overall size of the archive.

This archive file format has been re-purposed for application installation on Windows CE devices, by specifying a file with a special name that outlines the tasks required to install a given software package. This list of tasks will typically include decompressing and copying various files onto the PDA, but may also contain instructions to configure registry settings, or install shortcuts into the start menu etc.

Over the years the precise format of these files has changed. For a while the Windows Mobile Pocket PC and Smartphone platforms had incompatible CAB file formats. This has been resolved since the Windows Mobile 5.0 release which brought about a “unified” CAB file format for both platforms.

The older style CAB files had the list of setup instructions listed in a binary formatted file. The only information I am aware of on the structure of these CAB files is some reverse engineered documentation produced by the developers of the cabextract project.

The newer style CAB files have the list of setup instructions listed in an XML file called _setup.xml. It is this particular format that I will discuss here.

Extracting the contents of CAB files
On a desktop PC there are a number of ways you can extract the individual files within a CAB file. These include:

  • expand.exe – the Microsoft File Expansion Utility is a command line application present on all Windows machines. Specifying the name of a CAB file will cause the CAB file to be extracted into the current directory.
  • explorer.exe – by default most recent versions of Windows have an explorer shell extension which enables users to browse the contents of a CAB file by simply double clicking on it (as seen in the screenshot).
  • Winzip – many third party archive utilities will associate themselves with CAB files and enable you to extract their contents.

If you extract the _setup.xml file you can confirm that it’s main element is <wap-provisioningdoc>. This is a WAP provisioning document, as documented in MSDN in the Configuration Service Provider section.

The particular subset of this file format used by typical CAB files is fairly straight forward to follow, even without referring to the documentation. The _setup.xml file will enable you to determine the proper file names for the other files within a CAB file, and more importantly where they are installed to. One thing to be aware of is the use of macro Strings such as %CE2% to cope with internationalisation within file paths.

Possible uses of this tip
During development of an application, using this tip can be handy to verify that your CAB files are installing the desired files and settings. It is also useful when you have a CAB file which you have lost the original source code to, to determine what changes are made to the device.

The information would also be of use if you are developing an application to merge individual CAB files into one combined CAB file, such as the application discussed by Chris Tacke on his blog.

Random CAB fact of the day
Did you know that CAB files transfered via ActiveSync may be altered during the transfer process? If you have a CAB file which has been authenticode signed with a certificate, ActiveSync may strip off the certificate during the transfer process if it determines the connected device does not support signed cab files. This is something to be aware of, if you notice your CAB files won’t install if you download them across the network, but will if manually transfered via ActiveSync.

When is C# 2.0 not equal to C# 2.0?

Friday, July 27th, 2007

As I have mentioned previously I have only recently started learning about the .NET Micro Framework, as such I am constantly learning new things about this constrained development environment and today was no exception, here is what I learnt…

The lack of generics
I was investigating the use of the ExtendedWeakReference class, and as part of a test application I was putting together I thought it would be nice to make use of some generics. Generics were a new feature in C# v2.0 which enable you to produce efficient, reusable type safe code.

As the following example program demonstrates, you can make use of certain C# 2.0 features such as anonymous delegates when targeting the .NET Micro Framework. However any attempt to use generics will cause a build time error to occur.

using System.Threading;
using Microsoft.SPOT;
public class Program
  public static void Main()
    // Configure a timer to print out a message to the debug window once
    // every 5 seconds. Notice that we use an anonymous delegate for the
    // TimerCallback delegate parameter. This is a C# 2.0 language feature.
    Timer t = new Timer(delegate(object o){ Debug.Print("Hello World!"); },
                                  null, 0, 5000);
    // Place the main thread into an infinite sleep. The
    // timer callbacks will occur on a separate thread.
    while (true)

If you do attempt to use generics within your code the C# compiler will execute successfully (i.e. csc.exe indicates no errors in the build log) but the Meta Data Processor (MetaDataProcessor.exe) which runs automatically after the C# compiler will produce the following error:


The Meta Data Processor is the utility which converts assemblies from the standard PE Executable file format (as used on the desktop), into a smaller more efficient representation utilised by .NET Micro Framework devices.

My assumption here is that any C# v2.0 feature which ends up being a chunk of “compiler magic” which essentially converts your code behind the scenes into a form that would have been compatible with the V1.0 compiler is supported on the .NET Micro Framework. While features such as Generics, which required CLR changes in addition to compiler changes, are currently not supported by the .NET Micro Framework.

No support within the BCL to parse numbers
A typical programming task is to parse strings and convert them into numbers. Typically a .NET developer would use a static method within the Base Class Library such as Int32.Parse() to perform this operation.

However the numeric classes within the .NET Micro Framework BCL are pretty empty, and don’t include methods such as Parse. Likewise the System.Convert class does not exist. This means if you need to parse a number, you need to write the number parsing code yourself.

This issue has been discussed on numerous blogs and online forums. Some interesting coverage on this subject is as follows:

  • In a thread titled “Best way to convert string to float/double/decimal?” James Webster a Test Manager within the Microsoft .Net Micro Framework team mentions this is an issue which may be resolved in a later release of the framework. He also provides a quick suggestion as to a work around. This sample has a number of performance issues, which are then worked upon in the rest of the thread.
  • A post by Jens Kühner titled Number parsing with the .NET Micro Framework sounds very promising, however at present the download link to the source code appears to be broken.

While I was on Jens Kühner’s blog I noticed that he is currently writing a .NET Micro Framework book. He promises to release more details, and samples as time goes on. So his blog could be an interesting one to watch. It would be interesting to know how his book compares to Microsoft Press’s Embedded Programming with the Microsoft .NET Micro Framework.

The System.Math class
In a similar manor the System.Math class which provides various math functions is rather limited on the .NET Micro Framework’s version of the BCL. There are no SIN or COS functions for instance.

EmbeddedFusion recently released the source code for their “Ball-In-Maze” tutorial designed for their Tahoe Development Board. This lab was originally presented at MEDC 2007. Reading through the source code you come across a number of useful tips and tricks. Including an integer square root implementation, which I assume was done for speed.

Perhaps it is time to dust off my copy of Jack Crenshaw’s MATH Toolkit for REAL-TIME Programming book and develop a small support library of additional math functions.

Encrypt and decrypt the contents of a file created on a mobile device

Thursday, July 26th, 2007

A screenshot of the example symmetric encryption application I wroteEncrypting the contents of a file is a common task, especially with configuration files which may contain sensitive passwords, or database connectivity information.

Recently I discussed symmetric and asymmetric encryption support within .NET Compact Framework v2.0. These blog entries were heavy in theory and light on actual sample applications.

Microsoft’s 70-540 exam covers knowledge about encryption by outlining a couple of common usage scenarios and expecting candidates are capable of implementing them. One such task is the ability to encrypt and decrypt the contents of a file and this blog entry covers an example implementation of this.

How to use the sample application
The main user interface is a single form. By making selections in the combo boxes at the top of the form you can select the required encryption algorithm and key size.

Whenever you change key sizes, a random encryption key is generated for you and this is inserted into the key text box. If you have a message encrypted with a specific encryption key, you can type it into the key text box manually.

To create an encrypted text file, type your message into the textbox at the bottom of the form and tap the encrypt button. A file save dialog box will appear to ask you where you want to save the encrypted file.

To decrypt a text file, tap the decrypt button and a file open dialog box will appear to ask you to select a file to decrypt. Once you have selected one an attempt will be made to decrypt the message using the encryption key present within the UI, and if successful the cleartext message will be displayed in the textbox.

If you use Pocket Word to open the text files you have encrypted, you should see that they contain no human readable content and simply contain a “garbled mess”. You should only be able to recover your encrypted message by configuring identical encryption parameters within the GUI again and pressing the decrypt button.

How it works
The process of implementing symmetric encryption within the .NET Compact Framework has been covered before, so please refer to that blog entry for technical details on the implementation. The source code of the sample application is also available, and is heavily commented to describe what is happening at each stage of the process.

A high level overview of how this application performs encryption of text files is as follows:

  1. An instance of a class which derives from SymmetricAlgorithm is created.
  2. The LegalKeySizes property is read to determine a list of valid key sizes.
  3. The KeySize and Key properties are configured with the desired values.
  4. The IV property is configured with the desired value (and optionally the BlockSize property is altered).
  5. A FileStream instance is created to allow access to the file.
  6. The FileStream is wrapped in a CryptoStream, which is then used instead of the original file stream (this is what performs the encryption/decryption).

Further work
Questions to ask yourself while reviewing the source code of this sample include:

  • How does a CryptoStream know if it is encrypting or decrypting data?
  • How can I verify if a given key size is valid for the selected encryption algorithm?
  • What exceptions may be thrown during decryption if an incorrect key is utilised?
  • What object oriented concept makes it easy to switch between different symmetric encryption algorithms with only minor code changes?

This sample application only demonstrates the use of symmetric encryption algorithms. As an exercise left to the user, see if you can alter the sample application to use asymmetric encryption by using the RSACryptoServiceProvider class. As part of your solution you should figure out how to export and import the public part of your public/private key pair, so other devices can read your encrypted messages.

The source code for the sample application can be downloaded.

Handling GPIO Interrupts within the .NET Micro Framework

Wednesday, July 25th, 2007

My previous .NET Micro Framework example demonstrated how to determine the state of a GPIO input signal. This blog entry outlines how to implement an improved application which instead makes use of an interrupt event handler, for improved performance and power efficiency.

The problem with the InputPort based example was that it utilised a polling mechanism to constantly determine the current state of the GPIO port, this mode of operation is not ideal for a number of reasons, including:

  • Power Management – The polling implementation may become a busy loop, spinning around as quickly as possible, burning CPU cycles to check the state of the input which only occasionally changes state.
  • Responsiveness – A common resolution to the power management issue is to only periodically probe the hardware. The example application from the last blog entry sampled the GPIO state once per second. This has the side effect of introducing latency, since we will only detect a change in state once the current delay has completed. We may also miss a change completely if it happens too quickly.

To resolve some of these issues we can utilise the InterruptPort class. This class derives from the InputPort class mentioned in the previous blog entry, and hence by default inherits all of the InputPort’s properties and functionality.

The main difference is an additional constructor parameter which specifies when an ‘OnInterrupt’ event associated with the port should fire.

Determining when the interrupt should trigger
The additional constructor parameter specifies the conditions under which the interrupt should trigger. You can use one of the following Port.InterruptMode enumeration values:

  • InterruptEdgeBoth – The interrupt is triggered on both rising and falling edges.
  • InterruptEdgeHigh – The interrupt is triggered on the rising edge.
  • InterruptEdgeLow – The interrupt is triggered on the falling edge.
  • InterruptEdgeLevelHigh – The interrupt is triggered whenever the input signal is high.
  • InterruptEdgeLevelLow – The interrupt is triggered whenever the input signal is low.

Clearing Interrupt flags
Edge interrupts trigger when the specified signal transition occurs and automatically re-enable themself, ready to trigger on the next state transition. Level based interrupts however behave slightly differently.

Whenever a level interrupt (InterruptEdgeLevelHigh or InterruptEdgeLevelLow) is triggered it sets a flag which disables the interrupt from re-triggering until the flag is explicitly cleared by means of the ClearInterrupt method.

The main purpose for this is to stop a constant stream of interrupts occurring when the specified level is reached on the GPIO signal. By disabling the interrupt once it has triggered, the software can decide when it wants to be interrupted again. When the ClearInterupt method is invoked, it is possible that the interrupt event handler will fire immediately, if the specified level is still held on the signal.

Example Application
The following is a simple example of how the InterruptPort class can be utilised to produce asynchronous behavior.

The main loop of the program, simply prints the message “House Keeping Ping…” to the debug console every 60 seconds. This is to provide an indication of when the main thread is running. In a typical embedded device this main loop may do menial house keeping tasks, such as timer management, and status LED flashing etc.

While the main loop is sleeping (or printing debug messages), the hardware is constantly monitoring the state of the GPIO_Pin_3 input (attached to the Select button within the Sample Emulator). Whenever the signal goes low, an interrupt is triggered, which causes our button_OnInterrupt event handler to execute on a second thread.

You will notice that button presses are detected immediately even while the main thread is sleeping, unlike the polling example which only detected the button press when the main thread woke up.

using System; 
using System.Threading; 
using Microsoft.SPOT; 
using Microsoft.SPOT.Hardware;namespace InterruptPortApplication 
  public class Program 
    public static void Main() 
      // Specify the GPIO pin we want to use as an interrupt 
      // source, specify the edges the interrupt should trigger on 
      InterruptPort button = new InterruptPort(Cpu.Pin.GPIO_Pin3, true, 
        Port.ResistorMode.PullDown, Port.InterruptMode.InterruptEdgeLow); 
      // Hook up an event handler (delegate) to the OnInterrupt event 
      button.OnInterrupt += new GPIOInterruptEventHandler(button_OnInterrupt); 
      while (true) 
        // The main thread can now essentially sleep 
        // forever. 
        Thread.Sleep(60 * 1000); 
        Debug.Print("House Keeping Ping..."); 
    static void button_OnInterrupt(Cpu.Pin port, bool state, TimeSpan time) 
      // This method is called whenever an interrupt occurrs
      Debug.Print("The button is pressed"); 

The three parameters in the GPIOInterruptEventHandler delegate type are as follows:

  • pin – a reference to the pin that caused the interrupt to occur. This is useful because you can hook up the same event handler to more than one InterruptPort instance.
  • state – the logic level of the GPIO signal when the interrupt occurred.
  • timestamp – a relative time-stamp which allows you to accurately determine when the interrupt occurred.

The InterruptPort class is not designed for use in hard real time applications. In my mind it is more a Deferred Procedure Call (DPC) implementation triggered by hardware events than a true Interrupt Service Routine (ISR).

Since I have no physical .NET Micro Framework hardware yet, it is a bit difficult for me to tell exactly how the performance characteristics of interrupt handlers within the .NET Micro Framework stack up. This is defiantly an area I would like to characterise further once my hardware arrives.

In the mean time here are some links to low level performance related material that I have managed to find. Both articles are written by Chris Tacke and give an excellent insight into the performance characteristics of the .NET Micro Framework (and managed code in general) for embedded development.

Asymmetric Key Encryption on the Compact Framework

Tuesday, July 24th, 2007

Asymmetric key encryption is useful for use in exchanging data over insecure communication channels. This is due to the use of separate keys for encryption and decryption. This blog entry follows on from the previous one on symmetric key encryption and discusses how to utilise asymmetric key encryption within a .NET Compact Framework application.

Asymmetric Encryption classes within the .NET Compact Framework
The .NET base class library provides Asymmetric Encryption classes within the System.Security.Cryptography namespace. They all derive from the AsymmetricAlgorithm base class.

The .NET Compact Framework base class library provides the following asymmetric encryption classes

  • RSACryptoServiceProvider – This is the .NET implementation of the RSA algorithm named after its three creators – Ronald Rivest, Adi Shamir and Leonard Adleman. It was developed in 1977. This is a wrapper around an unmanaged algorithm implementation provided by the Windows CE Crypto API.
  • DSACryptoServiceProvider – This class is used for digitally signing messages to ensure that they are not tampered with during transit. This is also a managed wrapper around unmanaged code. Since digital signatures and hashing are not part of the current topic I will not discuss this class any further.

Common Asymmetric Algorithm properties
When dealing with the encryption aspect of these crypto service providers there are only a couple of properties of interest defined on the AsymmetricAlgorithm base class:

  • KeySize – the size of the secret key used by the asymmetric algorithm in bits. These are typically much larger than symmetric keys. For example RSA as implemented in the .NET Compact Framework supports keys between 384 and 16384 bits. Setting this property affects the strength of the encryption process.
  • LegalKeySizes – an array of KeySizes objects which outline the range of key sizes supported by the current encryption algorithm.

Likewise there are only a couple of methods defined on the AsymmetricAlgorithm base class.

  • ToXmlString – exports a key pair in the form of an string containing an XML document.
  • FromXmlString – imports a key pair from a string containing an XML document.

You will notice there are no methods for encryption or decryption on the AsymmetricAlgorithm base class. Most of the useful methods (including those used for actual encryption) are actually defined on the classes which derive from AsymmetricAlgorithm.

The most useful methods defined on the RSACryptoServiceProvider class are as follows:

  • Decrypt – a method to decrypt data with the RSA algorithm.
  • Encrypt – a method to encrypt data with the RSA algorithm.
  • ExportParameters – returns a RSAParameters struct, which defines the RSA encryption key pairs (i.e. returns the same data as the ToXmlString method, just in a different format).
  • ImportParameters – imports a public key or key pair from the specified RSAParameters struct.

How to export and import key pairs
Once you have created an instance of the RSACryptoServiceProvider class it will generate it’s own public/private key pair. You can import and export the keys for storage purposes, or to transfer them to another device. In most cases you will probably want to only export the public key (since the private key should be kept a closely guarded secret).

When exporting the keys via the ToXmlString (as XML) and ExportParameters (as a RSAParameters struct) methods, you have the choice of exporting only the public key (false), or both the public key and private keys (true) via a boolean parameter.

The following code sample, demonstrates using these methods:

// Export the public key (pass in true to also export the private keys)
// from device A
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider();
RSAParameters publicKey = rsa1.ExportParameters(false);
string publicKeyXML = rsa1.ToXmlString(false);
// ... transmit public key to another device ...
// Import the public key
// into device B
RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider();

Please note that in the code sample I have demonstrated using both the XML and object based methods. In a typically application only one set of methods would be utilised.

Secure private key storage
Your application most likely needs to reuse the same public/private key pair a number of times. This means that once generated you will typically need to store your key pair in a secure manor.

The RSACryptoServiceProvider class includes the ability to save the keys in a secure manor by using the Crypto API CSP key container facility. You should seriously consider using this functionality to store private keys, as it is highly likely that it will be more secure than most solutions you will be able to create manually.

To store your private keys in a CSP key container, perform the following actions within your code:

The .NET Compact Framework then handles creating and retrieving keys automatically. The first time the code executes a unique public/private key pair will be generated and saved into the specific key container. In the future when the RSACryptoServiceProvider instance is created with the same key container name, the keys will automatically be retrieved.

// Create the CspParameters object and set the
// key container name used to store the RSA key pair.
CspParameters cp = new CspParameters();
cp.KeyContainerName = "MySampleKeyContainer";
// Create a new instance of RSACryptoServiceProvider 
// that accesses the key container "MySampleKeyContainer"
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
// Display the key information to the debug window.
Debug.WriteLine("Key added to container: \n  {0}", rsa.ToXmlString(true));

How to encrypt and decrypt data using Asymmetric encryption
The Encrypt() and Decrypt() methods both accept two parameters as follows:

  • rgb – a byte array containing the data to be encrypted or decrypted
  • fOAEP – a boolean flag. If true OAEP data padding is used, otherwise PKCS #1 v1.5 padding is used. This parameter doesn’t really matter as much, as long as encryption and decryption utilise the same value. Controlling this parameter becomes important in scenarios where one end of the encryption process is dictated by a third party system.

The following example demonstrates basic RSA encryption and decryption by providing a couple of small helper functions which will be useful within your own applications.

The methods encrypt (or decrypt) data passed to them in the form of a byte array and return another byte array containing the processed output. These methods utiilise the CSP Key Container storage mechanism to securely store the public/private key pair used to perform the encryption process.

using System.Security.Cryptography;
public byte[] Encrypt(byte[] data, string keyContainerName)
  // Configure the parameters to indicate the name of the
  // key container which contains our public/private key pair
  CspParameters csp = new CspParameters();
  csp.KeyContainerName = keyContainerName;
  // Create an instance of the RSA encryption algorithm
  // and perform the actual encryption
  RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
  return rsa.Encrypt(data, true);
public byte[] Decrypt(byte[] data, string keyContainerName)
  // Configure the parameters to indicate the name of the
  // key container which contains our public/private key pair
  CspParameters csp = new CspParameters();
  csp.KeyContainerName = keyContainerName;
  // Create an instance of the RSA encryption algorithm
  // and perform the actual decryption
  RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
  return rsa.Decrypt(data, true);

Please note that if the encryption and decryption code was running on two different devices, you would have to use the technique discussed in the “How to export and import key pairs” section to ensure that the decryptor had access to the public key.

A common request on newsgroup forums is for help in encrypting small amounts of text. Common problems encountered in this scenario include improperly converting the binary data produced by the encryption process back into a text string.

For this reason I have also provided the following helper functions which make it really easy to securely encrypt and decrypt text strings.

using System;
using System.Text;
public string EncryptString(string data, string keyContainerName)
  // Encrypt a string using the private key stored within the
  // specified key container
  byte dataToEncrypt[] = Encoding.UTF8.GetBytes(data);
  byte encryptedData[] = Encrypt(dataToEncrypt, keyContainerName);
  return Convert.ToBase64String(data);
public string DecryptString(string data, string keyContainerName)
  // Decrypt a string using the public key stored within the
  // specified key container
  byte dataToDecrypt[] = Convert.FromBase64String(data);
  byte decryptedData[] = Decrypt(dataToDecrypt, keyContainerName);
  return Encoding.UTF8.GetString(decryptedData);
// Example use
string myEncryptedString = EncryptString("This is my top secret message",
string myDecryptedString = DecryptString(myEncryptedString,

Now that I have provided some rather long discussions on symmetric and asymmetric key encryption within the .NET Compact Framework, I am finally ready to dicuss some practical uses of encryption. In the next few days I aim to cover off some of the encryption related aspects of exam 70-540.

Symmetric Key Encryption on the Compact Framework

Monday, July 23rd, 2007

There are two main types of encryption algorithms available within the .NET Compact Framework – symmetric and asymmetric encryption. This blog entry will discuss how to utilise symmetric key encryption, but first we have to outline the difference between Symmetric and Asymmetric encryption (I will discuss asymmetric key encryption in a future blog entry).

Symmetric and Asymmetric Key Encryption
Symmetric encryption algorithms (also known as ciphers) process plain text with a secret encryption key to create encrypted data (called cipher text). The same secret key is used to decrypt the cipher text back to plain text.

Asymmetric encryption (also known as public-key encryption) is a cryptography technique that uses public and private key pairs to encrypt and decrypt data respectably. The private key is a closely guarded secret, while the public key can be freely distributed over untrusted networks. You do not worry who has your public key (you could print it on a 100foot tall banner if you so desired), but you must keep your private key secret.

The two keys are mathematically linked; data encrypted with the public can only be decrypted by the private key and visa versa. So once data is encrypted you can safely assume only the intended recipient can read it.

The disadvantage of symmetric key encryption is that it assumes that the two parties involved have already agreed upon an encryption key in a secure manor. Any insecurity in the key exchange mechanism compromises the security of the data. Conversely the disadvantage of asymmetric encryption algorithms is that they are more computationally expensive and hence slower to work with.

A common technique is to use an asymmetric encryption algorithm to transfer a randomised symmetric encryption key that is then utilised to encrypt the rest of the communication process. SSL work this way for example.

Symmetric Encryption classes within the .NET Compact Framework
The .NET base class library provides Symmetric Encryption classes within the System.Security.Cryptography namespace. They all derive from the SymmetricAlgorithm base class which provides a set of common properties and methods. By deriving from a common base class it is easy for your application to switch among the different encryption algorithms with only minor code changes.

The .NET Compact Framework base class library provides the following symmetric encryption classes:

  • RijndaelManaged – Rijndael also known as Advanced Encryption Standard (AES) supports use of 128 to 256 bit keys (in 32bit increments). This is also the only symmetric encryption algorithm within the BCL which has a fully managed implementation.
  • DESCryptoServiceProvider – The Data Encryption Standard (DES) supports 56bit keys. This is vulnerable to cracking attacks due to relatively short key length by modern standards.
  • TripleDESCryptoServiceProvider – Triple DES is essentially three iterations of the DES encryption process. It utilises 156bit keys, but only 112 bits are effectively utilised for encryption.
  • RC2CryptoServiceProvider – This is an encryption standard designed to replace DES. It allows for variable length keys.

You will notice that many of the encryption classes end with the postfix “CryptoServiceProvider”. This is an indication that the encryption algorithm is implemented in native code, as part of the Windows CE Cryptography API. Internally the BCL classes are a thin wrapper over Platform Invoke code which access the actual encryption algorithms.

When deciding which encryption algorithm to use MSDN contains a good article called Performance Comparison: Security Design Choices” which compares the performance of the algorithms.

Common Symmetric Algorithm properties
All symmetric algorithms derive from the System.Security.Cryptography.SymmetricAlgorithm base class and share common properties, the most commonly used properties are described below.

  • BlockSize – Symmetric encryption algorithms work on blocks of data. The block size is the number of bits the encryption algorithm processes at a time.
  • IV – The initialisation vector (IV) for the encryption process. To prevent patterns forming in blocks of encrypted data, the second block of data is encrypted with the results of the first block and so on. Since the first block has no previous block the initialisation vector is used to obscure the first block of data.
  • Key – The secret key used for the symmetric algorithm. If not specified one is automatically generated. After encryption the key must be stored and transfered to the application which performs the decryption.
  • KeySize – The size of the secret key in bits. When you create a symmetric algorithm object, the runtime will choose the largest key size supported by the platform. You should only change this if the message recipient does not support the same key size.
  • Padding – One of the PaddingMode enumeration values. Determines how the algorithm pads out the last block if the plain text doesn’t fully consume the last block.

Likewise the SymmetricAlgorithim base class provides a number of abstract methods which support the basic encryption processes:

  • CreateDecryptor – This returns an instance of an object which implements the ICryptoTransform interface. A Cryptostream object can use this to decrypt a message.
  • CreateEncryptor – Similar to the CreateDecryptor method except the ICryptoTransform instance returned performs encryption
  • GenerateIV – Generates a random initialisation vector to be used with the symmetric algorithm and assigns it to the IV property.
  • GenerateKey – Generates a random key to be used by the symmetric algorithm and assigns it to the Key property.
  • ValidKeySize – Determines if the specified key size is valid for the current algorithm.

How to generate symmetric keys
To generate a random key you must use cryptographic strength random numbers. If your “random numbers” are guess-able (or have some form of pattern to them), you cripple the strength of your encryption. You should not use the System.Random class, because the random numbers it generates are not of cryptographic strength.

The easiest way to generate cryptographically strong random keys is to create an instance of your desired symmetric encryption algorithm and call the GenerateKey() method after setting the KeySize property to the desired key length. This will generate a random key of the required length and automatically assign it to the Key property, as the following example demonstrates:

SymmetricAlgorithim sa = new RijndaelManaged();
byte[] key = sa.Key;

How to display encryption keys
Encryption keys are long sequences of random binary data and as such are difficult to display on a screen or to print out. Two common techniques for displaying keys (or general binary data) in a printable form are hexadecimal and Base64 formatting, as demonstrated by the following code sample:

// Converts the byte array into a hex encoded string
public string GetHexString(byte[] data)
  StringBuilder sb = new StringBuilder();
  foreach (byte b in data)
  return sb.ToString();
// Converts the byte array into a Base64 encoded string
public string GetBase64String(byte[] data)
  return Convert.ToBase64String(data);
// Example of using the methods defined above
// to display encryption keys
SymmetricAlgorithm sa = new RijndaelManaged();
sa.GenerateKey(); // generates a random key
MessageBox.Show(GetHexString(sa.Key), "Key in Hex Format");
MessageBox.Show(GetBase64String(sa.Key), "Key in Base64 Format");

A hexadecimal string is easier to quote over a phone (since it only uses the characters 0 to 9 and A to F) however it will be longer than a Base64 string which also uses additional printable characters.

You should not use the System.Text.Encoding classes to convert an encryption key to a string. Since the encryption key is binary data, the key is not guaranteed to always consist of valid characters. Passing your encryption key through a text encoding process may corrupt the key, due to the encoding process merging characters and/or removing invalid characters.

How to encrypt and decrypt files by using Symmetric keys
The symmetric encryption algorithms within the BCL implement a streaming model. You create an instance of a CryptoStream and use it to wrap up access to an underlying stream.

The CryptoStream class transforms data (i.e. encrypts or decrypts) as it passes through to the underlying storage stream. The CryptStream class is an example of the decorator design pattern.

To encrypt or decrypt data symmetrically within your application you need to perform the following tasks:

  1. Create a stream to interface to the data you will be reading or writing to
  2. Create and initialise a SymmetricAlgorithm object
  3. Call CreateEncryptor() or CreateDecryptor() to create an ICryptoTransform object
  4. Create a CryptoStream by passing in your stream and ICryptoTransform object
  5. Read/Write to the CryptoStream as if it was your original data source

The following example demonstrates the encryption and decryption process by reading and writing the contents of an encrypted text file.

using System.IO;
using System.Text;
using System.Security.Cryptography;
// Configure the desired encryption algorithm parameters
SymmetricAlgorithm sa = new RijndaelManaged();
// Encryption Example
ICryptoTransform transform = sa.CreateEncryptor();
using (Stream outputStream = new FileStream(@"\encrypted.txt", FileMode.Create))
  // Wrap the output stream up with a CryptoStream
  // which performs the data encryption
  using (Stream cryptoStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write)
    // Store data into the cryptoStream (which will encrypt it
    // and then pass it along to our outputStream for storage)
    using (TextWriter tw = new StreamWriter(cryptoStream))
      tw.WriteLine("Hello this my message to encrypt!");
// Decryption example
transform = sa.CreateDecryptor();
using (Stream inputStream = new FileStream(@"\encrypted.txt", FileMode.Open))
  // Wrap the input stream up with a CryptoStream
  // which performs the data decryption
  using (Stream cryptoStream = new CryptoStream(inputStream, transform, CryptoStreamMode.Read))
    // Read data into the cryptoStream (which will fetch encrypted
    // data from the inputStream and then decrypt it before returning
    // it to us)
    using (TextReader tr = new StreamReader(cryptoStream))
      MessageBox.Show(tr.ReadToEnd(), "Unencrypted Data");

If you look at the contents of the encrypted.txt file on the PDA device you will notice that it looks like random data. You can not determine what the message is by looking at it.

The encrypted contents of the file is binary data. If you must place this contents into a textbox control within a GUI, or send it in an email etc, you will most likely have to encode it using one of the techniques discussed in the section above about displaying encryption keys.

Notice: Typically the encryption and decryption processes would be in different parts of the application, or even on different devices. In this case you would also need to come up with a mechanism which ensures both parts of the code utilise the same initialisation vector (IV) and key parameters. Otherwise you can not be able to successfully decrypt the message.