MyMessageBox for Phone and Store apps

Tue, February 5, 2013, 02:41 AM under MobileAndEmbedded

I am sharing a class I use for both my Windows Phone 8 and Windows Store app projects.

Background and my requirements

  1. For my Windows Phone 7 projects two years ago I wrote an improved custom MessageBox class that preserves the well-known MessageBox interface while offering several advantages. I documented those and shared it for Windows Phone 7 here: Guide.BeginShowMessageBox wrapper.
  2. Aside: With Windows Phone 8 we can now use the async/await feature out of the box without taking a dependency on additional/separate pre-release software.
  3. As I try to share code between my existing Windows Phone 8 projects and my new Windows Store app projects, I wanted to preserve the calling code, so I decided to wrap the WinRT MessageDialog class in a custom class to present the same MessageBox interface to my codebase.
  4. BUT. The MessageDialog class has to be called with the await keyword preceding it (which as we know is viral) which means all my calling code will also have to use await. Which in turn means that I have to change my MessageBox wrapper to present the same interface to the shared codebase and be callable with await… for both Windows Phone projects and Windows Store app projects.

Solution

The solution is what the requirements above outlined: a single code file with a MessageBox class that you can drop in your project, regardless of whether it targets Windows Phone 8, or Windows 8 Store apps or both. Just call any of its static Show functions using await and dependent on the overload check the return type to see which button the user chose.

// example from http://www.danielmoth.com/Blog/GuideBeginShowMessageBox-Wrapper.aspx
if (await MyMessageBox.Show("my message", "my caption", "ok, got it", "that sucks")
== MyMessageBoxResult.Button1)
{
     // Do something
     Debug.WriteLine("OK");
}

The class can be downloaded from the bottom of my older blog post.


    

Debug.Assert replacement for Phone and Store apps

Sun, January 13, 2013, 09:42 PM under MobileAndEmbedded

I don’t know about you, but all my code is, and always has been, littered with Debug.Assert statements. imageI think it all started way back in my (short-lived, but impactful to me) Eiffel days, when I was applying Design by Contract. Anyway, I can’t live without Debug.Assert. Imagine my dismay when I upgraded my Windows Phone 7.x app (Translator By Moth) to Windows Phone 8 and discovered that my Debug.Assert statements would not display anything on the target and would not break in the debugger any longer! Luckily, the solution was simple and in this post I share it with you – feel free to teak it to meet your needs.

Steps to use

  1. Add a new code file to your project, delete all its contents, and paste in the code from MyDebug.cs
  2. Perform a global search in your solution replacing Debug.Assert with MyDebug.Assert
  3. Build solution and test

Now, I do not know why this functionality was broken, but I do know that it exhibits the same broken characteristics for Windows Store apps. There is a simple workaround there to use Contract.Assert which does display a message and offers an option to break in the debugger (although it doesn’t output the message to the Output window). Because I plan on code sharing between Phone and Windows 8 projects, I prefer to have the conditional compilation centralized, so I added the Contract.Assert workaround directly in MyDebug class, so that you can use this class for both platforms – enjoy and enhance!


Translator by Moth v2

Fri, December 16, 2011, 10:10 PM under MobileAndEmbedded

If you are looking for the full manual for this Windows Phone app you can find it here: "Translator by Moth".

While the manual has no images (just text), in this post I will share images and if you like them, go get "Translator by Moth" from the Windows Phone marketplace.

open the app from the app list or through a pinned tile (including secondary tiles for specific translations)

Translator by Moth appList Translator by Moth tile 

language picker (~40 languages)

Translator by Moth from Translator by Moth to Translator by Moth to Translator by Moth to

"current" page

Translator by Moth current Translator by Moth sip Translator by Moth it Translator by Moth appBarTranslator by Moth CopyPaste

"saved" page

Translator by Moth savedEmpty Translator by Moth saved Translator by Moth saved_CM

"about" page

Translator by Moth about

Like? Go get Translator by Moth!


ScrollViewer.EnsureVisible for Windows Phone

Sat, July 30, 2011, 08:06 PM under MobileAndEmbedded

In my Translator By Moth app, on both the current and saved pivot pages the need arose to programmatically scroll to the bottom. In the former, case it is when a translation takes place (if the text is too long, I want to scroll to the bottom of the translation so the user can focus on that, and not their input text for translation). In the latter case it was when a new translation is saved (it is added to the bottom of the list, so scrolling is required to make it visible). On both pages a ScrollViewer is used.

In my exploration of the APIs through intellisense and msdn I could not find a method that auto scrolled to the bottom. So I hacked together a solution where I added a blank textblock to the bottom of each page (within the ScrollViewer, but above the translated textblock and the saved list) and tried to make it scroll it into view from code. After searching the web I found a little algorithm that did most of what I wanted (sorry, I do not have the reference handy, but thank you whoever it was) that after minor tweaking I turned into an extension method for the ScrollViewer that is very easy to use:

	this.Scroller.EnsureVisible(this.BlankText);

The method itself I share with you here:

    public static void EnsureVisible(this System.Windows.Controls.ScrollViewer scroller, 
                                          System.Windows.UIElement uiElem)
    {
      System.Diagnostics.Debug.Assert(scroller != null);
      System.Diagnostics.Debug.Assert(uiElem != null);

      scroller.UpdateLayout();

      double maxScrollPos = scroller.ExtentHeight - scroller.ViewportHeight;
      double scrollPos = 
              scroller.VerticalOffset - 
              scroller.TransformToVisual(uiElem).Transform(new System.Windows.Point(0, 0)).Y;

      if (scrollPos > maxScrollPos) scrollPos = maxScrollPos;
      else if (scrollPos < 0) scrollPos = 0;

      scroller.ScrollToVerticalOffset(scrollPos);
    }

I am sure there are better ways, but this "worked for me" :-)


Monitor network connectivity in WP7 apps

Fri, May 27, 2011, 04:32 PM under MobileAndEmbedded

Most interesting Windows Phone apps rely on some network service for their functionality. So at some point in your app you may need to know programmatically if there is network connection available or not.

For example, the Translator by Moth app relies on the Bing Translation service for translations. When a request for translation (text or voice) is made, the network call may fail. The failure reason is not evident from any of the return results, so I check the connection to see if it is present. Dependent on that, a different message is shown to the user. Before the translation phase is even reached, at the app start up time the Bing service is queried for its list of  languages; in that case I don't want to show the user a message and instead want to be notified when the network is available in order to send the query out again.

So for those two requirements (which I imagine are common in other apps) I wrote a simple wrapper MyNetwork static class to the framework APIs:

  1. Call once MyNetwork.MonitorNetworkAvailability() method so it monitors the network change
  2. At any time check the MyNetwork.IsConnected property to check for network presence
  3. Subscribe to its MyNetwork.ConnectionEstablished event
  4. Optionally, during debugging use its MyNetwork.ChangeStatus method to simulate a change in network status

As usual, there may be better ways to achieve this, but this class works perfectly for my scenarios. You can download the code here: MyNetworks.cs.


Supporting copy 'n paste in your Windows Phone app

Tue, May 3, 2011, 09:36 PM under MobileAndEmbedded

Some Windows Phone 7 owners already have the NoDo update, and others are getting it soon. This update brings, among other things, copy & paste support for text boxes. NoDo_CopyPasteThe user taps on a piece of text (and can drag in either direction to select more/less words), a popup icon appears that when tapped copies the text to the clipboard, and then at any app that shows the soft input panel there is an icon option to paste the copied text into the associated textbox. For more read this 'how to'. Note that there is no programmatic access to the clipboard, only the end user experience I just summarized, so there is nothing you need to do for your app's textboxes to support copy & paste: it just works.

The only issue may be if in your app you use static TextBlock controls, for which the copy support will not appear, of course. That was the case with my Translator by Moth app where the translated text appears in a TextBlock.

So, I wanted the user to be able to copy directly from the translated text (without offering an editable TextBox for an area where user input does not make sense). Take a look at a screenshot of my app before I made any changes to it. I then made changes to it preserving the look and feel, yet with additional copy support (see screenshot on the right)!

So how did I achieve that? Simply by using my co-author's template (thanks Peter!): Copyable TextBlock for Windows Phone.

 

(aside: in my app even without this change there is a workaround, the user could use the "swap" feature to swap the source and target, so they can copy from the text box)


Watermark TextBox for Windows Phone

Fri, April 22, 2011, 08:01 PM under MobileAndEmbedded

In my Translator by Moth app, in the textbox where the user enters a translation I show a "prompt" for the user that goes away when they tap on it to enter text (and returns if the textbox remains/becomes empty). imageSee screenshot on the right (or download the free app to experience it).

Back in June 2006 I had shown how to achieve this for Windows Vista (TextBox prompt), and a month later implemented a pure managed version for both desktop and Windows Mobile: TextBox with Cue Banner.

So when I encountered the same need for my WP7 app, the path of least resistance for me was to convert my existing code to work for the phone.

Usage:

  1. Instead of TextBox, in your xaml use TextBoxWithPrompt.
  2. Set the TextPrompt property to the text that you want the user to be prompted with.
  3. Use the MyText property to get/set the actual entered text (never use the Text property).
  4. Optionally, via properties change the default centered alignment and italic font, for the prompt text.

It is that simple! You can grab my class here: TextBoxWithPrompt.cs

Note, that there are many alternative (probably better) xaml-based solutions, so search around for those. Like I said, since I had solved this before, it was easier for my scenario to re-use my implementation – this does not represent best practice :-)


RTL (Arabic and Hebrew) Support for Windows Phone 7

Tue, February 15, 2011, 11:12 PM under MobileAndEmbedded

Problem and Background

Currently there is no support for Right-To-Left rendering in Windows Phone 7, when developing with Silverlight (itself built on .NET Compact Framework). When I encountered that limitation, I had a flashback to 2005 when I complained about the luck of RTL on NETCF. Unfortunately, the partial solution I proposed back then requires PInvoke and there is no such support on Windows Phone today.

Fortunately, my RTL requirements this time were more modest: all I wanted to do was display correctly a translation (of Hebrew or Arabic) in my FREE WP7 translator app. For v1.0 of the app, the code received a string from the service and just put it up on the screen as the translated text. In Arabic and Hebrew, that string (incorrectly) appeared reversed. I knew that, but decided that since it is a platform limitation, I could live with it and so could the users. Yuval P, a colleague at Microsoft, pushed me to offer support for Hebrew (something that I wasn't motivated to pursue if I am honest). After many back and forths, we landed on some code that works. It is certainly not the most efficient code (quite the opposite), but it works and met the bar of minimum effort for v1.1. Thanks Yuval for insisting and contributing most of the code!

After Hebrew support was there, I thought the same solution would work for Arabic. Apparently, reversing the Arabic text is not enough: Arabic characters render themselves differently dependent on what preceded/succeeds them(!). So I needed some kind of utility that takes a reversed Arabic string and returns the same string but with the relevant characters "fixed". Luckily, another MS colleague has put out such a library (thanks Bashar): http://arabic4wp7.codeplex.com/.

RTL Solution

So you have a reversed RTL string and want to make it "right" before displaying on the screen. This is what worked for me (ymmv).

  1. Need to split the string into "lines". Not doing this and just reversing the string and sticking it a wrapping text control means that the user not only has to read right to left, they also have to read bottom up.
  2. The previous step must take into account a line length that works for both portrait and landscape modes, and of course, not break words in the middle, i.e. find natural breaks.
  3. For each line, break it up into words and reverse the order of the words and the order of the letters within each word
  4. On the previous step, do not reverse words that should be preserved, e.g. Windows and other such English words that are mixed in with the Arabic or Hebrew words. The same exclusion from reversal applies to numbers.
  5. Specifically, for Arabic, once there is a word that is reversed also change its characters.
  6. For some code paths, the above has to take into account whether the translation is "from" an RTL language or if it is "to" an RTL language.

I packaged the solution in a single code file containing a static class (see the 'Background" section above for… background and credits).

Download RTL.cs for your Windows Phone app (to see its usage in action download for FREE "The best translator app")

using RTL.cs

Enjoy, and if you decide to improve on the code, feel free to share back with me…


"Translator by Moth"

Tue, January 4, 2011, 09:47 PM under MobileAndEmbedded

updated for v2

This article serves as the manual for the Windows Phone 7 app called "Translator by Moth". The app is available from the following link:

http://social.zune.net/redirect?type=phoneApp&id=bcd09f8e-8211-e011-9264-00237de2db9e

"current" page

The "current" page is the main page of the app with language pickers, translation boxes and the application bar.

Language list pickers

The "current" page allows you to pick the "from" and "to" languages, which are populated at start time. Tapping on either of them brings up on a full screen popup the list of languages to pick from, formatted as English Name followed by Native Name (when the latter is known). In addition to the language names, they indicate which languages have playback support via a * in front of the language name. When making a selection for the "to" language, and if there is text entered for translation, a translation is performed (so there is no need to tap on the "translate" application bar button). Note that both language choices are remembered between different launches of the application.

text for translation

The textbox where you enter the translation is always enabled. When there is nothing entered in it, it displays (centered and in italics) text prompting you to enter some text for translation. When you tap on it, the prompt text disappears and it becomes truly empty, waiting for input via the keyboard that automatically pops up. The text you type is left aligned and not in italic font. The keyboard shows suggestions of text as you type. The keyboard can be dismissed either by tapping somewhere else on the screen, or via tapping on the Windows Phone hardware "back" button, or via taping on the "enter" key. In the latter case (tapping on the "enter" key), if there was text entered and if the "from" language is not blank, a translation is performed (so there is no need to tap on the "translate" application bar button). The last text entered is remembered between application launches.

translated text

The translated text appears below the "to" language (left aligned in normal font). You can tap on the translated text to copy (parts of) it. Until a translation is performed, there is a message in that space informing you of what to expect (translation appearing there). When the "current" page is cleared via the "clear" application bar button, the translated text reverts back to the message.

Note a subtle point: when a translation has been performed and subsequently you change the "from" language or the text for translation, the translated text remains in place but is now in italic font (attempting to indicate that it may be out of date). In any case, this text is not remembered between application launches.

application bar buttons and menus

There are 4 application bar buttons:

  • "translate" button takes the text for translation and translates it to the translated text, via a single network call to the bing Microsoft Translator service. If the network call fails, the user is informed via a message box. The button is disabled when there is no "from" language available or when there is not text for translation entered.
  • "play" button takes the translated text and plays it out loud in a native speaker's voice (of the "to" language), via a single network call to the bing Microsoft Translator service. If the network call fails, the user is informed via a message box. The button is disabled when there is no "to" language available or when there is no translated text available.
  • "clear" button clears any user text entered in the text for translation box and any translation present in the translated text box. If both of those are already empty, the button is disabled. It also stops any playback if there is one in flight.
  • "save" button saves the entire translation ("from" language, "to" language, text for translation, and translated text) to the bottom of the "saved" page (described later), and simultaneously switches to the "saved" page. The button is disabled if there is no translation or the translation is not up to date (i.e. one of the elements have been changed).

…and there are also 6 application bar menus:

  • "swap to and from languages" menu swaps around the "from" and "to" languages. It also takes the translated text and inserts it in the text for translation area. The translated text area becomes blank. The menu is disabled when there is no "from" and "to" language info. This command is also useful if you wish to copy the translated text (simply swap and then select it).
  • "send translation via sms" menu takes the translated text and creates an SMS message containing it. The menu is disabled when there is no translation present.
  • "send translation via email" menu takes the translated text and creates an email message containing it (after you choose which email account you want to use). The menu is disabled when there is no translation present.
  • "post to social network" menu opens a new phone page where you can choose the social networks to which you want to post the translation. The social network options depend on what you have configured on your phone, and can be Facebook, windows live, LinkedIn, and twitter.
  • "pin to start" menu pins the current translation to the start screen. See description further down.
  • "about" menu shows the "about" page described later.

"saved" page

The "saved" page is initially empty. You can add translations to it by translating text on the "current" page and then tapping the application bar "save" button. Once a translation appears in the list, you can read it all offline (both the "from" and "to" text). Thus, you can create your own phrasebook list, which is remembered between application launches (it is stored on your device). To listen to the translation, simply tap on it – this is only available for languages that support playback, as indicated by the * in front of them. The sound is retrieved via a single network call to the bing Microsoft Translator service (if it fails an appropriate message is displayed in a message box). Tap and hold on a saved translation to bring up a context menu with 5 items:

  • "pin to start" menu pins the selected saved translation to the start screen. See description further down.
  • "move to top" menu moves the selected item to the top of the saved list (and scrolls there so it is still in view)
  • "copy to current" menu takes the "from" and "to" information (language and text), and populates the "current" page with it (switching at the same time to the current page). This allows you to make tweaks to the translation (text or languages) and potentially save it back as a new item. Note that the action makes a copy of the translation, so you are not actually editing the existing saved translation (which remains intact).
  • "delete" menu deletes the selected translation.
  • "delete all" menu deletes all saved translations from the "saved" page – there is no way to get that info back other than re-entering it, so be cautious.

Note: Once playback of a translation has been retrieved via a network call, your Windows Phone caches the results. What this means is that as long as you play a saved translation once, it is likely that it will be available to you for some time, even when there is no network connection.

"about" page

The "about" page provides some textual information including version, credits, the ability to tap on the logo icon to rate the app, and a link to the creator's blog (that you can follow on your Windows Phone device). Use that link to discover the email for any feedback.

Live and secondary tiles

When you pin the app tile to the start screen, you'll observe that the tile will "flip" at certain intervals. While the front of the tile is the familiar logo and app title, the back of the tile will show the text and language selection from the last time you closed the app.

In addition, you can pin secondary tiles from within the app, either from the current page (see the app bar menu above) or from the saved page (see the context menu above). In either case, a new tile will be created for you on the start screen for the selected translation. On these secondary tiles, on the front is the familiar logo and the target translation language in English; on the back of the tile is the translated text and the language in the native alphabet. When you tap on these secondary tiles, they will open the "Translator by Moth" app and have preloaded the selected translation language and translation. So these secondary tiles are shortcuts directly to the translation you were interested in.

Other UI design info

"Translator by Moth" has been designed from scratch for Windows Phone, using the nice pivot control and application bar. It also supports both portrait and landscape orientations, and looks equally good in both the light and the dark theme. Other than the default black and white colors, it uses the user's chosen accent color. Finally, it has been updated to take advantage of new NoDo/7.x/Mango/8.x phone features

Feedback and support

Please report (via the email on the blog) any bugs you encounter or opportunities for performance improvements and they will be fixed in the next update. Suggestions for new features will be considered. If you like the app, don't forget to rate "Translator by Moth" on the marketplace.


Guide.BeginShowMessageBox wrapper

Thu, December 30, 2010, 12:38 AM under MobileAndEmbedded

imageWhile coding for Windows Phone 7 using Silverlight, I was really disappointed with the built-in MessageBox class, so I found an alternative. My disappointment was the fact that:

  1. Display of the messagebox causes the phone to vibrate (!)
  2. Display of the messagebox causes the phone to make an annoying sound.
  3. You can only have "ok" and "cancel" buttons (no other button captions).

I was using the messagebox something like this:

      // Produces unwanted sound and vibration. 
      // ...plus no customization of button captions.
      if (MessageBox.Show("my message", "my caption", MessageBoxButton.OKCancel)
              == MessageBoxResult.OK)
      {
        // Do something
        Debug.WriteLine("OK");
      }

…and wanted to make minimal changes throughout my code to change it to this:

      // no sound or vibration
      // ...plus bonus of customizing button captions
      if (MyMessageBox.Show("my message", "my caption", "ok, got it", "that sucks")
              == MyMessageBoxResult.Button1)
      {
        // Do something
        Debug.WriteLine("OK");
      }

It turns out there is a much more powerful class in the XNA framework that delivered on my requirements (and offers even more features that I didn't need like choice of sounds and not blocking the caller): Guide.BeginShowMessageBox. You can use it simply by adding an assembly reference to Microsoft.Xna.Framework.GamerServices.

I wrote a little wrapper for my needs and you can find it here (ready to enhance with your needs): MyMessageBox.cs.old.txt.

UPDATE 2013: If you don’t mind using await in front of the call to MyMessageBox.Show, I have an updated class that works for both Windows Phone 8 and for Windows 8 Store apps here: MyMessageBox.cs.txt.


Windows Phone 7 developer resources

Thu, September 16, 2010, 11:36 AM under MobileAndEmbedded

Developers of Windows Mobile 6.x (and indeed Windows CE) applications still use the rich .NET Compact Framework 3.5 with Visual Studio 2008 for development. That is still a great platform and the Mobile Development Handbook is still a useful resource (if I may say so myself :-).

The release of Windows Phone 7, changes the programming paradigm. The programming model has NETCF in its guts, but the developer uses the Silverlight or XNA APIs (and they can call from one into the other). I thought I'd gather here (for your reference and mine) the top 10 resources for getting started.

  1. Windows Phone Developer Home - get the official word and latest announcements.
  2. Windows Phone Developer Tools RTW - download the free developer tools (on my machine the installation took 30 minutes, over my existing vanilla Visual Studio 2010 install).
  3. Windows Phone 7 Jump Start video training - watch the 12 sessions by Wigley/Miles.
  4. Windows Phone 7 Developer Training Kit - work through the labs.
  5. Windows Phone RSS tag - channel9 has tons more WP7 videos, stay tuned.
  6. Windows Phone 7 in 7 Minutes - watch 20 7-minute videos.
  7. Programming Windows Phone 7 - read 11 free chapters from Petzold's eBook.
  8. The Windows Phone Developer Blog - subscribe to the official blog.
  9. Getting Started with Windows Phone Development - explore all links from the MSDN Library root page.           
  10. Silverlight for Windows Phone – another root MSDN library page.

If after all that you get your hands dirty and still can't find the answer ask questions at the WP7 development MSDN Forum.

 

On a personal note, I was pleased to see that the Parallel Stacks debugger window works fine with the WP7 project ;-)

Parallel Stacks and WP7


Windows Mobile development in VS2010

Wed, October 7, 2009, 09:55 PM under MobileAndEmbedded
With the release yesterday of Windows Phone (press release , blog post , training , launch site) and with the upcoming release of Visual Studio 2010 Beta2, we are starting to see the question again: "where is the smart device development support in Visual Studio 2010?".

This question was asked a lot during the VS2010 Beta1 timeframe and the answer remains the same: Mobile Development Tools are now aligned to the mobile platform releases and are hence decoupled from Visual Studio releases, so I personally guess we should see tool support in VS2010 when a new mobile platform is released. For now, stick with VS2008 for device development needs (official statement) and keep an eye on the Windows Mobile Development Center.

Mobile developer? The Race is On!

Fri, August 14, 2009, 12:17 PM under MobileAndEmbedded
In case my Windows Mobile developer friends have missed this, Loke shares how the Race is On!

Sharing Assets Between the .NET Compact Framework and the .NET Framework

Wed, June 4, 2008, 10:02 PM under MobileAndEmbedded
Thank you for attending the developer session with the title of this blog post. Below are some resources for you.

- Download the slides and demos for this talk here.
- For my relevant blog posts, follow all the links (the hyperlinked numbers 1-9) from this blog post.
- Best of all, ignore all of the above, and just read my MSDN mag article which I link to from here.

Mobile Book in Chinese

Sat, May 17, 2008, 03:54 PM under MobileAndEmbedded
Catching up with my inbox I found a message that our book is now translated to Chinese! Peter beat me to it with sharing the news so go over to his blog post with an image of the cover.

Volatile RegistryKey

Thu, December 20, 2007, 12:48 PM under dotNET | MobileAndEmbedded
When the Windows Mobile Managed APIs were introduced they made use of a new underlying Windows CE 5 feature (that WM 5.0 is based on): volatile registry keys (see dwOptions). Volatile keys are also available on normal/desktop/server Windows. In a nutshell, volatile registry keys do not survive an OS reboot so anything you write there is not persisted the next time you restart. The obvious question at this point is: Does the managed registry API support volatile keys? The answer is "no" for both the full .NET Framework and the .NET Compact Framework. Let's explore an UNSUPPORTED solution for both platforms.

On the surface without too much digging it appears that the native RegCreateKeyEx is wrapped by RegistryKey.CreateSubKey. So for the BCL team to add support for volatile keys to the managed API, one way would be to add a new overload to CreateSubKey that accepts our desire for volatileness and at the point it calls RegCreateKeyEx it passes in REG_OPTION_VOLATILE instead of 0 which is what the implementation does now (i.e. a change of one line of code).

But since we are not the BCL team and we cannot edit the library's code, we can create a helper static method to do that job for us. Maybe that method would live in the static Program class with a signature something like this:
public static RegistryKey CreateSubKey(this RegistryKey rk, string subkey, bool isVolatile)
{
if (!isVolatile)
{
return rk.CreateSubKey(subkey); // i.e. no change
}
else
{
// call our own method since we cannot change the framework's
return MothCreateVolatileSubKey(rk, subkey, RegistryKeyPermissionCheck.Default);
}
}
Note on the above:
1. I've made the method an extension method which means that we can call it in either of these two ways (the first being more natural):
RegistryKey rk1 = Registry.CurrentUser.CreateSubKey("my vol", true);

RegistryKey rk2 = Program.CreateSubKey(Registry.CurrentUser, "my vol", true);
2. As you can imagine the implementation of MothCreateVolatileSubKey is a simple duplication of the implementation of the existing framework method with 2 differences:
a) Where the framework's implementation passes 0 as the 4th argument to the native RegCreateKeyEx, we will pass REG_OPTION_VOLATILE.
b) Wherever the framework's implementation calls private/internal methods we will have to use reflection to access them (unless you fancy duplicating all of that too;)).

Yes, I know the above is very ugly, very unsupported and very much a hack. I have created a VS2008 solution with the above that you can use to test it out at your own risk. It contains two projects, one for NETCF to run on your Windows Mobile and one for the desktop.

It is quite possible that by running the code from the project your machine will be wiped clean and that your monitor will go up in flames after transferring all your money out of your bank account. You have been warned!

So, at your own risk, get the VS2008 projects here.

ASP.NET for Windows CE

Tue, October 30, 2007, 02:11 AM under MobileAndEmbedded
Three years ago I was speculating about this very topic, and was planning to implement it for the company I worked for at the time. I never got the chance, but the OpenNETCF guys delivered Padarn today! Very cool...

PowerShell combined with CoreCon

Wed, September 26, 2007, 05:17 PM under MobileAndEmbedded
Loke Uei has a cool walkthrough of using PowerShell to talk to the Device Emulator via the new managed CoreCon APIs. Check it out.

Write your own GC Heap Viewer for NETCF

Fri, September 21, 2007, 02:30 PM under MobileAndEmbedded
Steven only posts once in a blue moon but when he does every .NET Compact Framework developer should take notice. Read the details of the GC Heap data file format.

Power Toys for .NET CF 3.5

Thu, September 13, 2007, 01:05 AM under MobileAndEmbedded
If you are playing with Beta 2 of NET CF 3.5 then you are probably missing the brand new diagnostic/performance/configuration/etc tools. Well now there are more than ever before and available in the form of a Power Toys package that you can get here.

[Source: NETCF blog]

NETCF Beta 2

Sat, August 18, 2007, 06:49 PM under MobileAndEmbedded | Orcas
I got asked about new things in .NET Compact Framework 3.5 with the VS2008 Beta 2 release. Well, the NETCF team did all their good work very early on so there aren't any new features in this drop. Tons of new stuff compared to v2.0 of course, see my previous posts starting here.

In Beta 2 of NETCF 3.5 compared to Beta 1, I observe a couple of classes gone from the WCF stuff, some refactoring in System.Xml.Linq and some changes to mirror the System.Core changes I mentioned here in the 1st paragraph for the full framework.

The only major change is that the DataSet extensions have been factored into their own assembly: System.DataSet.Extensions.dll. This again mirrors the full framework implementation but internally the classes are not in sync yet. They will be by RTM, so my suggestion is to explore the LINQ to DataSet on the desktop, and use the same skills/code when it finally makes its appearance in the NETCF as well.

Facebook from .NET

Tue, July 24, 2007, 03:20 PM under MobileAndEmbedded | Links
It looks like the world has gone crazy with this Facebook thingy. I have zero time for real socialising let alone for online socializing so I have ignored the whole thing. By "ignored", I mean I have acted on invitations (meaning I had to create my space or whatever it is called) and other things that come into my email inbox, but I have not customised anything or initiated connections/invitations or even uploaded a photo. So why am I talking about it here?

It turns out that there is a .NET API for Facebook! It also looks like supreme device developer and all around top geezer, The Foot, has started porting it to support the .NET Compact Framework. Check out his blog post for more (which follows on from this one that includes screenshots).

WISP Lite in WM6

Wed, July 18, 2007, 04:33 AM under MobileAndEmbedded
A little known brand new feature in Windows Mobile 6 is the ability to do inking using the same technology as for the Tablet PC (Windows Ink Service Platform). Luis talks about it on the WM blog with a code example. One of the commenters of that blog post asked for a managed version (I don't blame him; in this day and age what was the WM dev team thinking?!). To get a managed version (and a bit more info on the API) go to Alex's blog and look for the hidden links.

Windows Mobile Security for devs

Mon, July 16, 2007, 04:41 PM under MobileAndEmbedded
Via David I found this WM security blog post and via that I found this old but great WM security article.

After you consume the info above (and most of my trusted mobile dev readers will already know that stuff) then you are left craving for a pretty and concise diagram that illustrates the flow of an app's execution on Windows Mobile. I hope your craving is satisfied with the following (thanks Mark!):

At some future point you should expect to see the diagram linked somewhere from this excellent page of security resources for Device Projects.

Web development for Mobile

Fri, July 13, 2007, 09:06 AM under MobileAndEmbedded
Occasionally I get people asking me about developing web apps that are accessible from Windows Mobile. Every time I explain how with something as powerful as the .NET Compact Framework, they should be writing smart clients on the device that can also work in offline mode, cache data and offer a richer user experience. These apps can then access their server as needed either via web services or via some kind of SQL synchronization mechanism if that is what they are using on their backend. Some people insist though on offering a suboptimal solution to their customers so what answer do we have for those? Head over to Thom's blog to explore Mobile Web Development with ASP.NET.

A related question I hear is "what capabilities does Pocket Internet Explorer (PIE) offer?". Well, it is not called that anymore, it is IE Mobile and there is a homonymous blog. Visit their blog for tons of useful info, including the standards support in IE Mobile.

Finally, one of the co-authors of my book wrote in the distant past a book on mobile web dev that you may be interested in.

PS: Might as well link to my answer for the often asked question about Silverlight for Mobile.

Slides from my MEDC sessions

Thu, June 28, 2007, 11:17 PM under MobileAndEmbedded
The MEDC world tour is over and my contribution was participating in panels and presenting at two locations: Las Vegas and Berlin. In both the US and the European events I delivered the sharing assets and the mobile UI tips sessions. You can find the powerpoint slides from both my breakouts in this ZIP file (tip: some of the slides have URLs for more info at the bottom).

Slides: Windows Mobile Managed APIs

Sun, June 24, 2007, 03:16 AM under MobileAndEmbedded
A few people asked me this week for my material for the Windows Mobile session I did at DevDays last week.

You can get the demos from this post. What you'll also find from there are links to screencasts I have done and other relevant blog posts. Note that even though those demos are for WM5 projects running in VS2005, the code is identical to what I showed in VS2008 Beta 1 targeting WM6 – no code change whatsoever.

Download the slides here (pptx inside another ZIP). If you are on a legacy version of powerpoint, see this post.

Using Extension methods for cross-framework projects

Tue, June 19, 2007, 10:11 AM under MobileAndEmbedded
In this post I assume you have read my blog entry on Extension Methods. When I described extension methods I finished by saying:
"Overall, I like this feature *a lot* (will post some concrete examples of why in the future)."
The time has come to explain myself. I've been waiting for my MSDN magasine article to go live so it can be the first to describe the proposed usage :-)

So to quote myself from the article:
"While using .NET Compact Framework classes, the occasion often arises that a particular class has members missing compared to the full Framework. Typically, developers have to write the missing functionality themselves and then decide whether to use inheritance if possible to add the missing members or add them to a utility helper class."
Please visit the article to see a good example of how extension methods can help with the above scenario.

When we faced this issue in the SDF from OpenNETCF, we took one decision in some cases (utility classes) and the other decision (inheritance) in other cases. Unfortunately, utility classes suffer from the inherent non-discoverability for client code and inheritance is not always possible due to sealed classes. So many times we opted for a 3rd approach (that I was never entirely comfortable with): Introducing a replacement class e.g. TextBox2. Now, there are still scenarios where that approach is the only viable technique, but for some cases using the Extension methods as I describe in the article is a better alternative.

I'll just give one more example here. If we wanted the System.Windows.Forms.Timer class in the NETCF to have a compatible interface with the desktop version, one thing we'd have to do is add Start and Stop methods. Easily achieved by dropping the following code file in just the device project and not the desktop project:
public static class TimerExtensions
{
public static void Start(this Timer t)
{
t.Enabled = true;
}
public static void Stop(this Timer t)
{
t.Enabled = false;
}
}
...and then the codefile that uses the Timer can be the same on both platforms, e.g.
private void menuItem1_Click(object sender, EventArgs e)
{
timer1.Start();
}

private void menuItem2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
We have seemingly added extra methods to a class so our utility methods are discoverable and if the real NETCF class ever got those methods implemented, our code gracefully bows out at runtime. Try it out... coding is believing how cool this is :)

MSDN mag article: Cross-framework code

Mon, June 18, 2007, 03:31 AM under MobileAndEmbedded
In my July MSDN magazine article, I have collected in a single place my tips for writing cross-platform managed code, in this case meaning code that targets both the Windows desktop and Windows Mobile. Even though the article was written with the .NET Compact Framework and the full .NET Framework in mind, most of the techniques apply in other scenarios as well.

Consider how many frameworks/CLRs we have today: .NET Compact Framework, full .NET Framework (aka desktop framework), .NET Micro Framework, Silverlight CLR, MONO (framework for non-Windows platform) etc. To that list you should add scenarios where you wish to target two different versions of the same framework type e.g. both v1.0 and v2.0 of the NETCF/Full Fx. Even though it looks the same, the framework/CLR between versions is effectively a different framework so again some of the principles in the article apply. Read the article here.

My book is now in my hands

Mon, June 11, 2007, 06:13 AM under MobileAndEmbedded | Personal | Links
Mobile Development Handbook

My book is now in my hands, and here is the proof... and another wobbly photo of the back :-D

At some point in 2006 I started writing a book and at some point in April 2007 we completed the project. I say "we", because I had two excellent co-authors, both long standing Device Application MVPs: Peter Foot and Andy Wigley. I would have liked to be able to say that I also am a .NET Compact Framework MVP, but unfortunately I lost that title when joining Microsoft last year as per the rules.

We explicitly targeted two audiences with our book and implicitly excluded one audience segment:
1. Existing C# and VB device developers - YES
If you are already targeting Windows Mobile devices you will know that all existing books talk about version 1.0 of the .NET Compact Framework and Visual Studio.NET 2003. Since those times there have been three service packs for v1.0, version 2.0 with two service packs and, of course, Visual Studio 2005. Furthermore, v3.5 is in Beta 1 right now as is Visual Studio "Orcas". Our book covers what is new in the .NET Compact Framework and Visual Studio 2005 compared to their predecessors. It also covers throughout the chapters, but also in a dedicated chapter, version 3.5 of the NETCF and VS "Orcas" for Devices.

2. Existing .NET developers who are complete newbies to device development - YES
There are millions of proficient .NET desktop developers that would like to know how to write code for their mobile device or generally want to find out how to transfer their skills or business logic to the mobile platform. The book's tone is certainly aimed directly to those developers by continually contrasting and comparing with desktop development as applicable, highlighting what is different or missing when doing device development.

3. Existing native device developers - NO
This book is all about managed code, but we never introduce any basic .NET concepts from scratch. We expect readers to know about those either through experience with previous versions of NETCF or through .NET desktop development. So if you are a native device developer, you should pick up another book to learn the basics of .NET. We also have made no assumptions of knowledge about the Windows CE and Windows Mobile platform. The reason is so desktop developers can get an introduction to the whole stack/environment and not just the dev platform and tools. So, as a native device developer, you will encounter concepts explained that you probably already are intimately familiar with.

Whether you are looking for a book to read cover-to-cover or for a reference that you go back to, this book will fulfil your needs. It isn't just a book on the raw technology, but more importantly it captures lessons from developers that have practised mobile and embedded development in the real world.

Mobile Development Handbook

Mobile Development Handbook

Thu, May 31, 2007, 02:08 PM under MobileAndEmbedded | Personal
Finally, the world gets an up to date book on Mobile Development! You can browse it at amazon or look for it at your favourite book shop online or offline.

Its 600+ pages are spread over the following 18 chapters:
1. .NET Compact Framework—a Platform on the Move
2. Building a Microsoft Windows Forms GUI
3. Using SQL Server 2005 Compact Edition and Other Data Stores
4. Catching Errors, Testing, and Debugging
5. Understanding and Optimizing .NET Compact Framework Performance
6. Completing the Application: Packaging and Deployment
7. Exchanging Data with Backend Servers
8. Networking
9. Getting Connected
10. Security Programming for Mobile Applications
11. Threading
12. Graphics Programming
13. Direct3D Mobile
14. Interoperating with the Platform
15. Building Custom Controls
16. Internationalization
17. Developing with Windows Mobile
18. Introducing .NET Compact Framework Version 3.5 and Visual Studio "Orcas"
I highly recommended you check it out, for example, on the publisher's official book page.

NET CF Beta 1 – what is new

Sun, May 27, 2007, 08:43 AM under MobileAndEmbedded
With Orcas Beta 1 you also get NETCF Beta 1 with a build number of 7066. The last public NETCF drop was in the January CTP (and remained unchanged in the March CTP) with a build number of 6282. I documented what was new in that build of v3.5 compared to v2.0 and added a couple more later. Those new APIs are all still in build 7066 and in addition we also get the ones below:

* System.Delegate gets a new CreateDelegate static method and the two associated properties: Method and Target.

* There are new types in the System.Security.Cryptography (in mscorlib): AsymmetricKeyExchangeDeformatter (and the Formatter) and RSAPKCS1KeyExchangeFormatter (and the Deformatter).

* X509 in System.dll: X509Store, X509CertificateCollection, ClientCertificates property on System.Net.HttpWebRequest and 4 enums in System.Security.Cryptography.X509Certificates (OpenFlags, StoreLocation, StoreName, X509FindType).

* DataGridCell was moved from system.windows.forms.datagrid.dll to system.windows.forms.dll

In addition to the list above (inc. the ones from my links above), I previously mentioned the headline NET CF features. Well, finally in this Beta 1 drop you can play with those! The LINQ implementation in System.Core.dll is now compatible with the desktop naming and we also get the LINQ to XML implementation in System.Xml.Linq. The Compact WCF implementation resides in the new assemblies System.ServiceModel.dll (dependencies of which include the new System.Runtime.Serialization.dll) and Microsoft.ServiceModel.Channels.Mail.dll. For a "Hello World" example, check out Mark's two blog posts.

If at this point you are ready to play with this stuff, then first visit this download page for two reasons:
1. It includes some additional new features that are not visible at the public API level that I describe in my posts.
2. If you proceed with the download you will actually be able to compile projects referencing the Compact WCF assemblies. Simply remove your existing "Microsoft .Net Compact Framework 3.5 Pre-Release" and install the download (same build number as above, but with correctly signed assemblies).

IL support by Compact CLR

Thu, April 19, 2007, 01:15 PM under MobileAndEmbedded
While chatting with users of a new .NET language that will RTM later this year (Vulcan.NET), I asked what they were doing for .NET Compact Framework support. They had most of it pretty much sussed. They understood that the tool support is the biggest hurdle since, at the end of the day, their language compiles down to IL so there should be no issues.

That last statement is true except the NETCF CLR only understands a (very rich) subset of the entire IL set. It doesn't support some niche opcodes mostly used by managed C++ (which the NETCF does not support). I promised I'd find the list of what is supported and what isn't. Dan from the NETCF team has posted such a table on his blog and even though it was written for v2.0 it still holds true for v3.5 of the NETCF. Check it out here.

Visual Studio for Devices features in Orcas

Wed, March 28, 2007, 09:35 AM under MobileAndEmbedded
While we looked at new features in NETCF 3.5 for the device developer, there are also tons of improvements in the IDE (VSD "Orcas"), the top 5 IMO being:

1. Unit Testing for Devices
Note that this also works for v2.0 device projects in Orcas too, yay!

2. New Project dialog

3. Device Emulator v3
This has all the goodness of Device Emulator v2.0 plus it can be automated/scripted via COM - the clue is the DEMComInterface.idl file in your DE installation directory.

4. Device Configuration Manager & Device Certificate Manager
Previously available as a powertoy for WM5. To see them in action, from your VS Orcas Tools menu, select Device Security Manager:


5. Windows Mobile 5 SDKs and .NET Compact Framework v2.0 SP2 in the box. No more need for separate downloads :)

New project dialog for VSD in Orcas

Wed, March 28, 2007, 09:16 AM under MobileAndEmbedded
UPDATE: After Beta 1 I updated the text below with a new addition/screenshot and struck out the inapplicable text (bug fixed).

Nick blogged about this first, and Neil followed. Both have screenshots on their blogs so check them out.


If you ask me, we needed this simplicity for newbies to device development because the old approach was way too confusing. Having said that, previously I could create any project type in two clicks and now I need a lot more; so penalising the expert user is definitely the case here IMO. Rule number one of UI development: less clicks is good. Rule number two: offer two navigation paths: one for the novice, one for the expert.

Regardless of the above, before Orcas RTMs, we have to fix the combobox behaviour: When I select NETCF version 2.0 in the bottom combobox and then select a platform in the top, why the heck does the value in the bottom combobox revert to the default of 3.5? Rule number three of UI development: If I have made selection, don't revert it based on another selection on the same dialog! What makes it worst in this instance is that when selecting something in the top combobox, the bottom combobox is hidden out of view so the change goes unnoticed unless you are looking for it.

Also, again regardless to the above, I would expect those combobox values to be remembered between different launches but unfortunately they are not (yet?).

As of Beta 1, the dialog has a new addition at the bottom: a hyperlink to get new SDKs (e.g the WM6 SDKs).

FileAs in Windows Mobile 6

Sun, March 18, 2007, 04:41 AM under MobileAndEmbedded
Whinge and you shall receive. 18 months ago I moaned about the lack of FileAs in Windows Mobile 5.0 and showed how to achieve that programmatically . WM6 offers it out of the box in the UI as you can see below :)

NETCF SP2 ships

Fri, March 9, 2007, 08:40 AM under MobileAndEmbedded
I am late with this news (stuck in a place with no network connection).

Build 7045 (ie 2.0.7045.0) of the .NET Compact Framework is out of the door. No need to copy/paste here what is fixed since it is described on the download page.

One of the big ones is new diagnostics (that finally work on Vista) and, as usual, Steven has all the details.

NETCF 3.5 Headliner Features

Thu, February 15, 2007, 03:06 PM under MobileAndEmbedded
Over the last two posts I enumerated additions to the .NET Compact Framework 3.5, and there will be more posts as more Orcas CTPs come out. In particular, the two headline items of NETCF 3.5 are not listed at all in my previous two blog entries and they are: Compact WCF and Compact LINQ.

1. I have mentioned before Compact WCF. It is not in the January CTP, but when it does appear I’ll let you know.

2. LINQ is a topic that I’ll be talking a lot more about with regards to the full framework 2.5. Once I've written a few posts on that, I will come back to indicate what is missing from Compact LINQ [1].

The best people to describe the headline features and focus areas of the NETCF 3.5 are the Compact Framework team of course and they have done so here.

Cheers
Daniel

[1] If you are familiar with LINQ already, note that in the Jan “Orcas” CTP the NETCF LINQ bits use the old namespaces (e.g. System.Query ) in line with the May 2006 LINQ CTP rather than move on to the new System.Linq namespace. They are obviously aligned in future versions. Namespaces aside, the Compact LINQ implementation largely lives in System.Core assembly like its big brother.

More NETCF 3.5 Additions

Wed, February 14, 2007, 04:56 AM under MobileAndEmbedded
All the API additions I listed in my previous .NET Compact Framework 3.5 post, are namespaces/types/members that were already present in the full dotnet Framework v2.0 and are now also part of the NETCF 3.5

Here I will list a couple of additions that are brand new:

* When querying the Platform property of the static OSVersion property of the System.Environment class, we get back the PlatformID enumeration. NETCF 2.0 had a smaller list than the full framework and now with 3.5 not only it catches up by adding the Unix value but it even goes further by adding a brand new value: Xbox (not a surprise if you read this).
If you ask me, the full framework team should also add this enumeration value for code compatibility.

The other addition is entirely specific to device development and hence lives under the Microsoft.WindowsCE.Forms assembly. The SystemSettings class gets a new property (to make a grand total of 2!) named WinCEPlatform that returns the homonymous enumeration which has 3 values: WinCEGeneric, PocketPC and Smartphone
(I guess we’ll have to learn to map those last two to WM6 professional and standard :-p)

Next I'll list the real headlines of NETCF v3.5

.NET Micro Framework SDK

Tue, February 13, 2007, 06:19 AM under MobileAndEmbedded
Hot from the factory, get it here.


Just like the WM6 SDK, works fine on Vista on top of VS2005 SP1 as the screenshots show.

NETCF 3.5 API additions

Mon, February 12, 2007, 01:23 PM under MobileAndEmbedded
The next version number of the .NET Compact Framework is 3.5, compared to version number 2.0 that ships today. This is so the version numbers can align with v3.5 of the full framework (NetFx3.5). You can play with NETCF 3.5 in the Orcas Jan CTP.

Below is some new NETCF stuff that I found (v3.5.6282.0):

* Remember the EventWaitHandle class that I wrote 2 years ago? It is now part of the compact framework (System.Threading). As part of the addition, the inheritance hierarchies have changed so AutoResetEvent and ManualResetEvent now inherit from EventWaitHandle and not WaitHandle (making this blog entry half-obsolete :)).

* Remember the Stopwatch class that I wrote? It is now in the CF (System.Diagnostics).

* The Array class get the Resize method and some new Sort overloads.

* The CompilerGeneratedAttribute class from the System.Runtime.CompilerServices namespace is now added.

* The SerializationException class from the System.Runtime.Serialization namespace is added.

* System.Text.StringBuilder gets a new overload for the AppendFormat method and also both overloads of the AppendLine method.

* The System.Threading.Thread class gets the static MemoryBarrier method.

* The String class now contains the Contains method.

* A whole bunch of classes get a public Dispose method including GraphicsStream, FileStream, MemoryStream, StreamReader, StreamWriter, StringReader, StringWriter, TextReader, TextWriter and others.

* To support the next addition, the InvalidDataException class is added to the System.IO namespace in System.dll

* We get the entire System.IO.Compression namespace (i.e. GZipStream, DeflateStream, CompressionMode) from the System.dll

* Relevant to the previous addition, there is a new enum System.Net.DecompressionMethods that is the type of the new property AutomaticDecompression on the HttpWebRequest class.

* We get the entire System.Media namespace (SoundPlayer, SystemSound, SystemSounds) from the System.dll

* Mainly to support the previous addition, we get two classes in the System.ComponentModel namespace: AsyncCompletedEventArgs and AsyncCompletedEventHandler.

* The Trace class from the System.Diagnostics namespace only had 3 overloads of the Assert method. Now it becomes much more useful with 4 overloads for each of the methods Write, WriteIf, WriteLine and WriteLineIf. It also gets the Fail, Flush and Close methods. Add to that the new TextWriterTraceListener and tracing looks much better overall in NETCF v3.5

Stay tuned for more coming this week...

Windows Mobile 6 SDKs

Fri, February 9, 2007, 07:31 PM under MobileAndEmbedded
Remember, you heard/saw it here first!

It looks like the Windows Mobile 6 SDKs are out. Gone are the “for Pocket PC” and “for Smartphone” monikers. Instead, there is Professional and Standard... another mark of the convergence of the two form factors no doubt :-)


As you can see from the images in this post, the install works great on VS2005 SP1 on Vista!

UPDATE: When they are back online I’ll let you know. Please take your complaints here.
UPDATE 2: They are back online and I've updated the link above. Additional information here.

Windows Mobile 6

Thu, February 8, 2007, 02:30 AM under MobileAndEmbedded
I *think* engadget are the first to break the news that what was codename "Crossbow" is now officially Windows Mobile 6

Mel has the screenshots and links to reviews, Loke lists the developer features, Scott talks about the security improvements, John asks us to stay tuned for more and the Outlook Mobile team lists their favourite features .

Like Peter says, it will be hard to get devices in the early stages (typically takes 4-6 months), so the vast improvements in the emulator are most welcome.

Windows Mobile 5 Demo code

Sun, February 4, 2007, 04:04 PM under MobileAndEmbedded
A few people have asked me for the code I used in my WM5 Managed API screencasts (part one, two, and three). While I can’t find that exact code, it was almost identical to what I used in my Tech Ed session last year, which luckily I could find. You may download the VS2005 project here.

Windows Mobile Managed APIs

Tue, January 16, 2007, 09:47 AM under MobileAndEmbedded
A very long time ago I blogged a bit about the Windows Mobile 5.0 managed APIs (also see this).

Recently I also described how to work around installing the free WM5.0 SDK on Windows Vista.

With v5.0 now being the de facto standard of Windows Mobile devices out there and given that the next version of Windows Mobile fully supports these APIs, it is never too late to jump in and learn how to use them and what they are about. In December I wrote a short article for the msdn flash on this very topic (subscribe to the flash now if you don’t already!).

So, if you want to learn more about the WM v5.0/vNext managed APIs or need more proof that mobile development works fine on Vista, download my 3-part nugget, which I hinted at in the article:

Part 1: Configuration, Telephony and Forms [streaming file and zip download]

Part 2: Status [streaming file and zip download]

Part 3: PocketOutlook [streaming file and zip download]

Note: The first 2-3 minutes of all videos is the same introduction. The last 1-2 minutes of all videos is the same summary and links. The 17-19 minutes in between is the demo bit, different in each part of course.

Best of "The Moth" 2006

Mon, January 1, 2007, 06:56 AM under dotNET | MobileAndEmbedded | Windows | Vista | Links
Exactly two years ago on New Year's day, I wrote the Best of "The Moth" 2004 blog enrty where I picked my favorite blog entries out of 96 posts. Exactly one year ago I had to choose from 151 posts to find the ones I thought were the best in terms of content and the result was the Best of "The Moth" 2005.

The year of 2006 I made 142 blog entries and below are a select few. Happy New Year!

01. I didn't have a chance to play with it as much as I wanted to, but with very little public info available, this blog served it well: .NET Micro Framework, its product sheet and other NETMF links.

02. Recognising an idiom of the using statement.

03. A cute desktop feature implemented for the Windows Mobile/WinCE platform in a reusable NETCF control: TextBox cue banner.

04. A picture is worth a 100 words and a video is... a whole bunch of pictures! Check mine out following the instructions here for my nuggets.

05. A comprehensive collection of links for Windows Workflow Foundation (WF).

06. I collected the links to my 9 blog posts on sharing assets between desktop and mobile platforms in one place. Follow the numbered links.

07. The most controversial feature of Windows Vista is something every developer must understand: User Account Control.

08. One of Vista's features is becoming my obsession and that is SideShow. My series of SideShow gadgets blog posts will continue in 2007 and so far you can read parts one, two, three, four and five.

09. I spent 6 months last year focusing almost entirely on Vista developer features that are new and that are *not* part of NetFx3. I have catalogued my blogging & screencasting efforts in a large collection of links to content that supports my speaking engagements on Vista. IMO this blog post alone could have been the best of "The Moth" this year:
Vista-only features for the managed developer.
Stay tuned in 2007 via one of the subscribe options on the left :-)

New NETMF web pages

Thu, December 28, 2006, 08:05 AM under MobileAndEmbedded
There is a NETMF book on the horizon and check out its very own book website (thanks Mike for the heads-up).

NETMF also gains its own NETMF MSDN area :-)

More on device development on Vista

Tue, December 26, 2006, 06:07 PM under MobileAndEmbedded
Remember the problem I got when trying to deploy to a real device from VS2005 on Vista? As that blog entry says, the solution was to run VS elevated once and that rectified the issue.

On an internal list I noticed someone else had a device issue on Vista this time with Platform Builder 6.0 and their error apparently was:
PB Debugger Warning: Debugger service map is set to none. If your image has debugging support it may not boot properly

...guess what the solution was again? Correct, run VS elevated once.

The other day at an offsite I did a very short intro to Windows Mobile development so I wanted to show first a small desktop app, then the same code in a device project connecting to a device and then connecting to an emulator. I prepared the machine before the short presentation by running VS normally for the desktop project and then running another instance elevated for the device project. I also wanted to save time by launching the emulator ready to use, so I did that from the VS menu and the first instance of VS that I came across was the desktop project. Can you spot the mistake I made?

When later in the presentation I tried to connect from the device project to the emulator I was treated to this:
---------------------------
Device Emulator
---------------------------
Error: The current VMID is in use. Wait for the other application to exit.
---------------------------
OK
---------------------------
Cryptic or what? The solution of course was to shut down the emulator and this time launch it from the elevated VS instance.

The moral of the story: You cannot have an elevated VS instance talking to a non-elevated emulator.

NETCF goodness in XNA and hopefully vice versa

Fri, December 22, 2006, 05:00 PM under MobileAndEmbedded
I hope by now everyone has heard about the XNA Framework, a set of managed code libraries for writing games on the Xbox and the PC.

Not everyone will know that the engine in XNA is based on the CLR of the .NET Compact Framework (I first heard about it here). What this could mean to device developers is that the next version of the NETCF has even more performance improvements (wouldn’t you back port any perf changes you made ;-)).

Existing NETCF application developers are prime candidates for becoming good XNA game developers (assuming you are not graphically challenged like me!). For those of you that haven’t dabbled with the NETCF before, learn how to write XNA code that performs well and read these 2 fresh posts by Chris To of the NETCF team: Part 1, Part 2.

the required ActiveSync proxy ports are not registered

Tue, November 28, 2006, 09:42 AM under MobileAndEmbedded
In the presentation to students that I mentioned here, I thought it was essential to show the smart device project deploy to the actual device (rather than the emulator that I use almost exclusively nowadays) since for newbies to the dev experience, I think it adds a lot of value to see that "this stuff is real".

When prepping for the event I realised that deploying to the device (and not the emulator) was broken on Vista! The error shown in the Error List was:
the required ActiveSync proxy ports are not registered
...this came from the Device Connectivity Component

I had heard the rumour that there are issues with VS2005 development on Vista but other than the one I talked about here, I had never faced *any* issues so this was a first for me! Luckily someone from the VSD team was able to give me a virtual slap and remind me that I should dogfood the workarounds we give to the public: Run VS2005 elevated – doh! I have never had to do that to date... Luckily I received this advice before my presentation earlier today :-)

Blogging this in case anyone else faces this issue (surprisingly no search results for the error above). If you are running WMDC on Vista RTM with VS2005 (without SP1) and you get the error above, run VS elevated (right click and select “Run as administrator”) and the issue goes away... phew!

For other device development issues on Vista see the relevant VSD blog entry.

.NET Micro Framework Product Sheet

Wed, November 15, 2006, 01:21 PM under MobileAndEmbedded
Ignore if you are not into embedded stuff. If you are, you heard it here first :-).

In the past I've talked about NETMF, and now you can download the product sheet here.

WCF for devices

Tue, October 31, 2006, 06:06 AM under MobileAndEmbedded
When we talk about the NetFx3 technologies, there are always one or two attendees (not the same ones each time!) that ask if any of the technologies are applicable to mobile devices. There are no plans for WF and no immediate plans for WPF (often confused with WPF/e which is actually quite a different technology with an unfortunate name IMO).

However, the WCF story is good with Orcas and it is now public information! Read all about the WCF support on Roman's blog post. Below some choice quotes:
"... The WCF programming model support will be limited to channel layer messaging (no service model support on the device) [...]
[...] We'll expose all necessary extensibility points so people could plug in their own transport and layered channels, while maintaining a unified programming model. [...] The channels we plan to deliver out of the box are Http and... yes, e-mail (for WCF on desktop and device)."

Go read the full story!

Free MEDC DevCon material

Mon, October 9, 2006, 03:00 PM under MobileAndEmbedded
Remember that rss download feed I was telling you about? It just "dropped me a line" to say that all the MEDC content is available for anyone to download!

Go get the MEDC 2006 conference DVD!

My session was APP330...

WMDC for Windows Mobile 2003

Sat, October 7, 2006, 03:46 AM under MobileAndEmbedded
I promised I’d let you know when WMDC for RC1 was out. Also given that most people searching for an ActiveSync replacement or for Windows Mobile Device Centre land on my blog, it is only fair that I let you have some links!

WMDC Beta3 page here. (Notice how now there is also support for Windows Mobile 2003 :))

How did I know? I got notified via the download center RSS feed (don’t tell me you are not subscribed to that?!) about the download page.

Mobile cross-platform development

Tue, October 3, 2006, 03:00 AM under MobileAndEmbedded
A topic I've done a lot of work on in the past and just one of the areas covered in Nick Randolph's podcast so go listen here (funny American and Aussie accents aside :-p).

Inspired by the podcast, I gathered some of the relevant blog posts I've written on the subject in chronological order (click on the numbers): 1, 2, 3, 4, 5, 6, 7, 8, 9

Favourite quote by Nick near the end (47:51):
"...you need the equivalent of the vb6 to vb.net converter/wizard... you'd run it on a VB6 app and it would come back with 18 million lines of code that had to be changed and your application only had 500K lines of code! "
LOL... been there, done that, got the t-shirt :D

Microsoft Developer Show #8

P2PMessageQueue queries

Sat, September 30, 2006, 09:36 AM under MobileAndEmbedded
Over the last year I have had a few people contact me with questions relating to the Point to Point Message Queue class I wrote for MSDN. This blog entry will serve as a URL where I can point future questions regarding it.

1. It seems that under certain circumstances, on certain platforms, the queue does not close properly. A possible solution is to declare a dedicated named event that you create in the ctor of the queue. Set it in the Close method. In the Monitor method, change the WaitForSingleObject to WaitForMultipleObjects and include this new event.

2. It also seems that under certain other conditions (that amongst other things include multiple senders) the class spikes the cpu. This is due to the way the native API works and the solution is not to run the thread that is responsible for raising events. To do that, follow the advice of the article and create a new P2PMessageQueueSender class that inherits from the original one and simply overrides the StartEventThread with an empty method (Note that this solution should also work for the 1st issue described above)

3. If you are porting the code to NETCF v2.0 (when I wrote the article it wasn’t released yet), there are things you can do to the code other than simply recompiling it, such as making any worker threads to background (IsBackground=true) .

Of course, the easiest thing for you to do is none of the above. Simply get the SDF from OpenNETCF, which will include the above improvements (plus you can then get support from the team as opposed to the “as is” code of my old msdn article ;-)).

For other NETCF questions, please use the newsgroup and forum...

Windows Embedded CE 6.0

Fri, September 22, 2006, 01:12 PM under MobileAndEmbedded
I followed the launch link from Mike's blog and, unless I am reading too much into it, the official product name for the next version of Windows CE is... (drum roll)...
Windows Embedded CE 6.0

XPe SP2 FP07 CTP WTF

Thu, September 21, 2006, 01:56 PM under MobileAndEmbedded
At most of my sessions on Vista I make the assertion that everyone has switched to .NET 2.0 and usually I get everybody nodding, but last week someone said:
"No, because it is not supported on Windows XP embedded".

I didn't know that at the time, but looking at the fountain of all knowledge (aka MSDN) I found this download that contradicts that statement: .NET 2.0 for XPe

While following links from the XPe site I also found a chat from a month ago about the longest product name ever:
"Windows XP Embedded Service Pack 2 Feature Pack 2007 Community Technology Preview"

What makes it even funnier is that besides the "2007" in its title, it is actually scheduled for release this year :-))

Sharing assets between Windows Mobile and Windows Desktop

Thu, September 14, 2006, 11:10 AM under MobileAndEmbedded
If you missed my session at MEDC, I'll be doing a repeat online for the Windows Virtual Mobile Group next Wednesday 20th September (12:00AM Eastern Time, 17:00 GMT)

Register Now!

I’ll be assuming knowledge of device development of course so if you are a desktop developer, get started ;-)

WMDC for Vista RC1

Thu, September 7, 2006, 02:40 PM under MobileAndEmbedded
No, it is not out for public consumption yet (although it is running here on my laptop). I was going to write an explanation to address the WMDC confusion... but Mel beat me to it here.

Resources for Mobile CAB

Tue, August 8, 2006, 02:30 PM under MobileAndEmbedded
For all my mobility developer friends, just got word that there is a new resource where you can get and contribute information regarding the Mobile Client Software Factory.

I then looked at Eugenio's latest blog entry and found a sea of resources: bookmarked!

TextBox with cue banner support for Windows Mobile

Thu, July 13, 2006, 07:30 PM under MobileAndEmbedded
When talking about TextBox with cue banner I thought I had done a good job at the end of the post of hinting that someone should write a pure managed version; a version that is not restricted to Windows Vista, but rather would work on WindowsCE/WindowsMobile devices (via the .NET Compact Framework of course).

Since nobody stepped up, I thought I'd tackle it myself :-). I have to say that what I thought would be a 10 minute job ended up taking 6 times as long and right about now I give up as what I have is good enough and a nice starter for someone else to take and polish, iron out any issues etc.

So, with no pinvokes and explicitly tested on WM 5.0 and WinXP, here is the TextBoxWithPrompt code file. Simply save this file and add it to one of your projects and then build all. Now open a form and go to the toolbox where you can drag the TextBoxWithPrompt onto your form and change its TextPrompt property to e.g. “Enter your name”



As always feel free to contact me via the link on the left about my blog entries.

Webcast follow up

Sun, July 9, 2006, 09:46 AM under MobileAndEmbedded
Thank you all that attended my webcast.

For those that missed it, you can replay it here: .NET Compact Framework for Desktop developers. You get the same experience except slide animations seem to have been taken out and of course you can't interact and ask questions.

Speaking of questions, looks like my content was so clear that I didn’t have to clarify anything :-p. Instead, here are some of the questions that I received.

Q1) I see from one of the last slides that you won't be covering SQL CE/SQL Mobile/SQL Everywhere. Please consider doing so in a future webcast.
A1) Thank you for the suggestion. In the mean time you can find info on SQL Everywhere here and here. Ask questions on this topic here.

Q2) Does Groove offer support for mobile devices yet?
A2) I have absolutely no idea. I would think not and indeed searching seems to bring back no relevant results so I'll stick with "no it is not supported at the moment" guess. If anyone has info to the contrary please enlighten me and I'll update this. Groove home page.

Q3) Are there any particularly cool open source projects for Windows Mobile?
A3) Yes, SDF from OpenNETCF. Source for v1.x is free and for v2.x available at a small fee. Binaries are free regardless of version.

Q4) What's your initial opinion of the new Mobile Client Software Factory? Is it useful for beginners or should novices focus on more meat and potatoes issues?
A4) I think it is a great effort. As everything else, only you know if it is of value for your particular scenario but definitely do check it out.

Q5) Windows Mobile or Tablet PCs?
A5) Mobility development is a wide field from laptops to tabletpcs to UMPCs to PocketPCs to Smartphones to watches! Depending on the job requirements one or more of the previous platforms can be chosen for any particular project. There is no universal answer.
Expect to read more on this blog soon regarding the Vista mobility story

Q6) Mapping for devices?
A6) See this and this. I would expect this to fully support mobile browsers or someone will be missing a trick.

Q7) In some Windows Mobile devices the .Net Compact Framework is in the system ROM in others it has to be downloaded and installed, what is the performance and other impacts of the built in framework vs a downloaded version?
A7) If you are building against a NETCF version that you expect to be in ROM on all your target devices, then there is no issue. If you don't, then you need to deploy the NETCF runtime with your app. In that case, NETCF is installed in RAM and hence using some of it (much like installing any application on your device). The other difference between the NETCF being in RAM or ROM is a tiny perf advantage in the ROM case. This is not something you should be worried about as it will definitely not be your perf bottleneck if you have one.

WM 5.0 projects on Vista

Fri, June 30, 2006, 04:27 PM under MobileAndEmbedded
It seems many NETCF developers are being bitten on Windows Vista after installing the WM 5.0 SDK for Visual Studio. The symptom is that although the SDK installation appears to go fine, the WM 5.0 project templates do not appear in VS2005.

The problem has to do with User Account Control (btw, I'll have a lot more to say about UAC in a future blog post). The way to work around it (on Vista Beta 2 at least) is to disable UAC and then install the WM 5.0 SDK thus getting the project templates to appear.

Specifically:
1. Launch "Control Panel"
2. Navigate to "User Accounts and Family Safety -> User Accounts"
3. Click on "Change Security Settings"
4. On the window that appears, uncheck the "Use User Account Control (UAC) to help protect your computer" checkbox (requires restart)
5. Now install the WM 5.0 SDK (or do a repair if you already had)
6. Launch VS2005 to verify you have the templates
7. Enable UAC again

The above combined with the WMDC update should answer most relevant queries...

.NET Compact Framework on Symbian

Tue, June 27, 2006, 03:18 PM under MobileAndEmbedded
Some people are asking about NETCF on Symbian. This makes me smile.

You see, every now and then, someone will bring out a Nokia phone and show me some end user feature and ask me how to achieve the same on a Windows Mobile device following it with a rant about how Symbian devices are dominant in the market compared to WM devices. My response is always the same. Yes, at the moment, Symbian is the dominant mobile OS when it comes to number of end user devices out there (not so sure in the enterprise/corporate world). However, from a developer perspective, that is completely irrelevant! Ask not how many devices are out there, ask how many of them are running an app that did not ship with the device. In other words, ask what percentage of Symbian devices compared to WM devices are running a 3rd party application that the user installed themselves. Windows Mobile *is* the dominant OS when you ask the right question and it is kind of expectant really: Every windows developer is a potential WM developer. The platform itself is built with running 3rd party apps in mind.

So going back to the original question, it shouldn't surprise us that it is being posed. An unfortunate developer has been asked by a decision maker to target a Symbian device and naturally the developer wants to use a modern, RAD and powerful platform.

The best development tool for all your needs is of course Visual Studio. To that end, there is an add-in for Visual Studio that allows targeting non-WM devices BUT note that this does not use the NETCF on the target - it is just a tool thing.

The best development runtime/framework of course is the .NET Compact Framework (ok, so I may be slightly biased :-)). When I was at MEDC a South African guy (Dusan Babich) approached me with some brochures and interesting ideas about porting the NETCF to a subset of Symbian devices. He didn't have a demo to show at the time but he said they were very close to releasing. I am not sure how far it got but this is their website should you wish to follow up.

I also found this excellent paper on porting the NETCF to Symbian phones. Just to keep the balance, here is an article on porting Symbian apps to Windows Mobile SmartPhones.

So there you have it. A slightly lengthier reply than what I had in mind originally but it is good to have context, right? To wrap it up, my advice is to target the Windows Mobile platform that gives you a versatile range of devices with a common API (and the story will get even better with future versions of SmartPhone and PPC form factors converging, I would imagine). If I am perfectly honest, I am not sure WM will win the consumer market tomorrow, but it is definitely slashing into the enterprise space right now and once it is done there, more of an end user focus should follow, in my opinion.

Vista: ActiveSync replacement

Fri, June 16, 2006, 08:57 AM under MobileAndEmbedded
There was a pleasant surprise on Windows Update this morning, a Beta update of the Windows Mobile Device Center that I talked about last month. After downloading it I captured some screenshots below (some are behind the hyperlinks and others inline with the body).

First connect a WM device or you'll get different screenshots since the UI options are visible only when applicable.

First screen offers us two options. The first one sets up the partnership and the second looks like this:


Hovering over any of the 4 areas, exposes further options: Programs and Services, Pictures Music and Video, File Management and Mobile Device Settings.

The Programs and Services option has two sub-options: One takes you to the windowsmobile home page on microsoft.com; the other option allows you to add/remove programs via this dialog:


The Pictures Music and Video option has 3 sub-options: one shows you how many "new pictures/video clips are available for import"; the last one launches a wizard from Media Player so you can "add media to your device from windows media player"; the middle option offers the following dialog "picture video import settings":


The File Management option doesn't seem to have changed from the one I captured last time.

The Mobile Device Settings option shows connection settings and of course the one we've all been waiting for: Setting up partnership (which I'll have more on later :-)

Vista: Windows Mobile Device Center

Wed, May 24, 2006, 05:12 PM under MobileAndEmbedded
Click on the links in this post to unveil the screenshots

Plug your Windows Mobile device to your Vista machine, and you get greeted by Windows Mobile Device Center.

If you click on "Pictures, Music and Video" then you'll get Media Player with the option to sync media.

Clicking on "File Management" brings up Portable Devices in explorer, allowing you to transfer files between the device and computer. On my device I have a 2GB SD card, so explorer shows that too. Another way of arriving to a similar display is simply by browsing Computer (no longer called My Computer).

The 3rd and final option of Mobile Device Center is "Change PC and connection settings".

By the way, if you don't plug a device and you want to view the Mobile Device Center window (or if you close the window and want to get it back), finding it is not easy. First I opened the "Control Panel" and naively thought it would be under "Mobile PC". I tried the "Mobility Center" but no luck there either. Finally, I found it under "Additional Options".

So, to sum up, the great news is that Vista has the *base* functionality of ActiveSync built in. The bad news is that (in build 5384 at least) not all the features of ActiveSync are available (plus AS isn't supported on Vista).

To finish on a positive note, by Vista RTM the Windows Mobile Device Center base application (probably complemented by a supplement) *will* completely replace ActiveSync. At that point we'll be able to target a real device from VS2005 for NETCF development!

UPDATE WMDC is here!

Standalone Device Emulator with WM 5.0 images

Thu, May 18, 2006, 06:20 PM under MobileAndEmbedded
I hope those of you at MEDC caught Barry Bond's session on the emulator. Well, it is now RTM :-)

The Microsoft Device Emulator 1.0 is a standalone version of the same ARM based Device Emulator that ships as part of Visual Studio 2005. The standalone emulator is intended for situations when you want to demonstrate or test your application on a computer that does not have Visual Studio 2005 installed. In addition, we are offering the Windows Mobile 5.0 and Windows Mobile 2003 SE operating system images that you can use with the Device Emulator.

Device Emulator 1.0 has a number of features that make it significantly better than its predecessor (the x86 emulator). You will find that it:

* Runs code compiled for ARM processors rather than for x86 processors. In most cases, you can run the same binaries on the emulator as you do on the device.

* Supports synchronizing with ActiveSync. You can use the Device Emulator with a full ActiveSync partnership. This feature allows you to debug applications that are syncing, or be able to use real synchronized data from within the Device Emulator.

* Provides support for more development environments. The emulator has been tested for developing and debugging applications with Visual Studio 2005, Visual Studio .NET 2003, and with eMbedded Visual C++ 4.0 (eVC4) SP4, all using ActiveSync. No crossover serial cable is required.

* The Device Emulator supports GAPI. You can write and debug GAPI games on the Device Emulator and expect them to work.

Download it now

List of AKU build numbers

Wed, May 17, 2006, 05:10 PM under MobileAndEmbedded
FYI, John Kennedy (whom I had the chance to meet at MEDC and he is a fine example of a British character :-) updated the mobile wiki with a list of Windows Mobile 5.0 AKUs

...and for my non-mobility readers who are wondering what it is: AKU

.NET Micro Framework

Sat, May 13, 2006, 02:52 PM under MobileAndEmbedded
I hinted before that this would be one of the big announcements at MEDC 2006, and I wasn't far off.

At the high level, here is what I recall about it:

1. Evolution of the SPOT. Has tiny footprint (200-400 KB), about ~1MB of flash required and very low power consumption.

2. Ships with Watches, Microsoft TV, Vista SideShow and plans for many more internally and many partners already on board.

3. Targets platforms smaller than WinCE (and thus smaller than WinPX embedded, of course) such as Sensors, actuators, remote controls, wearable devices etc.

4. Bootable .NET runtime (i.e. this is not an application layer on top of the core platform... it *is* the platform) including managed drivers!

5. C# only, interpreted. Program via Visual Studio 2005, naturally :-)

6. ARM 7, ARM 9 only (no MMU).

7. 100-150 APIs is all an OEM/ODM needs to implement for supporting /porting/integrating the platform.

8. No Windows Forms, but if you include the UI/Shell, it is based on WPF - hope the NETCF team can take a leaf out of the NETMF book cause Avalon and XAML rock (I suspect I’ll be blogging about that more in the future)!

9. SumoBot competition at MEDC was based on this. I wrote some of our NETMF code for our bot (we lost in the first round... hmm...).

MEDC 2006 registration

Mon, May 8, 2006, 02:51 PM under MobileAndEmbedded
Today (Monday) I registered for the MEDC at the Venetian (remember to come to my session if you are here tomorrow Tuesday at 16:45) where I received my bag and badge.

Looking at the contents of the bag, gives away some of the themes of this year's conference (if they weren't obvious already).

* Windows CE 6 Beta DVDs
On the inside cover it reads: "Windows CE 6 features a redesigned kernel architecture that supports up to 32767 simultaneous processes and 2 GB virtual address space per process"

...then under Disc 2 it reads: "...with Platform Builder Plug-in for Visual Studio 2005" :-)

* The t-shirt
It is about the .NET Micro Framework pointing to aboutnetmf.com

* Two pairs of Windows Mobile 5.0 DVDs
The "Windows Mobile 5.0 Developer Resource Kit" and the cool new "Windows Mobile Enterprise Resource Kit"

Also in the bag:
- 8 marketing brochures including one from OpenNETCF

- A notepad, conference guide and hard copy of "Smartphone and Pocket PC" mag

- A jelly cell mate

I don't like this year's bag so I will be going round with last year's bag, since my laptop fits in it this time!

Device platform not found

Sun, April 30, 2006, 09:35 AM under MobileAndEmbedded
Recently I opened a VS2005 Smart Device project that I was assured worked for others, only to face an error message box:
---------------------------
Microsoft Visual Studio
---------------------------
Error retrieving information from user datastore. Platform not found.
---------------------------
OK
---------------------------

When I hit my only choice, which was the OK button, a warning message box appeared:
---------------------------
Microsoft Visual Studio
---------------------------
The project could not be opened because it refers to a device platform that does not exist in your datastore.
---------------------------
OK Cancel
---------------------------

Clicking OK or Cancel had the same effect: the project does not load (i.e. it is "unavailable" in solution explorer).

However, in the top right corner of the warning message box there was the question mark icon. At first I didn't think of clicking on it, since it traditionally is used to get help on UI widgets on the dialog box it appears on. Instead, this one acted as a Help button (why not offer that next to the Cancel button is beyond me) and pointed to this msdn page:

The project you are trying to load targets a device platform that your Visual Studio installation is not configured to support.

To correct this error
Install the platform that supports the project you want to load.

For example if you are trying to load a Windows Mobile 5.0 project and do not have the Windows Mobile 5.0 SDK installed, install the Windows Mobile 5.0 SDK.

So clearly whoever saved that project had saved it while the "Target Device" was set to "Windows Mobile 5.0" (and probably created the project in the first place by choosing the WM 5.0 template). Since the WM 5.0 SDK doesn't ship with VS2005, any machine (like my tablet) that hasn't had the WM 5.0 SDK installed fails to open the project.

As I didn't have time at this instance to download the SDK (or switch to my main machine that has the SDK installed), I opened the csproj file in notepad, located the following line:
<PlatformID>4118C335-430C-497f-BE48-11C3316B135E</PlatformID>
... and changed it to this one:
<PlatformID>3C41C503-53EF-4c2a-8DD4-A8217CAD115E</PlatformID>

Save and close, now reopen in Visual Studio and all is fine (with Target Device set to "Pocket PC 2003").

While it makes no difference, I also changed the OSVersion tag, since it points to 5.01, which is not the WinCE version that PPC2003 is based on: 4.20

Finally note that if you *can* open your project and *then* need to change the platform, you don't have to mess with the text files, simply choose Project->Change Target Platform.

NETCF v2.0 SP1

Fri, April 21, 2006, 01:04 PM under MobileAndEmbedded
Get the SP1 Beta for the .NET Compact Framework v2.0

Those that have been waiting for WinCE 4.2 or for headless support need not wait any longer.

However, neither that nor the bug fixes nor the other *new* features excite me more than the TuneIn Remote Performance Monitor. Finally, when people ask me about .NET Compact Framework performance tools I won't have to apologise on behalf of the NETCF team :-D

1.0.4292.2

Sun, January 15, 2006, 01:56 PM under MobileAndEmbedded
While today we are on v2 of the .NET Compact Framework (2.0.5238.0), you can of course have v1.0 (there never was a v1.1) side by side on the target.

NETCF v1 had three service packs and the SP3 version number is 1.0.4292.0 (for the full list of version numbers and how to determine what is on your target see this).

So it was a surprise to me when I run cgacutil.exe (in the Windows directory) on my jasjar and it reported the correct v2 version but a new (to me) v1 version: 1.0.4292.2

It turns out (thanks Nazim Lala) that revision 2 is specific to Windows Mobile 5.0 (a loader security fix).

When I created a v1 app and run it on the device the plot thickened: my call to System.Environment.Version.ToString() returned 1.0.4292.0 – so which is correct, the API or cgacutil?

The answer is both. From an end user/developer point of view, nothing has changed so the hard-coded version returned by the API remains (by design) the same (thanks Jeremy Hance).

(so now you know :-)

#NETCF_AGL_

Sat, December 10, 2005, 03:41 PM under MobileAndEmbedded
Visual Studio 2005 includes some of the remote tools that previously we had to install eVC to get. They are still not integrated in the IDE but you can find them from the Windows Start menu same place where the VS2005 item is. The Windows CE Remote Spy didn't work in pre-release versions but obviously with RTM it does so take it for a spin. One of its features is listing all windows on the target including the handle, caption and class. The typical way you use this info is with FindWindow e.g. as shown here for programmatically closing any open msgbox on your device.

Anyway... If you use Remote Spy with Compact Framework v1 SP3 applications, you'll find that the class name of the CF forms show up as #NETCF_AGL_BASE_. If you go a step further, reference the Microsoft.WindowsCE.Forms assembly and then simply create an instance of the MessageWindow, you will observe how its class is #NETCF_AGL_MSG_. I was told a long time ago not to rely on these facts as they are internal implementation details of the NETCF windowing system. Well, I checked for v2 apps and nothing has changed with those two.

However, there is another special window that every CF v1 application has (one per app instance) and that has a class of #NETCF_AGL_PARK_. Furthermore, its caption is the file system path to your application. This *has changed* with CF v2: now its caption is empty, and the class is #NETCF_AGL_PARK_ appended with the application's file system path.

The moral of the story is, if you do take advantage of undocumented features, your application may break when you move it to the next version regardless of the compatibility efforts of the product teams at MSFT.

FileAs

Thu, December 8, 2005, 03:03 PM under MobileAndEmbedded
About 3 months ago I switched to a PocketPC Phone Edition 2003 SE device as my main phone (shocking that it took me so long, but it did). One of the things that really pisses me off is adding new contacts on the device:
1. Create a new contact
2. Populate the contact including entering the Name field: "Name Surname"
3. OK it and go back to the Contacts list
ACTUAL RESULT:
4. You get a an item in the list that reads "Surname, Name"
$%^&££$&*ing thing!

DESIRED RESULT:
4. Get an item that displays as "Name Surname".

I thought Windows Mobile 5.0 would have fixed this (e.g. by offering the FileAs option available on Outlook on the desktop), but when I received my JasJar (thanks Mike!), I found the same pain is there. So I am trying to find how I can change this on the device (forget synching with Outlook). Someone please tell me how and put me out of my misery.

Anyway, if you can't find how to do it on the UI, next step is to do it programmatically I guess, so that is what I did (it is so easy):

1. Create a new Windows Mobile 5.0 project in VS2005. Choose the Smart Device Project/Console project type.
2. Add a project reference to Microsoft.WindowsMobile.PocketOutlook
3. Replace Main with your own:
static void Main(string[] args){
OutlookSession os = new OutlookSession();
ContactCollection cc = os.Contacts.Items;

for (int j = 0; j < cc.Count; j++){
Contact c = cc[j];

string s = c.FileAs;
int i = s.IndexOf(',');
if (i > 0){
string s1 = s.Substring(0, i);
string s2 = s.Substring(i + 2, s.Length - i - 2);
c.FileAs = s2 + " " + s1;
c.Update();
}
}

cc.Dispose();
os.Dispose();
}

If you are targeting a WM2003 device, create the appropriate project for that and instead of adding a reference to the Microsoft assembly, add a reference to InTheHand equivalents.

Naturally, you can create a fancy UI to select which ones to change etc but the above is all I wanted. I run it every time I add new contacts.

PnP on PPC2003

Sun, November 20, 2005, 03:55 AM under MobileAndEmbedded
It is always nice to see something you created being used by others. In this case I am referring to my MSDN article.

Udo Killermann sent me a project he wrote that use the P2PMessageQueue component to monitor device plug-n-play events.

You can also use the DeviceStatusMonitor in the SDF from OpenNETCF (guest,guest), which in v2 also uses the P2PMessageQueue, but Udo wanted a stand-alone example.

Download his project here, and any questions regarding the PnP project must be sent to 'udo dot killermann at web dot de' and not me!

Getting started with .NET Compact Framework development

Wed, November 16, 2005, 01:40 PM under MobileAndEmbedded
I meet a lot of experienced .NET developers lately (including colleagues) that have focused on WinForms or ASP.NET or other .NET areas, but have never dabbled with the .NET Compact Framework. It doesn't take long before out conversation ends up in me providing information on how to get started with NETCF development. Here goes for future reference

1. The very first thing to do is to install Visual Studio 2005 (it side by sides with earlier VS versions).
[ The Express editions are no good to you but Standard and above will do perfectly. There is also a stand alone SDK and you could even try Visual Studio.NET 2003 Professional or higher, but my advice is to get Visual Studio 2005. ]

2. (optional) If you are planning on targeting Windows Mobile 5.0 devices, then you also need to download the Windows Mobile 5.0 SDK (i.e. for SmartPhone and PocketPC). In this case, you also need to get ActiveSync v4 (install this *over* your existing ActiveSync v3).

3. Create a new project via the normal route, but choose the “Smart Device” node and then the appropriate self-explanatory project type (e.g. “Device Application”). Note that VS2005 also supports creating apps that target Compact Framework v1.0 (there never was a NETCF v1.1). I recommend you stick with the v2.0 projects.

4. Drag a button on the form and add an event handler to it as you normally would, and type: MessageBox.Show("It isn't that different, is it?").

5. Start debugging the application: note how you have to choose where to deploy your application (i.e. an emulator type), choose whatever you want (e.g. “Pocket PC 2003 SE Emulator” and then “Deploy”) and notice how your application runs and you can click the button to get your msgbox (this may take a few minutes if this is the first time you are deploying).

6. From the IDE, click the "Stop" to stop debugging your application (emulator remains running, but your application has exited).

7. (optional) There are also some platform considerations, read these

8. (optional) If you need to share/execute your CF code on the desktop, see this.

9. (optional) For some links on how the NETCF differs from the full framework, see here

10. (optional) Remember the netcf is not a strict subset

From here on, you can start developing that NETCF app you’ve always dreamed of :-)

You will run into issues and you will have questions. You are a smart guy/girl so, before you ask me for help, check that your question isn't already answered in the FAQ (old and new), search the netcf newsgroup via google and check that OpenNETCF hasn't addressed the limitation you face. If you still haven't got a resolution, now you can seek support. Luckily there is a vibrant netcf community and for NETCF v2 the MSDN forums rock.

Welcome to the world of mobile development. Isn’t it much more satisfying running your own creation on your pda/phone than on the desktop? The mobility space *will* take off big time in 2006. Good luck!

CF v2.0 on WinCE 4.2

Mon, November 14, 2005, 04:48 PM under MobileAndEmbedded
As you know, NETCF 2.0 supports WinCE 5.0, PocketPC 2003 and Windows Mobile 5.0 devices.

After much pressure on the fantastic netcf team, they have allowed a few of us to blog this exciting news:

Service Pack 1 of .NET Compact Framework v2.0 will offer support for custom Windows CE 4.2 devices:
• Runtime support only
• Support on all WinCE processor types

I can’t tell you anything else but if you have feedback/requests on this particular topic, log them at the product feedback center (ladybug). The NETCF team is listening!

Dotnet changes

Tue, September 20, 2005, 01:37 PM under MobileAndEmbedded
.NET Full Framework changes between versions

.NET Compact Framework v1.0 service pack changes/fixes

.NET v1.1 differences with .NETCF v1.0 (also download the class comparison chm)

For netcf 2.0, the document above still mostly applies but keep in mind that CF 2.0 has even more exclusive classes and it now supports COM Interop and multimodule assemblies. See the msdn2 page for an overview of what is new in CF 2.0 and this one for differences with full fx.

Finally, here is what you've all been waiting for: CF 1.0 versus CF 2.0 at an API level.

B2 -> RC

Mon, September 19, 2005, 12:57 PM under MobileAndEmbedded
This blog entry is for you if:
You have been using Visual Studio 2005 Beta 2 (and all the previous CTPs) but have "ignored" all releases in the last 5 months. Now you download VS2005 Release Candidate and want to know what is new in NETCF 2.0

+ New classes:
SuppressMessageAttribute (as requested)
GeneratedCodeAttribute
SelectionRange

- Removed Classes:
ThreadTerminateException

+ New members:
HardwareKeys.None
Control.InvokeRequired (and for all other Controls)
DataGrid.BackColor
TreeNode.Handle
MonthCalendar.GetDisplayRange
Dns.GetHostEntry (as requested)
ThreadPool.GetMaxThreads & .SetMaxThreads (as requested)
MessageWindow.Text (as requested)
Marshal.AllocHGlobal & .FreeHGlobal & .ReAllocHGlobal

+ New Overloads with timeouts:
AutoResetEvent/ManualResetEvent/Mutex/WaitHandle .WaitOne(int millisecondsTimeout, bool exitContext)
Thread.Join(int millisecondsTimeout)

- Removed the setter from the following properties (so now they are read only):
BalloonChangedEventArgs.Visible
DocumentListEventArgs.Path
ResponseSubmittedEventArgs.Response
HelpEventArgs.MousePos

* You may also notice harmless renamings (e.g. MsgBoxResult.OK rather than Ok), massaging of the Generics stuff, changes in the BindingList/BuidingSource area and some System.XML alterations.

On the VSD side, we find full support for Visual Form Inheritance.

My MSDN article

Sat, August 13, 2005, 02:55 PM under MobileAndEmbedded
My MSDN article is now online. Check it out and, as always, let me have your comments.
(Had it been published in exactly 3 weeks time, the employer name under the author name would have been "Avanade", of course...)

Point-to-Point Message Queues with the .NET Compact Framework


Bug in Substring under netcf

Sat, August 13, 2005, 08:10 AM under MobileAndEmbedded

String s1 = "Some string";
this.Text = s1.Substring(1, s1.Length)
When you run the code under the full framework, you can see the ArgumentOutOfRangeException: "Index and length must refer to a location within the string. Parameter name: length".

When you run it under the .net compact framework v1.0 you see nothing. It is too tolerant (bug).

This is now fixed in netcf v2.0 so if you try the same code you'll get a ArgumentOutOfRangeException: "Specified argument was out of the range of valid values."

If your app took advantage of the bug it will now crash. It is for reasons like this you'd want to run your app in compatibility mode under netcf 2.0 (unless you can recompile your code under CF v2.0, of course).

However, in this case, that won't help you... until we get some msft comments, I guess it is probably a bug in the compatibility mode or maybe compatibility is only there for by-design changes and does not extend to bug fixes...

Sharing Cursor.WaitCursor and InputPanel in VS2005

Thu, August 11, 2005, 04:33 PM under MobileAndEmbedded
Most PPC apps use the SIP (see point 1 here). Now that resx files are compatible, many developers will try to share code at the windows forms level.

So rather than try to conditionally compile in or out the InputPanel do the following: in your desktop project only, simply add a file that provides stubs for the InputPanel class:
namespace Microsoft.WindowsCE.Forms {
public class InputPanel {
public event EventHandler EnabledChanged;
private bool mDummy;
public bool Enabled {
get { return mDummy; }
set { mDummy = value;}
}
}
}
Next hurdle will be changing the cursor. On the full framework, every control has a Cursor property and that is what you assign; on the compact framework, there is a single cursor which you access globally through Cursor.Current

So, add a new code file to your project (and share it in both projects) that has the following:
namespace YourNamespace {
public static class TheCursor {
public static void CursorCurrent(Control c, Cursor defaultOrWait) {
#if FULL_FRAME
if (c != null) {
c.Cursor = defaultOrWait;
}
#else
Cursor.Current = defaultOrWait;
#endif
}
}
}
Now, through a global find and replace (which I usually advocate against), replace all occurrences of:
Cursor.Current = Cursors.Default and
Cursor.Current = Cursors.WaitCursor
to
TheCursor.CursorCurrent(this, Cursors.Default) and
TheCursor.CursorCurrent(this, Cursors.WaitCursor) respectively.

If you get any compile errors it means you were assigning Cursor.Current from a method of a class that is not a control:
a) Review that design decision
b) If you stick with it, change the this to null

Now in your desktop project, wherever you were going to code the following:
someControlOrFormEtc.Current = Cursors.Default and
someControlOrFormEtc.Current = Cursors.WaitCursor
instead code:
TheCursor.CursorCurrent(someControlOrFormEtc, Cursors.Default) and
TheCursor.CursorCurrent(someControlOrFormEtc, Cursors.WaitCursor) respectively.

Not a strict subset

Thu, August 11, 2005, 10:20 AM under MobileAndEmbedded
We say that the .NET Compact Framework is a compatible subset of the full .NET Framework with few elements existing in the netcf and not the full fx.

For v1.0 I've mentioned previously and allow me to quote:
"[...] the CF is a subset of the full framework, but a closer look reveals functionality specific to the CF in the Microsoft.WindowsCE namespace (such as MessageWindow and InputPanel), the infrared classes and of course the SQL stuff is different."

MSDN has a couple more links for those compact framework unique areas here and here.

With v2.0, the CF-exclusive classes grow.

In particular, the Microsoft.WindowsCE.Forms namespace gains the following elements:
1. HardwareButton
2. MobileDevice.Hibernate
3. SystemSettings.ScreenOrientation
4. DocumentList
5. Notification
6. LogFont

NETCF 2.0 also adds the Microsoft.WindowsMobile.DirectX and .Direct3D namespace (as I mentioned here).

That's it... everything else in the compact framework is API compatible with the full framework. Happy reading :-)

Show numeric SIP for WinCE devices

Mon, August 8, 2005, 12:25 PM under MobileAndEmbedded
Everybody knows that to show the Soft Input Panel on a WindowsCE device you have to use the Microsoft.WindowsCE.InputPanel (set the Enabled property to true/false to show/hide).

A common request, to which there is no clean answer, is to show the SIP in numeric mode or not so the user doesn't have to do it.

However, Alex Feinman has a great hack that provides just that; it checks for the color of the "123" button and sends a windows message depending on if it is black or white (pressed or not). Go download it here.

If you are targeting PocketPCs then use it and that is the end of the story, see you next time.

If you are targeting custom Windows CE devices, you need to make a few small changes (on our platform we are using the small keyboard with the "Large Keys"):
1. The calls to GetPixel/SetPixel take the X,Y coordinates which are hard coded to 2,2. Change the Y to be 77.
2. Change the last parameter in the two calls to Message.Create to be: new IntPtr(0x00490009).
3. Change the condition so it caters for showing a numeric sip in non-numeric mode.

I've wrapped the changes in an InputPanelEx class:
a) In your projects replace all occurrences of InputPanel to InputPanelEx.
b) Wherever you have inputPanel1.Enabled = true, add another line inputPanel1.Show(true) [if you want to show numeric SIP].

Resx compatibility for Smart Device projects

Mon, August 1, 2005, 04:05 PM under MobileAndEmbedded
The punchline is that with VS2005 there is no more incompatibility for resource files (resx) between the compact and full frameworks!

To quote from my post on writing cross-platform code with VS.NET 2003:
"Trying to share the form code would effectively mean not using the designer at all."

This statement is no longer true with VS2005. You can follow the steps for sharing code files (as described in that blog entry) for forms as well. You may still prefer not to share forms between the two platforms but at least it will be technically possible now.

A side effect is that we no longer need cfresgen (as previously mentioned here) and instead we can use resgen (for both platforms).

Another side effect of this improvement is that existing resx files you have that work in your cf v1.0 projects, cannot be added to VS2005 projects. They have to go through the upgrade wizard. So although you have been told that the VS2005 upgrade wizard only affects solution and project files and nothing else, now you know that it also affects resx files; even though the (Beta 2) conversion report does not indicate that!

Overall, good stuff from the VSD team (and in this particular case, Xin Yan).

Visual Form Inheritance with netcf

Thu, July 28, 2005, 12:54 PM under MobileAndEmbedded
One of the features that devs got excited with when Visual Studio .NET 2002 launched, is Visual Form Inheritance. I have never used this feature in a commercial app but I guess I can see its appeal.

.NET Compact Framework v1.0 projects do not support Visual Form Inheritance in the designer (you cannot view the results of inheriting your form from another of your own forms). Specifically, if you attempt to directly inherit from anything other than System.Windows.Form, the winforms designer will not render your form's design surface. However, your application will still compile and execute with the visual inheritance correctly observed at run time.

With Visual Studio .NET 2003, you should do your design work before changing the parent of your form to be another form (i.e. do it while it still inherits from Form and the designer works). When you need the designer again, change your class to inherit from System.Windows.Forms.Form
public class Form4 
//: System.Windows.Forms.Form // Use this line for design time
: Form2 // Use this line for runtime

This has been discussed multiple time previously in the newsgroup archives e.g. here

So what is the story with v2.0 of the compact framework and Visual Studio 2005?

Start with a new Device Application with a single form and add some controls to it. If you navigate to "Project->Add New Item", the dialog does not include the "Inherited Form" template (in Beta 2). However, you can add a "Windows Form" and then change the code to achieve visual form inheritance. Here are the steps:

1. Create a new Smart Device Project
2. To the default Form1, add a button
3. Add a new form (Form2)
4. Delete the mainmenu from Form2
5. Go to the code and change it (Form2.cs) so it does not inherit from Form and instead inherits from Form1
6. Rebuild the solution
7. Open Form2 in the designer and observe how it shows button1

If you are using VB, make sure at step 5 you go to the Form2.Designer.vb (instead of the Form2.vb) - see my previous post on partial classes and how to get to the designer file.

Hopefully by RTM the VSD team will add the template so it will be even easier!

UPDATE: September 2005 - Visual Studio 2005 Release Candidate supports the "Inherited Form" template

WindowsMobile.Forms

Thu, July 21, 2005, 12:08 PM under MobileAndEmbedded
In my previous post I linked to a class diagram that shows all the WM 5.0 managed namespaces. It turns out that diagram doesn't show the WindowsMobile.Forms namespace so here it is for your enjoyment:


Had I drawn it in a C# project all those 'As' would be ':' conforming to UML style but I'll refrain from going on about that again.

Microsoft.Windows.Mobile

Wed, July 20, 2005, 03:20 PM under MobileAndEmbedded
All of you know that Windows Mobile 5.0 was released in May at MEDC (Bill Gates keynote). Devices are expected to ship in Q4 this year.

From a general dotnet perspective, the most exciting thing about this platform release is that it exposes managed APIs! This is a first in both the mobile/embedded and desktop/server world. Maybe Longhorn will be the next, but for now WM 5.0 is the first and only one to do that.

What prompted me to share this is that already there are articles etc that refer to these APIs as being part of .NET Compact Framework v2.0 - they are not, they are part of the platfrom (which also includes CF 1.0 SP3 by the way). If you use netcf 2.0 to target a WM2003 or a WinCE 5.0 device, the APIs are not available. In contrast, if you use netcf v1.0 to target a WM 5.0 device then the APIs are available.

There is a lot of redundancy in my statements above but hopefully it will clarify the state of play (my fear is that this will become another common misconception similar to people talking about v1.1 of compact framework - when there is only v1.0 and v2.0).

The APIs I refer to are classes in the following namespaces:
Microsoft.WindowsMobile.PocketOutlook
Microsoft.WindowsMobile.Configuration
Microsoft.WindowsMobile.Status
Microsoft.WindowsMobile.Telephony
Microsoft.WindowsMobile.Forms

You can access them from Visual Studio 2005 once you download the WM 5.0 SDK and after you add reference to the relevant assemblies (same as namespace names with "dll" suffix)

Just to confuse things, there is a netcf 2.0 namespace with similar name: Microsoft.WindowsMobile.DirectX. If you are into game programming, check it out and also the article here

So, before I let you go back to your work, here is a link if you wish to find out more: recorded webcast & class diagram (the one missing is the Forms namespace which you can see here)

Oh, I almost forgot, if you like the new classes and would like to see them on earlier PPC versions (e.g. PPC 2003), check this out :-)

Form.Owner in NETCF 2.0

Thu, June 2, 2005, 12:52 PM under MobileAndEmbedded
As a Pocket PC user and a NETCF 1.0 developer, you are familiar with the problem of showing different forms in the same application while preventing the user from navigating between forms from the "running list" (not to mention returning to the correct form after closing a sub-form). This was described previously here (look at the fourth entry: 4. Moving between applications)

So in NETCF 1.0, if you simply use ShowDialog to display another form:
a) The new form (specifically its caption/text) appears in the "running programs list"
b) The original form also appears in the list, which means you can navigate to it (although it appears disabled once activated)
c) There is potential for closing the second form and returning to another window on the PPC (the original form has moved back in the z-order)

With CF 2.0 you can use the new Owner property of the Form and hence get rid of every problem from the above list. Do not confuse the Owner property with the Parent property, which is inherited from Control and is not intended to be used with forms

Run the following snippet (assume it is in the button click event handler of Form1 in VS2005 NETCF 2.0 project):
Dim f As New Form2()
f.Owner = Me
f.ShowDialog()
...you'll notice that only one entry for your application exists in the running list. The only potentially strange thing is that it has the caption of the first form (while the body of the form is clearly that of Form2)! This is easily rectified with the following modification (this time in C#):
Form2 f = new Form2();
f.Owner = this;
string s = this.Text; //make a copy of the original caption
this.Text = f.Text; //set our caption to the form we are about to show
f.ShowDialog();
this.Text = s; //restore the original caption once the second form is closed
Although I would have preferred the original snippet to exhibit the behaviour of the second snippet, still we must agree that this is a step forward from NETCF 1.0!

CF COM Interop #1 FAQ

Fri, May 20, 2005, 02:15 PM under MobileAndEmbedded
Now that NETCF 2.0 supports COM Interop (for CF 1.0 your best bet is 3rd party support), there is a FAQ emerging.

Q: I have a native/C++ exe/process and cannot get it to talk to my managed/C#/VB dll/class library. What's wrong?
A: As indicated last year, this is not supported.

To help Google get you here, I will use various phraseologies that all indicate the same thing.

You can call native COM components from managed code, as long as it is from a managed exe - VS will generate the RCW (Remote Callable Wraper) for you. Once you have activated native COM objects from managed code, they can call you back; so in that sense - and that sense only - CCW (COM Callable Wrappers) are supported.

You cannot activate (or register) managed objects through COM. Regasm.exe that the full framework supports is not available. Forget doing a CoCreate on your managed objects.

If you think about the last statement it makes sense, since runtime hosting of the NETCF CLR is not supported; how could you start a native process that "talked" to a managed library (dll)?

Incidentally, if you must communicate from native code to managed code and since you cannot do that in the same process, consider one of the IPC mechanisms available on WinCE.

While we are on the subject of NETCF 2.0 COM Interop limitations, allow me to quote from one of Richard Greenberg's slides from MEDC:
"Only MTAs (multi-threaded apartments) are supported and there are no custom marshalers or auto-generated Class Interfaces."

Compact Framework Unit Testing

Mon, May 16, 2005, 12:49 PM under MobileAndEmbedded
Question:
Do Smart Device Projects (i.e. Compact Framework projects) support unit testing as offered by Visual Studio 2005?

Investigation:
1. In a CF project write the following method:
public Int32 GetBuildVersionPart(){
return System.Environment.Version.Build;
}
2. Right click on the method and choose "Create Tests...", choose C# and OK, choose default name and OK

3. Set the newly created project as startup project (via context menu)

4. Go to the test method and change the following line:
int expected = 0;
to
int expected = 50215;

5. Comment out the Assert.Inconclusive line

6. Run the project

7. Observe: The PPC emulator starts, which is promising, but unfortunately the unit test passes :-(
It would not pass if it was running against the CF, as the build number is 5056 (the full framework build number for Beta 2 is 50215).

Conclusion:
Unit testing is not supported by CF projects and instead the tests get retargeted to the full framework (much like Deploy to My Computer).

Link:
For an open source project that supports unit tests running on the device, see CFNUnitBridge from Trey

Marshal.PreLink

Fri, May 6, 2005, 12:19 AM under MobileAndEmbedded
All Compact Framework developers know that without pinvoking you cannot author any serious CF 1.0 application.

We've all been in the situation where we have declared a function from coredll.dll (or some other native dll) and when we called it we got the infamous MissingMethodException (meaning the DllImport declaration was wrong). That is the only way to find out, try it and see.

Well, CF 2.0 gets support for a method that is already in there in the full desktop .net framework version 1.1. The method in question is Marshal.PreLink/PreLinkAll. It basically verifies that your dllimports have been declared properly, e.g.
static void Main() {
// Assuming all your dllimports are in Form1
System.Runtime.InteropServices.Marshal.PrelinkAll(typeof(Form1));
Application.Run(new Form1());
}

My suggestion is to still test the methods explicitly from your code, but I will be using this shortcut when in debug mode; it's a sweet little time saver :-)

SuppressMessage not in CF

Thu, May 5, 2005, 01:52 PM under MobileAndEmbedded
As you may have noticed, in VS2005 you can turn static code analysis on via the project properties ("Enable Code Analysis"). Many of the rules are just guidelines and do not qualify as warnings. There should be a separate category, maybe called *recommendations*. However, that is not the point of this blog post.

Fortunately, you can suppress warnings simply by right clicking on them and choosing "Suppress". What that does is to add an attribute to the line of code that breaks the recommendation so next time you compile/build, the annoying warning will not appear in the error list. The attribute is the System.Diagnostics.CodeAnalysis.SuppressMessageAttribute (it applies only if the compilation constant CODE_ANALYSIS is defined)

Example:
// no comments on the content of the method please
public void SomeMethod(bool b, object o) {
if (b) {
((EventHandler)o).Invoke(null, EventArgs.Empty);
} else {
((EventHandler)o).BeginInvoke(null, EventArgs.Empty, null, null);
}
}
One of the 4 warnings you'll see for the method above is the following:
CA1800 : Microsoft.Performance : 'o', a parameter, is cast to type 'System.EventHandler' multiple times in method Class1.SomeMethod(Boolean, Object):Void. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction.

So, you bring up the contextmenu for the item in the "Error List", select "Suppress message" and life is good again.

So where is the problem? As the title of this entry suggests, the attribute is not supported by the Compact Framework (at least in Beta 2) and doesn't compile:
The type or namespace name 'CodeAnalysis' does not exist in the namespace 'System.Diagnostics' (are you missing an assembly reference?)

There are two issues with that:
1. You cannot suppress those annoying recommendations warnings that shouldn't be there in the first place.
2. If you are sharing code between the full and compact frameworks, you'll get compilation errors.

There is nothing you can do about the 1st one (apart from vote for it).
For the second, as you know, you can use conditional compilation. However, in this case I'd go ahead and define the attribute in code in your CF projects, so at least you get past the compilation problem. Define it like this:
namespace System.Diagnostics.CodeAnalysis {
public class SuppressMessageAttribute : Attribute {
public SuppressMessageAttribute(string category, string checkId) {}
}
}

Note, I tried implementing the attribute fully but the warnings were still not suppressed so the bare minimum skeleton as above is good enough to at least get us past the compilation errors

When the desktop and compact teams do not talk to each other

Wed, April 27, 2005, 02:59 PM under MobileAndEmbedded
While moving some of my cross-platform code from .NET 1.1/CF 1.0 (Visual Studio .NET 2003) over to .NET 2.0/CF 2.0 (Visual Studio 2005) Beta 2…

… the desktop compiler warned me that the following method was obsolete:
System.Net.Dns.Resolve(hostname)

No problem, as the helpful warning informed me of the replacement method, so I change my code and it compiled:
System.Net.Dns.GetHostEntry(hostname)

I then open my Smart Device project and I encounter an error that GetHostEntry is not recognised (the method is not supported by the CF version of Dns)! I look the class up and it supports Resolve without any obsoletion warning in sight!

The temporary solution is conditional compilation, but I am confident that by RTM the CF team will resolve (no pun intended) this :-)

Intellisense for CF v2.0

Tue, April 26, 2005, 12:52 PM under MobileAndEmbedded
We looked last time at the VS.NET 2003 support for Smart Device Projects from an intellisense perspective.

VS2005 seems to be miles ahead in that department (as well). In fact, I have yet to find a PME (property, method, event) that compiles while it is not supported _or_ a PME that is supported at runtime and not offered in the IDE :-)

The story is even more interesting. Let's take a control, e.g. TreeView. If you try to add an event handler in code, intellisense lists only the events that are applicable. Now, since TreeView inherits from Control, I know I should be able to add an event handler to an event that is exposed by Control such as DoubleClick or Paint. So, even though intellisense doesn't help me, I can type:
treeView1.DoubleClick += new EventHandler(treeView1_DoubleClick);

Here is the new feature. This does not result in a compilation error but rather a warning in the "error list" window:
"Members not supported by the Device platform should not be called: System.Windows.Forms.TreeView.add_DoubleClick is not a supported method in this platform".
I like this! If I have explicitly written code that intellisense doesn't recognise I must have my reasons, so don't error out on me - just warn me. E.g. if code is shared between desktop and CE devices, you may avoid the conditional compilation and just not offer the functionality on the CE device. (this does make me think of a feature request to turn every compilation error into a warning, but I'll resist going down that thinking path...)

Needless to say that if you try something like adding an event handler to TreeView.NodeMouseClick event, which is supported in .NET 2.0 but not NETCF 2.0, you do get a compilation error; the warning in the previous case is only because the event is inherited from Control.

Intellisense for Smart Device Project v1.0

Mon, April 25, 2005, 03:13 PM under MobileAndEmbedded
When writing Compact Framework code with VS.NET 2003, intellisense is smart enough to filter out the framework methods that do not apply to the CF. Truth be told it could be better. There are some properties shown that are not supported by the CF, yet they compile, and hence you only find out at runtime. Some of them will result in runtime exceptions (e.g. changing the Font of a UpDown control) and others will silently do nothing and have no effect (e.g. changing the Size of a StatusBar). I am not sure which outcome is worse, but I do know the methods should not have been available in the IDE in the first place, since a Smart Device Project was chosen! The help is pretty good (but certainly not perfect) at pointing out which class members are applicable to CF.

The area where the IDE is really bad is events. C# shows in the properties window the events that are applicable, but some events are shown even though they are not supported (e.g. PictureBox.Validating) and others are supported and not shown (e.g. PictureBox.Click). In the latter case the workaround is to manually add the events in code (in code there is no filtering so, whether applicable or not, the compiler lets you add event handlers). VB is much worse. As you know, the event handlers are generated by selecting the event names form the top right combobox in the code view; well that combo doesn't even make an attempt at filtering! In case you think the documentation will come to your rescue, think again: the documentation makes no statement about the applicability of events to the CF or not.

To complicate things further, there have been 3 service packs for CF 1.0 and all of them apply to the runtime *not* the VS IDE. Since the SPs, some properties (e.g. BackColor) are available. None of these are shown in the properties window but you have to manually use them through code.

At this point you might be expecting me to offer some solution. Sorry, but there is only one way to face this issue: try out your code before you make assumptions about what is supported or not.

VS2005 is a whole different (more pleasant) story and we'll look at that next time.

SystemColorsEx

Mon, April 11, 2005, 02:56 PM under MobileAndEmbedded
Recently I needed to change scrollbar colors, the disabled text color and other similar items. The target is a Windows CE device (not a PPC) and I quickly found (through the control panel) the Display Properties dialog and specifically the "Appearance" tab. If you don't have a WinCE device, launch the 4.1 emulator that ships with VS.NET 2003 to check it out.

So there was my goal: to find out what it does under the covers in order to offer us changing colors of individual items (e.g. Active Title Bar color) and also the overall scheme (e.g. Brick). We start at the obvious place: *everything* on this platform is stored in the registry. Using the Remote Registry editor (that comes with eVC) we take a snapshot before and after a scheme change and then use windiff (or similar) to spot the difference. Bingo; we find a string value "Current" under HKCU that stores the scheme name and, more importantly, we find a byte array value "SysColor" under HKLM that stores the color data. Searching on MSDN proves fruitful and informative, leading us to this and this. We test out our understanding by changing some of the RGB values in the registry, flush, reset the unit and the changes take effect. Nice!

Next step is to figure out how the control panel applet applies the change on the fly. We suspect some windows message and decide to investigate further with another eVC tool, remote spy++. Every time we apply a change a WM_SYSCOLORCHANGE message is broadcast. So we try with our own app to change the registry and then broadcast the same message but no effect takes place. Wouldn't it be great if we had the source code to the OS dialog so we could see exactly what it does? But wait, I have platform builder installed on this machine, so I could locate the code and check it out! After a few hit and miss searches, I nail it down. They call an API that does both the writing to the registry and the broadcast and the on-the-fly change: SetSysColors

Note that, if you don't care about changing colors and all you need is read-only access, then the existing System.Drawing.SystemColors class fits the bill.

This has been a not so short story, leading up to providing you with a managed class that wraps all of the above. Use it in your own WinCE (not-PPC) projects for changing color themes on the fly or single element color changes.

Download the VB class here.
Get the C# version as part of the SDF (guest, guest).

Thread.IsBackgroundOrIsIt()

Wed, March 30, 2005, 01:46 PM under MobileAndEmbedded
One of the missing methods from NETCF 1.0 today is Thread.IsBackground.

CF 2.0 will support this method with a few noteworthy caveats. Read carefully Brian Smith's contributions in this thread.

SmartPhone development quick start

Sat, March 26, 2005, 10:25 AM under MobileAndEmbedded
So you have experience developing .NET Compact Framework applications targeting your Pocket PC (2000/2002 or WM2003) or even custom Windows CE devices. Now you want to dabble with SmartPhone 2003 development, since CF supports that too (but not SP2002). Where do you start?

The first thing to do is install the SmartPhone SDK. This will give you a new Smart Device Project type and an emulator of course (you may also get the Second Edition Emulator. Usually you choose the Pocket PC platform, now you should choose Smartphone (the only omission from the "project type" list is the "Non-graphical Application", a.k.a. "Console Application" on the Windows CE platform).

So the new project is created. The first thing you note is that the form is small (182w x 239h). In reality, the area you can manipulate is 176x180 pixels since you'll have a border, title bar and menu area. The menu area is actually the space for two soft keys (more on those in a moment). The second limitation we observe is the toolbox; device controls are already much fewer than the desktop, but they are further halved in numbers for Smartphone projects [VS2003 toolbox][VS2005 toolbox]. Later, I'll say a couple of words for some of the 14 controls (datagrid doesn't work) we have at our disposal.

At this point, it is worth stating the obvious: the SP has no touch screen and all interaction is via hardware buttons. The emulator [vs2003][whidbey] gives us some clues. Let's have a closer look at the buttons moving from the top downwards:

There are 3 sections:
1. LCD area
-Two button directly below the screen (a.k.a. soft keys).

2. Middle/center of the phone
-Two phone keys. Green for call and red for hungup.
-Below the call button there is a "home" button.
-Below the hungup button is a "Back" button.
-Between the 4 buttons just described is the rocker [Left, Right, Top, Down and Enter/Action]

3. Lower end of the phone
-Typical 12-button keypad found on all phones

In theory you could hook into any of these buttons and do whatever you want, but it makes sense to remember that the device's primary use is as a phone and also that MSFT has some guidelines for SP applications (some of which are enforced by the CF at runtime). For example the 12-button keypad can be used only for data entry (e.g. on a textbox); the call/hungup buttons (with the green & red phone icons) should be left alone, as should the home button (house icon). The back button navigates to the previous form (or to the previous application, if you are on the main form).

So let's look at the remainder buttons in correlation to the CF controls.

+ The following controls have no user interaction (other than displaying info, of course):
Label, Panel, PictureBox, ProgressBar, Timer, ImageList, VScrollBar, HScrollBar

+ The following 3 controls should be the only control on a single line (other than non-interactive controls mentioned above, of course):

- CheckBox
Up/Down move to the previous/next control on the form. Left/Right/Enter toggle the state.

- ComboBox
Up/Down move to the previous/next control on the form. Left/Right navigate through items in the combobox list. Enter brings up a full screen list of the items for selecting by scrolling with Up/Down.

- TextBox
Up/Down move to the previous/next control on the form. Left/Right moves the caret in the textbox. The Back button erases a character. If the textbox is Multiline=true, Enter brings up a full screen textbox (with scrollbars, if needed):

+ The following two controls must be the only (interactive) control on the form (there is no automatic way for them to pass focus to another control):
- ListView
Up/Down moves through the listview items. Left/Right scrolls horizontally, if there is a scrollbar visible. Enter generates the ItemActivate event.

- TreeView (must be the *only* control on the form)
Up/Down moves through the visible treenode items. Left/Right scrolls horizontally, if there is a scrollbar visible. Enter expands/collapses a treenode.

+ Given the absence of buttons, the two soft keys are the main mechanism of performing actions. The following control is how we drive the two soft keys:
- MainMenu
When placed on a form, the two buttons directly under the screen become applicable. The mainmenu can only have two top-level menuitems, the Text of which is rendered on the screen buttons. The left root menuitem cannot have any child menuitems of its own and thus acts more like a button. The right root menu can have menuitems and hence may function as the normal menus we are accustomed to.

It is always good to cut code in order to understand a new platform, but I suggest you familiarise yourself with the platform philosophy before embarking on a project. Even if you are an experienced PPC developer, Smartphone is a new platform (in terms of UI - you can always use existing CF dlls without recompilation). I hope the above serves as a basis for understanding the philosophy and approach you should take for Smartphone development.

Other useful links for the newbie Smartphone developer:
Keys, menus, faq, msdn article, sp with cf primer, smartphone developer ng

Progress on RTL

Tue, March 22, 2005, 02:48 PM under MobileAndEmbedded
In the previous entry we identified how CF 2.0 does not support RTL on CE 5.0. We also defined what RTL support means.

Like with most features that CF does not support, we can work around this one with a bit of pinvoke. By reading this page on MSDN (thanks Chris Lorton) we see that, if we pinvoke SetWindowLong passing it the Control.Handle, we can change the RTL style.

In VS2005, to test if the above works, we populate a form with all the CF 2.0 controls and run the following method (e.g. call it from a button/menu click):
// Call this method with this.ChangeToRTL(this)
private void ChangeToRTL(Control c) {
this.ApplyStyle(c);
foreach (Control c2 in c.Controls) {
this.ChangeToRTL(c2);
}
}

private void ApplyStyle(Control c) {
Int32 lS = GetWindowLong(c.Handle, GWL_EXSTYLE);
lS |= WS_EX_LAYOUTRTL;
SetWindowLong(c.Handle, GWL_EXSTYLE, lS);

c.Invalidate();
}
To test the results you need a CE 5.0 device (or simply get the CE 5.0 emulator as described here).

I have given you enough to run the test and check the results for yourselves, but here is my summary (lookout for screenshots at the end):

1. The following controls pass the test and meet the criteria as defined previously:
button, label, textbox, checkbox, radiobutton, progress bar, v/h scrollbar, form, tabcontrol, datetimepicker, monthview, toolbar, statusbar, listbox

2. The following fail
domainupdown, numericupdown - text part right aligns but buttons remain on the right

trackbar - shade issue (need to change value for effect to take place; refresh is not good enough)

treeview - When ShowLines=true, the lines are portrayed the wrong way round

listview - columns do not right-align (they are not affected at all by the style-change)
listview - resizing a column looks funny. You drag to the right but the listviewitems below move to the left and vice-versa

MainMenu - The top mainmenu items do not change order, although they are aligned to the right (and correctly after the toolbar) menus - when clicking on toolbarbutton with a menu OR a mainmenu to bring down its menuitems, the menuitems appear to the left of the mainmenu/toolbarbutton.

combobox - It appears ok RTL *but* clicking on the dropdown button results in the list appearing but the main combo area disappearing. Clicking elsewhere to take away the focus results in the combobox being drawn to the left (it moves left exactly its width in pixels). Repeating the process eventually moves the combobox outside the form area on the left (kind of funny, really).

3. Vertical Scrollbar issue [treeview, listview, listbox, multiline textbox etc]
Regardless of what is described above, all controls that can have a vertical scrollbar work only if the style is applied *prior* to a vertical scrollbar being displayed. If the vscrollbar is visible and the RTL style is changed, then the vscrollbar stops responding (freezes) and remains on the right.

Screenshots:
Good RTL
Not so good RTL
Bad RTL
Menu RTL

If you have a CE 5.0 device with CF 2.0 on it, feel free to try the exe (in fact, if from IE on your CE 5.0 device you browse to this link, you can run it)

RTL problem

Thu, March 17, 2005, 11:38 AM under MobileAndEmbedded
In some places in the world they read and write from right to left (RTL). Prime examples of such languages are hebrew and arabic. As a software developer, if your market extends to such users, you should support RTL in your application. Unlike support for a LTR language, there are additional things your windows app must do. For .NET apps this includes using the Control.RightToLeft property.

For the Compact Framework the story is less straightforward. You see, the CF is a subset of the .NET Framework that runs on Windows CE based devices. Windows CE 4.x and previous versions do not support RTL (since all current Pocket PC devices are based on the CE 3.x/4.2 operating system, by definition they do not support RTL either). There may be 3rd party solutions available, but I am not aware of any. It would be a nice touch if the CF implemented RTL support without support from the OS (i.e. it could simulate it) however that would probably mean that the windows controls would not be just thin wrappers of the OS equivalent and hence performance would suffer - not to mention framework size.

The OS story becomes much better with the next version of Windows CE. In a sentence, CE 5.0 supports RTL :-)

For devs with their own platform this means migrating from 4.2 to 5.0. (for devs of PPCs [Windows Mobile for Pocket PC] or SPs [Windows Mobile for SmartPhone], my *guess* is you have to wait for a next version of Windows Mobile which if based on CE 5.0 could expose the underlying OS support).

Since CE 5.0 supports RTL and since Compact Framework 2.0 *only* runs on CE 5.0 (and WM2003 for PPC), I'd forgive you for making the logical jump that CF 2.0 exposes Control.RightToLeft - think again. That's right, the infamous "postponed"!

Before we go off in a sulk, it is worth capturing what we mean by RTL support:

1. CheckBoxes (the square bit) and RadioButtons (the circle bit) should appear on the left [there is no CheckAlign property on CF]
2. UpDown buttons (e.g. NumericUpDown and DomainUpDown) should appear on left
3. Controls with vertical scrollbar (e.g. TreeView, ListView, ListBox, multiline TextBox etc) should render the scrollbar on the left
4. Wherever there is text that is naturally left-aligned, it should be right-aligned (e.g. *any* control with .Text property such as Form or .Items such as ListView)
5. Menus, ToolBar buttons and form buttons (i.e. max/min/close buttons, control box) must be mirrored (right aligned)
6. ProgressBar, TrackBar and HScrollBar should start from right.
and a more subtle one
7. Shadows of controls should appear on the left. If you haven't noticed this before, have a closer look at button/scrollbar/trackbar etc: they have a white border top & left and dark border bottom & right. The left & right shades must be switched when RTL applies.

Next time we'll see what we can do with CF 2.0 to support RTL on CE 5.0. I'll include screenshots and details of which controls (based on the November CTP) pose insurmountable problems!

CF with Delphi

Sun, February 27, 2005, 07:41 AM under MobileAndEmbedded
I would like CF development to be accessible to *everyone*. No personal gain in that statement (I've always had an MSDN universal subscription and I don't plan, in the near future, to write in anything other than C# and VB), I just want the platform to gain more developers/users.

It is sad that there is no SDK for CF 1.0 and that VS.NET 2003 Professional and above is required. Even though CF 2.0 comes with an SDK and VS2005 Standard is adequate, I am still not happy that the Express editions will not support Smart Device projects.

On the programming language front, dotnet is about multiple languages being able to target the platform (20+ on the desktop). On the other hand, CF only allows C# and VB.NET! No J#, no managed C++ etc. If you are thinking "it all compiles down to IL at the end of the day", unfortunately that is not enough: some IL instructions such as localloc and calli are not supported and design time support is more complex.

So, in the context of the above, I was disappointed to read this post on the Delphi blog (via Tim Anderson).

Will an MSFT reply be forthcoming?

ThreadPool

Wed, February 23, 2005, 02:57 PM under MobileAndEmbedded
No doubt you are familiar with the System.Threading.ThreadPool (if not, go learn about it now!). The Compact Framework implementation only offers a single method: QueueUserWorkItem(WaitCallback, Object). Basically, every time you call this method it will call you back on a different thread, passing back to you the state object you gave it, so you can run your background work. Once the background work is finished (i.e. the method returns), the thread is then either reused in a future call or is removed from the pool (after a undefined interval). The advantage over explicitly creating threads is obvious in such a thread-reuse scenario (less context switching, no thread creation/destruction overhead each time, ease of use).

Internally, the NETCF ThreadPool is built on the System.Threading.Timer (whose core implementation is in native code). In other words starting a one shot timer with dueTime of 0 is the same as queuing a work item with the ThreadPool. Clearly using the ThreadPool is the preferred choice (in other words don't use the Threading.Timer just for going async, rather use it in scenarios where timing is truly required).

Apart from the different implementations, the desktop and CF ThreadPool have other differences.

1. The documentation states that explicitly using a thread is a better alternative to the ThreadPool for lengthy operations i.e. use the ThreadPool for short-lived tasks. One of the reasons it advises this is because the desktop implementation has a ThreadPool limit of 25 per process (so, for example, you can imagine deadlock situations if you starve the ThreadPool of its 25 threads and e.g. two of them are waiting to acquire the same resource). However, the NETCF 1.0 ThreadPool has a limit of 256 (treat that as if there was no limit; for a laugh, I tried testing the limit and my device stopped responding around ~150). Note that CF 2.0 rectifies this by setting the limit to 25, bringing parity with the desktop. On the desktop with .NET 1.1 you can change it if you really try hard and with .NET 2.0 there is even a method (SetMaxThreads). I am not sure if we will see this method in the CF 2.0 RTM, but for the November CTP you can control the number of threads via the registry: HKLM\Software\Microsoft\.NETCompactFramework\ThreadPool\MaxThreads

2. The desktop's ThreadPool threads are all background. Since the CF 1.0 does not support background threads, the difference is obvious. As a reminder, a non-background thread can keep your process up even if the main (UI) thread has exited. Since CF 2.0 supports Thread.IsBackground, the ThreadPool threads will return true for that property.

3. ThreadPool threads, like other managed threads, are created at the default priority of Normal (251 in WinCE terms). I have discussed previously about "Threads and ThreadPriority with the .NET Compact Framework". If (against my advice in that post) you change the priority of ThreadPool threads (which btw can only be done in the callback), you will find that the priority may not be reverted when the thread is returned to the ThreadPool (MSFT quote). In other words, future uses of the ThreadPool could run on that thread with whatever priority you gave it in a different context (dangerous!). This is not true for the Full Framework and, fortunately, CF 2.0 brings parity with the desktop.

So we can see all the differences between CF 1.0 and Full Fx 1.1, but we also see how CF 2.0 eliminates them.

Finally, CF 1.0 does not support Control.BeginInvoke but CF 2.0, like the desktop, does. BeginInvoke indeed uses threads from the ThreadPool on both platforms.

ListView with scroll events and TopItem

Tue, February 22, 2005, 02:09 PM under MobileAndEmbedded
Two years ago I asked the question:
"I cannot find an event to catch when the user scrolls the scrollbar? The goal is to detect when the listview is scrolled and then get all visible items (or just the top one and work my way down since I know how many can be visible at a time) and do some function..."
I then replied to my own post.

The simple idea of overlaying the listview with a vscrollbar works great and is an important technique for CF lists with a large number of items (for memory and performance improvements). What I am trying to say is that, rather than populate your list with XXX number of items, you need only populate the visible (e.g. 8-16) items and when the user scrolls down populate accordingly the remainder (since you know the top index and the number of visible items at any one time).

The same principle, but with a twist, applies when the listviewitems need to be refreshed/updated every so often. E.g. my listviews get populated with information retrieved from the network. By knowing which items are visible, I avoid refreshing the ones that are not, resulting in faster user interaction and less noise on the network. By also wrapping the refresh timer into the container control, the rest of the client code is oblivious to how the list gets populated.

Finally, you could offer explicit pageup/pagedown buttons (since you are in programmatic control of the scrolling). A screen shot of what such a listview looks like see this (the statusbar of that screenshot is a whole different story :-).

Enjoy the code from the link at the top of this post and if you need the same for a ListControl rather than a listview, follow the link from here.

How do I serve webpages from NETCF?

Mon, February 21, 2005, 09:03 AM under MobileAndEmbedded
Over the last 2-3 weeks I have discussed on 3 completely separate occasions the subject of serving web pages from a CF application on a Windows CE device. Since ASP.NET is not supported on the Compact Framework, the question I get is "how to" and my answer is typically along these lines:

There are 3+1 options
1. Native Only
2. Managed Only
3. Hybrid
4. Wait for CF 3.0 (?)

1. The first option is basically not an option if you are determined to leverage your business logic, which is already written in C# or VB.NET. However, I always mention it because I think it is important to understand what the out-of-the-box options are on Windows CE. You can find them here.

2. The second option basically means writing your own web server (and hence not taking advantage of IIS on WinCE). This either makes faces drop ("Are you serious?") or produces smiles ("I am a control freak anyway so having complete command of how the web server works sounds great!"). Either way, you don't have to start from scratch, as others have been there before (use them as inspiration or just rip off their implementations).
a) Port cassini
b) Use the results of the Monash project
c) Port the ASP.NET MONO implementation (not aware of any *public* project that has achieved it, but there are some guys that have done it (ended up at ~1300KB) and if they want to go public with it I am sure they will - I cannot say anything else, I'm afraid)

3. If you followed my link when discussing the first option, you know that on WinCE you typically write an ISAPI extension for serving pages; imagine if from the ISAPI extension entry point (HttpExtensionProc) you could start talking to a managed dll that did the work for generating and returning the pages. Alas, unlike the desktop, hosting the runtime is not an option with NETCF. So what is it that I always offer as a poor alternative for hosting the runtime? Inter-Process Communication! So, to summarise the hybrid approach with CF 1.0/2.0: Write some C code that seats between IIS and a managed exe communicating via any IPC mechanism you see fit.

4. This is not a serious option for two reasons: Who in their right mind will wait for CF 3.0 when even CF 2.0 is not released yet (does anybody work for a company that looks that far into the future)? The second reason this is not a serious option is because nobody knows what CF 3.0 will offer! My hope is that the CF team will listen to requests on allowing us to host the CLR (this will make option 3 a breeze) or even better offer ASP.NETcf (and then I woke up :-)

Expect to read more on this topic here in the future, as I am looking at this feature for one of our products.

Netmodules revisited

Tue, February 15, 2005, 01:25 PM under MobileAndEmbedded
Alternative title: "Discovery of the day, link.exe"

Recall how at the Beta 1 timeframe we saw CF 2.0 add support for multi-file assemblies? If not, please go and read it, as the content here builds on that (here based on November CTP).

a) Follow steps 1, 2 and 3 from that post (adjusting the path to [drive letter]\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\CompactFramework\2.0\Debugger\BCL).

b) Change step 4 by typing /t:module just before ProgramMixed.cs
You now have two files (Form1Mixed.netmodule & ProgramMixed.netmodule) but, instead of one of them being an exe and the other a netmodule, they are both netmodules. Recall from step 5 that running the exe would work only if the netmodule accompanied the exe (hence the talk of multi-file assemblies).

c) Now, enter the following at the command line:
link /LTCG /verbose /entry:MixedLanguages.Program.Main /out:SingleFile.exe Form1Mixed.netmodule ProgramMixed.netmodule /subsystem:windows

The result is a single executable that contains the IL from both netmodules (that you recall were written in two different languages)! And we didn't even have to use ilmerge.

[This blog entry was inspired by this post]

Headless support... cut!

Tue, February 8, 2005, 03:02 AM under MobileAndEmbedded
Mike Zintel has a follow up to his previous post (the one which made me throw the rattle out of the pram). I'll give you a few minutes to go read it if you promise to come back.

Is it shocking or what?
Headless device support is close to being dropped!
Anyone got a helmet? I'll need it as I inform my team that the business logic wrapped in my .NET code cannot be used on our new product and we have to rewrite it in eVC! Can you guess the response? Perhaps something along the lines of: "Why didn't we do that in the first place?"

.NET CF 3.0

Fri, February 4, 2005, 03:26 PM under MobileAndEmbedded
We haven't even got CF 2.0 yet and Mike Zintel is talking about CF 3.0... fantastic! Go let the team know what you want.

The focus for CF 3.0 will be
"making it easier to deal with transiently connected networks."
Only a fool would argue that it is not an important area and I will not be that fool; however, I would like to offer my wish list leading with a statement (warning, rant ahead):

.NET Compact Framework is not only about mobile devices!

I understand that the focus is on Windows Mobile devices but *PLEASE* give some thought to custom-WinCE-based devices. Vanilla CE devices. Non-PPC devices. I don't care what you call it, but you know what I am talking about.

There are devices fixed on a wall with a permanent network connection. Do you want such a device to run Windows CE? What development language do you expect me to use, C++? If that is the answer, I don't have a problem, but just come out and say it! I can tell you that NETCF 1.0 is perfectly capable of satisfying the initial need, but when trying to take an application to the next step... brick walls. Example:

- Web server & Web Services (*not* client).

Give me ASP.NET on the device! Componentize it so if you don't want PPCs to suffer the footprint, they can opt out.

You should be striving for CF 3.0 to be the sensible choice for WinCE development. Is there any *new* project for the PC starting its life based on C++? Madness, in my view; dotnet or Java are the only sensible choices. Do the same for Windows CE. Today most WinCE old hats still cringe at the sound of CF. Tomorrow with CF 2.0 it will get better. With CF 3.0, unless I am writing drivers, choosing C++ should be a laughable choice. Magneto comes with managed platform interfaces; Longhorn will come with managed platform interfaces; are we ever going to see that in the core WinCE OS?

If I hear or read one more time that "NETCF = mobile battery-powered occasionally-connected device", I'll unscrew my unit off the wall, pull the ethernet & power cables out and hit somebody on the head with it!

Not to finish on a violent tone, let me summarise:
1. ASP.NET on the device (implies the ability to host the runtime)
2. Parity with the desktop. Give me the .NET Framework on the device and componentise it so OEMs can opt out.
3. Throw a bone to non-PPC developers

"...pretty please, with sugar on top..."

Could not load this custom viewer

Wed, February 2, 2005, 02:14 PM under MobileAndEmbedded
It seems that every other week some blogger somewhere discovers the great new VS2005 feature: custom Debugger Visualizers. How many of you realise this doesn't work for Smart Device Projects?

For example, if in a Compact Framework 2.0 project you try my DV sample you'll see the option, but selecting it produces the following error:
---------------------------
Microsoft Visual Studio
---------------------------
Could not load this custom viewer.
---------------------------
OK
---------------------------

I know there is no need to encourage you too much to go make the product better :-)

Win32Api

Mon, January 31, 2005, 04:01 PM under MobileAndEmbedded
Every .NET developer is familiar with platform invocation services (PInvoke), the ability to call native functions declared in dlls via the DllImport attribute. In the early .NET days it was common to see queries about specific API declarations, but 4 years down the road you would have thought people would stop asking and instead use the ready-made ones easily found all over the web. This blog entry is proof of the opposite and it will serve as my pointer next time someone requests a particular Win32 DllImport declaration.

First place to go is the pinvoke wiki (tip: check out the Helpful tools). This was started by Adam Nathan (author of the only COM Interop book you need, which covers interoperability in general and not just COM).

From a Compact Framework perspective, the first place to go is the OpenNETCF source. Search it for the API name you are after and steal the C# DllImport declaration :-)

In addition to the above, since I often refer to a Win32Api class in both newsgroup and blog posts, I include here a link to my own Win32Api.vb (as the extension suggests, it is in VB.NET so the C#-challenged amongst you may prefer it)

Win32Api is a class with the dllimports that I use in my projects (exposed as Shared methods). It started life years ago when I was doing desktop development and was subsequently morphed to support both compact and Full frameworks (hint: look for the FULL_FRAME compilation constant). I don't claim to have crafted every declaration myself, quite the opposite, half of them are probably lifted from ready made declarations found on the web :-)

PB SDK for VS

Fri, January 28, 2005, 12:58 PM under MobileAndEmbedded
For those that write Compact Framework applications for custom CE devices, the VS emulators are not as useful as they are for PPC development.

We always advise people to get an SDK from the device manufacturer – or even better an actual device to test against. I have been lucky to be playing with a real device from day 1, never having to use the emulator for real development. If you are trying to generate an SDK from Platform Builder, you may find that it is not easy to get it right first time, and more often than not you end up with a black-screen emulator that VS.NET 2003 cannot connect to. The fun bit is where the emulator works OK in eVC, and then when you try to use it in VS, not only it doesn't work but it actually hoses the emulator in such a way that it stops working in eVC, but I digress.

So I thought it useful to include here the *exact* steps that work for us when building (and exporting) an SDK for use in both VS and eVC. Enjoy :-)

1. Make a new platform based on Emulator BSP
2. Configure the image as you require (make sure the image includes .NET Compact Framework, toolhelp.dll and Smart Device Authentication Utility)
3. Make sure that KITL support is disabled in the image (i.e. when you select Platform -> Settings -> Build Options, the only thing that should be checked is "Enable EBOOT Space in Memory")
4. Build the Emulator image
5. Configure the SDK
On the emulation tab - this is up to you e.g. memory size = 64MB and screen size = 320x240, 8 bit
On the transports tab - Make sure Microsoft KITL Transport is *not* checked, set ActiveSync as the default
On the Development Languages Tab - Select everything (so the same SDK will work in eVC++ and VS.NET)
On the Startup Servers tab - Make sure they're all selected and that ActiveSync is the default.
6. Build the SDK

Default Font ignored

Thu, January 27, 2005, 01:01 PM under MobileAndEmbedded
In a Sentence (or five)
When NETCF controls are created they have a default Font. You would expect the default Font to be picked from the platform (operating system) default Font. However, that is not the case and instead they start of with Tahoma. This cannot be defended as a design choice so it must be a bug! Vote for it to be fixed (the bug is present in CF 1.0 and CF 2.0).

Repro Steps
1. Create a new form
2. Add a button to it (or any other control including custom ones)
3. In the button event handler put the following code:
MessageBox.Show(this.Font.Name,Button1.Font.Name); //C#
MessageBox.Show(Me.Font.Name,Button1.Font.Name) ' VB
4. You see Tahoma, Tahoma (assuming your system default is Tahoma)

5. Change the system's default Font to Arial or Courier New (or some other Font on your unit)
HKLM\System\GDI\SysFnt\Nm
HKLM\System\GWE\Menu\BarFnt\Nm
HKLM\System\GWE\Menu\popFnt\Nm

6. Reset the unit and run the test again
7. You see Arial, Tahoma (they should both be Arial - or whatever the system default is)

Why Fix the Bug
1. 99.99% of controls never have their Font changed by the developer; in fact the only times we change font is for size or style, not name. Hence we expect the Font to be the system default.
2. If we run an app like that on a unit where the default font has changed, it will not pick it up.
3. eVC defaults to system Font so there is no precedence of hardcoding default fonts
4. As the repro steps show, there is inconsistency within the implementation itself. The title bar caption/text the default font whereas the other controls use the hardcoded Tahoma
5. Further inconsistency is that the menu fonts are picked up properly. Even the built-in error handler dialog picks up the correct Font.
6. Changing the Font of every control in Smart Device projects is more cumbersome than the desktop since changing the Font of a container (e.g. Form, Panel) does not propagate to the children controls (no Ambient properties on CF)

How I came across it
Due to other reasons, we have to change the default font of our platform to Arial. Half the screens look odd and I now have to go and explicitly change the Font for all controls. Yes I know "poor me" but that is not the point. Next time we decide to change the default Font I will have to change the hardcoded values since the NETCF controls are not smart enough to pick the default.

How small?!

Wed, January 26, 2005, 03:26 PM under MobileAndEmbedded
Most people associate Compact Framework target devices with Pocket PCs only. This is very convenient for the developer in many ways, e.g. a screen resolution of 240x320 and the presence of a stylus are presumed in most cases.

Imagine you are targeting a device with a very small display (e.g. 105x32mm, 240x64pixels). Naturally, you need to maximise the amount of elements you can fit on a screen, to make it useful. If you take the imaginary scenario further and say that the display is *not* touchscreen (instead hardware buttons provide the only way to drive the UI), then it becomes even more obvious that the GUI controls should be as small as possible (just large enough to read and as small as you can get away with).

Imaginary scenarios interest me, so I thought I'd see how the CF (and by extension WinCE) caters for such an eventuality. The focus is on the Height of controls (Width is not only pretty much adjustable, but also not the dominant limiting factor).

Naturally the following controls are irrelevant: Panel, PictureBox and Timer.

The following controls can be resized (and where applicable their Font is changeable to accommodate the size reduction):
Button, Label, TextBox, ListBox, ProgressBar, TabControl, TrackBar, Datagrid, TreeView, ListView, HScrollBar and VScrollBar

The Toolbar does not have a Size property, but its height is controlled by the size of the images associated with it (on custom WinCE devices, not PPC!). So by adding 8x8 icons to the ImageList associated with the toolbar (or by just changing the ImageSize property), the toolbar will be high enough to fit those images - nice. Like the Toolbar, the TreeView and ListView also play nice with the image size (if there is an ImageList associated with them, otherwise like I said in the previous paragraph, the Size/Font properties also work).

Once the size and Font of controls such as ListView, ListBox and TreeView is decreased, it sticks out like a sore thumb that their scrollbars are too thick. Not a big problem, though, as this can be controlled by the following registry settings:
HKLM\System\GWE , DWORD values "cxHScr", "cyHScr", "cxVScr", "cyVScr"

Menus (MainMenu, ContextMenu and MenuItem) are resized according to their Font. However, they do not expose a Font property, so you are stuck with whatever the default Font is for the platform. You can change that through the registry:
HKLM\Menu\BarFnt , DWORD "Ht" for height , DWORD "Wt" for boldness: 700 or 400
HKLM\Menu\PopFnt same as above, but this applies to menu items rather than the menu bar

The following controls are problematic:
-DomainUpDown and NumericUpDown can have their height changed but, before you get too excited, their Font is *not* changeable and in fact attempting to assign a Font results in a NotSupportedException at runtime! Net result: these controls have, effectively, a fixed minimum height (The CF 2.0 story is the same, except now the Font property is not exposed at all).
-ComboBox and StatusBar have the reverse problem: You can change their Font but not their Height - it compiles but no runtime change is observed (The CF 2.0 story is the same, except now the Height property is not exposed at all).
-CheckBox and RadioButton shrink, but the square box and circle respectively are of fixed size!
-We saw that menus can be shrunk based on Font size, but the Menu bar *height* is not configurable.

Showing off some of the above is this screen capture

VOTE for the WinCE/NETCF teams to improve in this area.

We already saw registry settings for scrollbars and menu font, here is one more that helps (reset is required before any effect takes place for all these):
HKLM\System\GWE , DWORD "cyCap" changes the height of a windows caption/title bar. Note that, if the Font is not changed accordingly, the text will not be rendered.

For more registry entries see here. I have played with all of them on our platform and found that they are more geared for large displays rather than smaller ones. In other words, the defaults are already targetting small displays, so if you want to go smaller there isn't much there :-(

Desktop to PPC (Part B)

Tue, January 25, 2005, 03:17 PM under MobileAndEmbedded
Continuing from part A (if you haven't read it, we'll wait for you...go on then :-)

5. Take over the device
Popular desire amongst devs is to take over the device. Their app is so important that nothing else should be accessible. This is not as bad as it may sound, as in some cases the application really is the raison d'etre of the device. Every solution described seems to create more issues, so there doesn't seem to be a clean one-rule-fits-all. If you have this requirement, here are some links for you to pursue [1, 2, 3, 4, 5, 6] (in other words search for "full screen" and "kiosk")

6. File System
The storage system on PPCs is similar to the desktop, with only a couple of differences. There is no C:\ drive; everything starts at the root, so an example path is this: "\Program Files\Some Folder\MyApp.exe". More importantly, there is no concept of current directory, the implication of which is that you must always use absolute paths (like the example above). To get the directory of your NETCF app, see this. Note that the OpenFileDialog will only let you browse the "My documents" directory, so if you need to go to other places you have to create your own.

7. Memory Constraint
An obvious difference with PPC devices is the limited memory that is available. When the device runs into low memory situations, it will start closing open windows (this is not minimising, it is real closing). If you get in such a scenario, some people advise to try hooking into the WM_HIBERNATE/WM_CLOSE windows msg; I advise you to revisit your architecture and not consume so much memory in the first place. Measure and set the expected memory your app requires to run smoothly, and if it doesn't get that on a device, it simply means the environment does not meet your criteria. You should, of course, be cleaning up resources in the Form.Closing events in any case. For more on memory problems see Memory Problems FAQ

8. Deployment
Deployment is quite different on devices than to the PC and all links you need on this topic are already provided here

9. Question: "How do I take advantage of my existing desktop .NET code?"
Answer: Share the code

If you are using the NETCF for targetting a device other than PPC (like me), you cannot make any of the above statements without knowing the specifics of the device (all custom CE-based devices are different). In this MSDN article, you can see some of the differences between PPC projects and WinCE projects in VS.NET 2003. I may do an entry on the topic too, at some point in the future.

Desktop to PPC (Part A)

Mon, January 24, 2005, 03:16 PM under MobileAndEmbedded
With the Compact Framework making programming for devices so easy, there is an increasing number of desktop developers making the move to CF development (or at least getting their feet wet). They face the challenges of a .NET Framework that is missing whole areas (e.g. Remoting, COM Interop, ASP.NET) and has every interface trimmed down (e.g. the Thread has only 2 public instance members) - it is not called the *Compact* Framework for nothing. Many of my blog entries focus on exactly that: the differences between the full and compact frameworks and sometimes how to bridge the gap.

However, another difference is the actual operating system or platform. This bites the developer even more if they are not daily users of a Pocket PC (which is the target of 95% of the NETCF developers). The situation described has as a consequence a lot of questions in the CF newsgroup, so I will try to address some of these in this entry and point to it in the future (as an FAQ).

1. Input methods
PPCs do not have a mouse or a keyboard (for the few devices that have, keyboard events are supported by some NETCF controls since Service Pack 2). The lack of a mouse is catered by a touch screen and the use of a stylus (mouse events are not supported in most controls and you may need to create your own control; help for custom controls is here, here and here). Right-click context menus are simulated by tap-and-hold (made possible by the aygshell.dll that is part of the PPC platform). There is a Soft Input Panel (SIP), which is a software keyboard that can pop up on the screen. To interact with it, you must reference Microsoft.WindowsCE.Forms.dll and drag the InputPanel control onto your form. To show it, you call InputPanel1.Enabled = true, typically in the GotFocus event of a TextBox (and set it to false in the LostFocus). To detect when it is up or down, you can track the InputPanel.EnabledChanged event. Note that hand-in-hand with the InputPanel is the MainMenu control that your form must have - even if it doesn't use it (!)

2. Form/Dialog size
Forms and dialogs on the PPC are always full screen (the only exception to that rule is the built-in MessageBox). There are known workarounds, but it seems that they hurt more than they help, so my advice is to stick with full screen dialogs and design for that approach from day 1. Try to design the UI so the user never gets the impression they are interacting with more than one screen; use multiple hidden panels on one form and swap them in/out as appropriate.

3. App/Form closing
The design guidelines for the PPC are clear: Applications do not exit/close, instead they minimise. This aids in the concept of a device that is always on (and the apps are always available, without waiting for them to load each time). For NETCF apps, setting the Form1.MinimizeBox to true will display the X button in the top right, whereas MinimizeBox=false will instead show a little OK button in the top right. Clicking an X minimizes the form, whereas clicking an OK closes the form and by extension the application if the form is the application's main form. Note that minimising is not identical to the desktop, i.e. all that happens to the window is that it is pushed to the back of the stack of open windows on the PPC. To programmatically know when a smart minimize occurs, you should hook into the Form1.Deactivate event (which is supported even though designer support is missing).

4. Moving between applications
Following from points 2 & 3 above, you might wonder how you switch between applications. There are various ways: By closing (minimising really) windows, you can reach the desired one OR you can use the top-right Start menu (Windows icon) OR open the Start->Settings->System->Memory->Running Programs screen. The "Running Programs List" displays all the open windows (minimised or not) and allows you to switch between them. This presents a problem in a scenario where your app has Form_A opening Form_B and you only expect the user to get back to Form_A after closing Form_B; they can also go to Form_A by using the "Running Programs List"! The workaround is to only show in the list the active form and to do that you must set the caption (Form1.Text) of other forms to String.Empty (""). By the way, if you are having trouble bringing your application to the front programmatically, read that.

In my opinion, these are the top 4 gotchas for desktop devs moving to the PPC platform. Look forward to the next 4 or 5 in part B.

Semaphore

Sat, January 22, 2005, 10:34 AM under MobileAndEmbedded
We looked at the implementation of EventWaitHandle for the NETCF 1.0 & 2.0

Here, I offer an implementation of Semaphore (another new Whidbey class inheriting from WaitHandle). If you are looking for it (e.g. in your Object Browser), note that unlike every other System.Threading class, it is in System.dll (and not mscorlib) (!)

Get the C# version from OpenNETCF (like most of my other contributions, in 1.3), and the VB version is available right now: Semaphore.vb

EventWaitHandle

Wed, January 19, 2005, 02:39 PM under MobileAndEmbedded
We looked at the absense of a nice class from NETCF (today & tomorrow). Here I will offer an implementation of the .NET 2.0 EventWaitHandle for the NETCF.

The C# version is over at the SDF, and the VB version is right here

Take note of inheritance limitations as described before, and obviously I have omitted parts of the interface that do not apply on WinCE. Finally, if you only wanted the class for CF 1.0 or just for CF 2.0, there are changes you can apply to the implementation - as it stands, it works on both :-)

WaitHandle

Tue, January 18, 2005, 02:21 PM under MobileAndEmbedded
As part of some restructuring for my app, I had to dig into the abstract System.Threading.WaitHandle class. As you'd expect, this is different on NETCF to the Full Fx, and both have changed with Whidbey (based on November CTP).

NETCF 1.0 vs .NET 1.1
The CF version does not provide the WaitAll or WaitAny methods; it only provides the basic parameterless overload of WaitOne. Comparing the total number of members (fields, properties, methods) regardless of scope, we find the CF version having half the members than the Full Fx (13 vs 26).

.NET 1.1 vs .NET 2.0
The main addition we'll get is the public static SignalAndWait methods (3 overloads). The class grows by 9 members in total. The other change is the replacement of the Handle type. Instead of using an IntPtr, it is now of the newly introduced SafeWaitHandle (of the new Microsoft.Win32.SafeHandles namespace)

NETCF 1.0 vs NETCF 2.0The WaitHandle in CF 2.0 brings no changes compared to CF 1.0 apart from implementing the IDisposable.Dispose method (that the Full Fx classes do in all versions).

Getting to the point
So why am I looking at this class? Well actually, I am not interested in the class itself; it is the derived classes that are interesting, and to understand an object's behaviour you must understand its parents. In .NET 1.1 and NETCF 1.0 the public inheritance relationship is:
Figure A
WaitHandle : MarshalByRefObject
|-> Mutex
|-> AutoResetEvent
|-> ManualResetEvent

In .NET 2.0 this changes with the introduction of a new class (and the one that interests me) EventWaitHandle:
Figure B
WaitHandle : MarshalByRefObject
|-> Mutex
|-> EventWaitHandle
|-> AutoResetEvent
|-> ManualResetEvent
|->Semaphore

EventWaitHandle is not supported in CF 2.0 and, in fact, the whole inheritance hierarchy remains the same in CF 2.0 as it is today (i.e. Figure A). Ignoring Semaphore for the time being (maybe a subject of a future post), I would have urged you to go vote but the inclusion of EventWaitHandle to NETCF has already been postponed.

The main use of this class would be for creating named events which play a prominent role in Inter-Process Communication on WinCE.

Next time we'll look at wrapping the pinvokes required to offer a class that exposes the same interface as EventWaitHandle (unfortunately, though, it cannot fit in the same inheritance hierarchy as the desktop, i.e. we cannot change the existing Compact Framework XXXXResetEvent classes to inherit from the EventWaitHandle we introduce, rather than the WaitHandle that they do).

Memory Problems FAQ

Tue, January 11, 2005, 11:34 AM under MobileAndEmbedded
A great number of posts in the NETCF newsgroup are memory related. This is no surprise, given the constraints of devices (as opposed to the PC), and most posts somehow end with a variation on this tail question: "[...] is this a known memory leak with the CF?"

Given that there are plenty of CF resources to help you in this area, I thought I'd gather them up in a single place for future reference.

1. The first thing to do is make sure you are running the latest released CF version. Contrary to popular misconception, this is (today) CF 1.0 SP3. For CF version info (numbers, how to determine it, where to get it etc) please go here.

2. Doing the above is good regardless of anything else; the second thing to address is "Are you really having memory troubles?” Can you reproduce a sample where you get an OutOfMemoryException? If not, why do you think there is a memory leak! This is common to devs still new to the managed world, where resources are not reclaimed immediately after they have been used. A rule of thumb applies here: if an object you are using offers the Dispose method, call it when you have finished using the object.

3. So we've now reached the case where you can reproduce a sample that throws the OutOfMemoryException (or at the very least that is what your main app does). Before you start pointing fingers at the Garbage Collector, please understand how the GC works (note the significant differences compared to the Full Fx version i.e. not generational, code pitching etc). Once you've done that, understand some v1.0 issues and workarounds, including when to call GC.Collect

4. "Fine with all the theory, but how do I measure?" You have a number of options available (please use them):
- Call GC.GetTotalMemory(false)
- PInvoke GlobalMemoryStatus (FAQ 6.5)
- Monitor Perf Statistics/Counters (do follow the links from that blog entry)
- Device's control panel applet e.g. on WinCE emulator, Start->Settings->System look under the Memory tab for memory info and how to change the memory distribution (check out the FAQ on the WinCE memory division between Storage and Program memory)

5. For completeness, here is a link to an in-depth article on WinCE memory management. The main takeaway, if you are coming from a desktop background, is that each process in CE has a limit of 32MB virtual address space; so forget loading all those massive bitmaps in memory.

6. On very extremely rare occasions you may possibly observe a "Low Memory Dialog" rather than an OutOfMemoryException. This is the OOM dialog which shouldn't, but may, pop-up before a managed exception is thrown. That is an indication that you are stressing the system but, if you really want to, you can remove the OOM component from your device - assuming you have control of the image with Platform Builder (if you are in that situation, check out the SetOomEvent and registry entries).

7. Finally, if none of the links above take you to long documents with many numbers, go read Advanced Memory article on CF 2.0

Deploy to My Computer

Fri, January 7, 2005, 11:28 AM under MobileAndEmbedded
Regular readers will recall the deployment feature for Smart Device projects that was cut after Beta 1. It has now been confirmed that the "Deploy to My Computer" feature will not be supported for RTM. However, there are some steps you can follow to get it working (it just won't be supported) and it is likely that in the future there will be a powertoy to do the steps for you.

If you want more details on the feature I am talking about, and more importantly want to follow the steps to get "Deploy to My Computer" working today with the November CTP, please visit ladybug.

Below is a copy of the steps (which I can confirm work... on my setup anyway:-).

This is courtesy of Kei Amos:
Enabling deployment of managed applications to the desktop rather than a device:

This is a great productivity enhancement for application development, when you deploy often.
Note: Applications that use device-specific apps will not run properly on the desktop, and controls will render as desktop controls.

INSTRUCTIONS
1. In Visual Studio select Tools/Options, and then select Device Tools/Devices from the tree.
2. In the top combo box, select the platform that you want to add desktop deployment to. You’ll need to do this for each platform you want to use.
3. Select one of the devices, (it doesn’t matter which one) and click the Save As… button. Save as “My Computer”. If you’ve already done this for a platform, you’ll need to save subsequent devices with slightly different names (like “My Computer2”)
4. Close VS and open your %USERPROFILE%\Local Settings\Application Data\Microsoft\CoreCon\1.0\conman_ds_platform.xsl file in a text editor.
5. Find the <DEVICE …> element corresponding to the device you created and add the node (i.e. search for “My Computer” to find the correct node.)
<PROPERTY ID="IsDesktopDevice" Name="IsDesktopDevice">true</PROPERTY>
Place it right after the first <PROPERTYCONTAINER> tag.
6. Save conman_ds_platform.xsl and restart VS.

Now when you deploy, you can select “My Computer” from the deploy dialog.


UPDATE: For Beta 2, also see this thread

NETCF SP3 RTM

Wed, January 5, 2005, 03:07 PM under MobileAndEmbedded
The latest Service Pack 3 for the .NET Compact Framework is now released as an MSI (via Tom Krueger). It was previously available as a QFE only.

For version number and full fix list please visit my previous announcement of the QFE release.

For history of NETCF version numbers and how to determine what version you are running see the wiki page.

JIT

Fri, December 31, 2004, 06:35 AM under MobileAndEmbedded
By now, all .NET developers know that their managed code (C#, VB.NET etc) gets compiled to Intermediate Language (IL) which itself, at runtime, gets Just-In-Time (JIT) compiled to native code. Here we'll look at some of the differences of the NET Compact Framework JIT engine compared to the desktop (full framework), as well as what CF 2.0 will change.

As a historical aside, the alpha (pre-RTM) version of the CF did not have a JIT compiler and instead IL was interpreted on the device. Since RTM (for CF version info please go here), the IL is JITted to native code on the device/target. This is done on a per method basis (like on the Full Fx). When a method is called, it is detected that there is no native code for the method, so IL is compiled into native code and executed; next time the method is called the native code gets executed, which means that the JIT performance penalty is only incurred once.

The major difference on the CF is that the native code is cached in the GC heap (i.e. in RAM) and is susceptible to "pitching" if a full GC occurs (for more detail on GC phases and pitching look there). In other words, the JITted native code can be thrown away under memory pressure, so next time a recompilation has to take place for any methods that were pitched. Do not confuse pitching methods with the actual type data structures (metadata), which are never pitched once loaded.

To obtain some numbers for your CF app, you should use the perf counters. In particular focus on: Bytes Jitted, Native Bytes Jitted, Number Of Methods Jitted, Bytes Pitched and Number Of Methods Pitched

Another difference in the same area is that ngen is not supported on the NETCF. So you cannot pre-compile your assemblies to native images.

Finally, note that the JITted code has a limit of 64K (native size, not managed). You wouldn't expect to hit that limit, but very large forms can break the rule in their auto-generated InitializeComponent method. The workaround is to split the method into smaller ones (at the expense of losing designer support).

CF 1.0 comes with two JIT compilers: sJIT and iJIT. The former is for ARM devices only and the latter is for all other CPU architectures (inc. SH3, MIPS, x86). SJIT takes slightly longer to compile IL to native code, but the resulting code is faster than what IJIT can produce (there is a detailed slide "Differencies between JITs" in this ppt, for anoraks :-)

CF 2.0 comes with a unified JIT, which is more performant and optimised than what we have today. Note that VS2005 will ship with ARM CPU Emulators and not x86 like today, so the emulation experience will be enhanced from a performance perspective too.

As you recall I have read all CF books, so I can tell you that both Building Solutions with the CF and CF Kick Start include short paragprahs on JITting. The NETCF bible dedicates a few pages on the JITted Code Pool / native image cache.

Happy New Year!

BackgroundWorker Sample

Wed, December 29, 2004, 06:46 PM under MobileAndEmbedded
You should be familiar by now with Whidbey's excellent BackgroundWorker class and my implementation of it for the Compact Framework 1.0 - for immediate use today :-)

Although the MSDN examples and walkthroughs (as described on the above link) are great, I thought I would port Chris Sells's sample from the excellent article he wrote a while back: Asynchronous Calculation of PI digits. I encourage you to download the code from that article and compare it against the code I present here. It will instantly become apparent what power the BackgroundWorker brings in terms of simple code to write, read and maintain (let alone understand, but that might be a drawback depending on your outlook :-).

The form looks like this.

You can download the project at the end of this entry, but here is all of the relevant code (works on both CF and desktop):
        // Declare the worker
private BackgroundWorker mBW;

// Call this method in form's ctor
private void InitBW(){
mBW = new BackgroundWorker(this);
mBW.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(mBW_RunWorkerCompleted);
mBW.ProgressChanged
+= new ProgressChangedEventHandler(mBW_ProgressChanged);
mBW.DoWork += new DoWorkEventHandler(mBW_DoWork);
mBW.WorkerReportsProgress = true;
mBW.WorkerSupportsCancellation = true;
}

// Handles click for Calc/Cancel button
private void cmdCalc_Click(object sender, System.EventArgs e) {
if (cmdCalc.Text == "Calc"){
// read digits from numeric updown control
int digits = (int)nuDigits.Value;
pbLeft.Maximum = digits;
// ask worker to do its job
mBW.RunWorkerAsync(digits);
cmdCalc.Text = "Cancel";

}else if (cmdCalc.Text == "Cancel"){
// ask worker to cancel
cmdCalc.Enabled = false;
mBW.CancelAsync();

}else{
// Only two enabled states for
// this button: Calc and Cancel
System.Diagnostics.Debug.Assert(false);
}
}

// Completion event
private void mBW_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e) {
// Just get ready for next time
cmdCalc.Text = "Calc";
cmdCalc.Enabled = true;
}

// Progress event
private void mBW_ProgressChanged(object sender,
ProgressChangedEventArgs e) {
// Touch GUI, no problem
pbLeft.Value = e.ProgressPercentage;
txtPi.Text = (string)e.UserState;
}

// On worker thread! Only method with real logic
private void mBW_DoWork(object sender, DoWorkEventArgs e) {
int digits = (int)e.Argument;
BackgroundWorker bw = (BackgroundWorker)sender;

// we will be updating the UI with progress
string pi = "3";

// Show progress (ignoring Cancel so soon)
bw.ReportProgress(0, pi);

if( digits > 0 ) {
pi += ".";

for( int i = 0; i < digits; i += 9 ) {
// Work out pi. Scientific bit :-)
int nineDigits = NineDigitsOfPi.StartingAt(i + 1);
int digitCount = System.Math.Min(digits - i, 9);
string ds = System.String.Format("{0:D9}", nineDigits);
pi += ds.Substring(0, digitCount);

// Show progress
bw.ReportProgress(i + digitCount, pi);

// Deal with possible cancellation
if (bw.CancellationPending == true){
e.Cancel = true;
break;
}
}
}

}

Download the project (zip).

CF 2.0 Performance Statistics revisited

Tue, December 28, 2004, 10:57 AM under MobileAndEmbedded
In the past, I have talked about the performance counters for CF 1.0 apps, including a list of the new counters that CF 2.0 adds (based on the VS2005 Beta 1). It seems that with the November CTP the list has changed again. Rather than list what has changed from Beta 1 or comparing it with what we have today with NETCF 1.0, I give you the complete list. Notice that some of today's counters have been removed (e.g. "Execution Engine Startup Time") and some have clearer names (e.g. "Peak Bytes Allocated (native + managed)"). Finally, before we look at the list, note that the statistics file has changed from mscoree.stat to ExeName.stat

List of perf counters with the November CTP of CF 2.0:
Total Program Run Time (ms)
App Domains Created
App Domains Unloaded
Assemblies Loaded
Classes Loaded
Uncontested Monitor.Enter Calls
Contested Monitor.Enter Calls
Threads in Thread Pool
Pending Timers
Scheduled Timers
Timers Delayed by Thread Pool Limit
Work Items Queued
Peak Bytes Allocated (native + managed)
Managed Objects Allocated
Managed Bytes Allocated
Garbage Collections (GC)
Bytes Collected By GC
Managed Bytes In Use After GC
Total Bytes In Use After GC
GC Compactions
Code Pitchings
Calls to GC.Collect
GC Latency Time (ms)
Pinned Objects
Objects Moved by Compactor
Objects Not Moved by Compactor
Objects Finalized
Boxed Value Types
Process Heap
Short Term Heap
Jit Heap
App Domain Heap
GC Heap
Native Bytes Jitted
Methods Jitted
Bytes Pitched
Methods Pitched
Exceptions
Platform Invoke Calls
COM Calls Using a vtable
COM Calls Using IDispatch
Complex marshaling
Runtime Callable Wrappers
Socket Bytes Sent
Socket Bytes Received

UPDATE: Ask and you shall receive. Scott Holden gives us the official list based on the latest internal builds.

Visual Studio WinCE Emulators

Thu, December 23, 2004, 03:09 PM under MobileAndEmbedded
Visual Studio.NET 2003 shipped with a WindowsCE 4.1 Emulator (as well as PPC 2002 emulator, of course). Although the PPC emulators where updated via separate SDK downloads, the WinCE emulator never was. It never got updated, so even today some devs fall into the trap of thinking it is a 4.2 emulator. For example, with the 4.1 emulator, trying to use the InputPanel control (SIP) results in crashing (NullReferenceException more often than not).

Of course, if you are going to be targeting a non-PPC device, you should obtain an SDK that includes an emulator from the provider of the custom CE-based device. Nevertheless, having a generic WinCE emulator out of the box is nice for those quick generic tests.

Whidbey will not ship with a CE 5.0 emulator (and hence none of the Beta or CTPs include one either). The plan, apparently, is to make a CE 5.0 image available after the release of VS2005. If you don't know about it yet, CF 2.0 will only run on CE 5.0 devices and greater (and PPC2003 and greater). I tried installing an SDK created with PlatformBuilder 5.0 but had no success (Beta 1 on Win2K, November CTP on XP) then found out via the private ng that it is not supported yet.

Only recently came across this; granted you can't straightforwardly debug with it and it doesn't work in a Virtual PC, but at least via copying files you can run NETCF 1.0 apps and also CF 2.0 apps (if you deploy the x86 Compact Framework 2.0 cab first)

Generics in Compact Framework

Wed, December 22, 2004, 05:09 AM under MobileAndEmbedded
A disclaimer up front: This is by no means a tutorial or even my original work on Generics. The subject has been discussed in depth ever since it was announced as part of Whidbey. Given that generics were not available in the Compact Framework in previous releases and I did say I would talk about them a bit, here goes some code for CF from the November CTP (tested in the emulator):

I bet 90% of the mileage on generics use will come out of using the classes in the framework and specifically the System.Collections.Generic namespace. An example is this:
' VB - consuming built-in collections
        Dim s As New System.Collections.Generic.Stack(Of Int32)
        s.Push(5)          'no boxing
        s.Push(6)
        's.Push("invalid") 'will not compile :-)
        Dim tot As Int32 = s.Pop() + s.Pop()          'no cast

// C# - consuming built-in collections
    System.Collections.Generic.Stack<int> s;
    s = new Stack<int>();
    s.Push(5); //no boxing
    s.Push(6);
    //s.Push("invalid"); //will not compile :-)
    int tot = s.Pop() + s.Pop(); //no cast

However, you can create your own generics classes and even structs:
' VB - Declare generic struct
Public Structure MyPoint(Of T)
    Dim x As T
    Dim y As T
End Structure

// C# - Declare generic struct
public struct MyPoint<T> {
    T x;
    T y;
}

...and of course consume them:
' VB - consume generic struct
        Dim mp As New MyPoint(Of Single)
        mp.x = 12.3
        mp.y = 5

// C# - Consuming own struct
    MyPoint<float> mp = new MyPoint<float>();
    mp.x = 12.3;
    mp.y = 5.2;

Even more useful, you can create generic methods and impose constraints on the types:
'VB - generic method with constraints
Public NotInheritable Class MyMath
    Private Sub New()
    End Sub
 
    Public Shared Function Min(Of T As IComparable)(ByVal a As T, ByVal b As T) As T
        If a.CompareTo(b) < 0 Then         'no casting + intellisense help
            Return a
        End If
        Return b
    End Function
End Class

// C# - generic method with constraints
public static class MyMath {
    //Min with constraints
    public static T Min<T>(T a, T b) where T : IComparable {
        if (a.CompareTo(b) < 0) {//no casting + intellisense help
            return a;
        }
        return b;
    }
}

' VB - Consume generic method
        Dim m As Int32 = MyMath.Min(6, 8)

// C# - Consume generic method
    int m = MyMath.Min(6, 8);

I have only scratched the surface here, if you want to know more about Generics I encourage you to go searching. I can recommend these articles: [1, 2]

UPDATE (7 Jan 05): Roman Batoukov has the implementation details
UPDATE (26 Jan 05): Nazim Lala has the details on reflection with generics

Watchdog design for CF app

Tue, December 21, 2004, 04:02 PM under MobileAndEmbedded
I encourage you to read my previous entry on watchdogs, even if you are familiar with the topic. It will ensure we are on the same page on principles and terminology.

CF's non-deterministic nature in combination with some areas that can indeed take 100s of milliseconds to process (e.g. form loading) dictate the design choices. Cutting to the chase, I'd say your only viable option is to have another blind process as the dog and then choose a high interval for kicking it from the CF app (i.e. >9 seconds). Further, I suggest the dog is an eVC app with as little baggage as possible. For the kick, you can choose between a variety of IPC mechanisms, and I suggest using a named event. The CF app signals the event and the eVC app waits on it, with a timeout twice as large as the time interval.

The CF app will signal the event exactly like I have described here (i.e. cmdWrite_Click method). Obviously you create the named event and store the handle. On a timer's tick (System.Windows.Forms.Timer; *not* a Threading.Timer) signal the event. Also, signal it before any method that will take some time to complete. You can basically kick the dog from a number of places, but the important one is the kick from the UI thread on a timer whose interval is half the interval defined in the dog process.

So the C app acting as the dog has code similar to this pseudo code:
// in a thread

while(1)
{
if (WaitForSingleObject(hDogEvent, 20000) != WAIT_OBJECT_0)
{
//RESET UNIT
}
ResetEvent(hDogEvent);
}

We implemented the above on our platform with a few additions.
1. The dog itself kicks the hardware watchdog on our unit. So should anything go wrong with that process (effectively should something go wrong in the OS), our unit resets.
2. The dog is also the launcher of the CF app on unit startup. So the dog starts the CF app and keeps the handle to the process. So, on a separate thread, it waits on the process handle; if that returns (interpreted as the app has exited), it also resets the unit. [Note there is no mechanism for the user to terminate the CF app but, in the case where the process is nuked for whatever reason, the dog does not have to wait for the interval and instead resets the unit immediately.]
3. Before resetting the unit, it stores in the registry the reset reason with a timestamp (the app also does that in cases where it legitimatly resets the unit e.g. language change) - the diagnostic value of this is obvious.
4. If I told you, I'd have to kill you :-)

And as an aside, my CF app displays on a diagnostics page the amount of time it has been running along with the reason it was last reset. We have a unit in the office that has been going for >100 days (although I am sure there are others on the field that have been going for longer ;-)

About Watchdog

Tue, December 21, 2004, 03:47 PM under MobileAndEmbedded
My experience in this area is with CF apps on CE, but the principles apply on other platforms/technologies.

So the requirement is that your application never hangs (e.g. like it would if you touched a UI control from a worker thread) *and* never sits there with a crash dialog the user stares at (like it would if an unhandled exception occurred).

The way we achieve this is by implementing a watchdog. In a sentence, a watchdog monitors your application and when the latter becomes unresponsive, the watchdog takes a certain action. How does the dog know your application is unresponsive? Your application tells it every X units of time (e.g. 5 milliseconds or 30 seconds etc) that it is OK. How does it tell it? By any mechanism you design, e.g. signaling a named event, calling a library/platform method etc. What does the watchdog do when it has not been told for some time? It restarts your app or resets the unit or notifies some other resource. For embedded devices you can get dedicated hardware watchdogs, and even some chips (e.g. the XScale) include watchdog features. WinCE 5.0 offers watchdog APIs so you could even use those rather than roll your own.

No matter how you implement it, the watchdog is usually very simple, in order to avoid it being susceptible to locks/crashes itself!

To recap:
1. You need a watchdog (be it another process, a physical part or whatever) a.k.a. the dog
2. Your watchdogged app tells the dog it is OK on a predefined interval (a.k.a. kick, pet, tickle, stroke etc)
3. When the dog has not received a kick (or a number of) on predefined interval(s) it takes some action (usually restart the app/unit)

You can make the situation more complex by adjusting at runtime the interval (depending on what your app does), you can have different threads in your app kicking at different intervals and so on and so forth.

Next time I'll discuss an application of the above principles for a CF app on a CE device.

AppDomain.UnhandledException Part 2

Mon, December 20, 2004, 04:01 PM under MobileAndEmbedded
Below find the VB code for global exception handling in NETCF, as described here. First though, a sort paragraph that you may skip if you desire.

It is worth noting some behaviours of surrounding Application.Run with try..catch (which we already established is not needed). On its own, it cannot catch exceptions thrown from a thread, but it can catch ones thrown on the GUI. It can also catch them when thrown in a Control.Invoke, but only after the built-in CF error dialog appears. If you use try..catch in combination with AD.UnhandledException, it gets more interesting. The try..catch handler is always hit straight after the AppDomain handler with a ThreadAbortException (and a different StackTrace); in those cases, your handling code better run fast, as the process is on its way out and even a MessageBox will not stay up for long. The exception (no pun intended) to the last comment and the order the two handlers are run, is when the exception is thrown on the GUI thread. So, once again, AppDomain.UnhandledException is all you need.

Without further ado here is the VB version:

Public NotInheritable Class EntryPoint
Private Sub New()
End Sub

<MTAThread()> _
Shared Sub Main()
' Add Global Exception Handler
AddHandler AppDomain.CurrentDomain.UnhandledException, _
AddressOf OnUnhandledException

Application.Run(New Form1)
End Sub

' In CF case only, ALL unhandled exceptions come here
Private Shared Sub OnUnhandledException(ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs)
Dim ex As Exception = TryCast(e.ExceptionObject, Exception)
If (ex IsNot Nothing) Then
' Can't imagine e.IsTerminating ever being false
' or e.ExceptionObject not being an Exception
EntryPoint.HandleException(ex, e.IsTerminating)
End If
End Sub

'' This should not throw any exceptions
'' and should run as quick as possible
Private Shared Sub HandleException(ByVal ex As Exception, _
ByVal t As Boolean)
' Log ex.StackTrace or whatever
'MessageBox.Show(ex.StackTrace, ex.Message);
Dim fs As FileStream = Nothing
Dim sw As StreamWriter = Nothing
Try
fs = New FileStream("GEH.txt", FileMode.Append, _
FileAccess.Write, FileShare.None, 1000, False)
sw = New StreamWriter(fs)
sw.WriteLine("DateStamp: " + DateTime.Now.ToString())
sw.WriteLine("ToString(): " + ex.ToString())
sw.WriteLine("Message: " + ex.Message)
sw.WriteLine("StackTrace: " + ex.StackTrace)
System.Threading.Thread.Sleep(1000) 'for a laugh
sw.WriteLine("THE END")
sw.Flush()
Finally
If sw IsNot Nothing Then
fs.Close()
sw.Close()
End If
End Try
End Sub
End Class


AppDomain.UnhandledException Part 1

Mon, December 20, 2004, 03:49 PM under MobileAndEmbedded
The punchline is that the AppDomain class (along with other enhancements such as AppDomain.Unload), also offers AppDomain.CurrentDomain.UnhandledException. As soon as I saw that (in combination with this), I started running various tests (over 20 different combination scenarios run in release mode with no debugger attached) in order to update an older post on Global Exception Handling on the CF 2.0.

Let's remember that unhandled exception tests must include: Throwing on the GUI, on a ThreadPool thread, Thread, Control.Invoke, object finalizer and after Application.Run when the app is exiting. As you recall, on the desktop the only way to cater for all of these is by hooking into AppDomain.UnhandledException, Application.ThreadException and surround Application.Run with try..catch. CF 1.0's limitation was fully described here.

With NETCF 2.0, we still don't have Application.ThreadException but, unlike the desktop scenario, we don't need it since the NETCF 2.0 AppDomain.UnhandledException catches *all* unhandled exceptions. Here is an example of its use:

static class EntryPoint {
[MTAThread]
static void Main() {
// Add Global Exception Handler
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(OnUnhandledException);

Application.Run(new Form1());
}

// In CF case only, ALL unhandled exceptions come here
private static void OnUnhandledException(Object sender,
UnhandledExceptionEventArgs e) {
Exception ex = e.ExceptionObject as Exception;
if (ex != null) {
// Can't imagine e.IsTerminating ever being false
// or e.ExceptionObject not being an Exception
SomeClass.SomeStaticHandlingMethod(ex, e.IsTerminating);
}
}
}


Note that I have never seen e.IsTerminating be false, in other words after your handler gets run the process exits. The last statement includes the case where you throw an exception in the handler; so, exceptions thrown in the global exception handling routine are swallowed (why would you throw in there in the first place is a valid question).

Next entry will serve as a holder of the VB equivalent code plus a blurb on try..catch around Application.Run. Go :-)

I stripped this article from the fine detail and instead just presented the result; if you have a deeper interest let me know and I'll send you how I arrived at the conclusions.

StackTrace

Sat, December 18, 2004, 02:56 AM under MobileAndEmbedded
If you are a desktop developer, imagine life without Exception.StackTrace. Has it sunk in yet? Good, your imagination has just taken you to what is reality for CF developers today (add to that CF's absence of GEH and you'll realise why it is the *compact* framework).

If you are a CF developer you feel my words no doubt... well feel no longer, because CF 2.0 (available now in a CTP release near you) gets Exception.StackTrace :-D

Before you ask, no the standalone StackTrace class is not available and neither is Environment.StackTrace but you can't win them all right?

As you'd expect, the built-in CF error dialog that comes up when an uncaught exception is thrown, now takes advantage of StackTrace to give us better info as to where the unhandled exception occurred.

Stopwatch

Thu, December 16, 2004, 01:03 PM under MobileAndEmbedded
A useful class in .NET 2.0 for measuring performance, but not only, is the System.Diagnostics.Stopwatch class. Once again this does not appear to be part of CF 2.0, so I set out to implement one for both CF 1.0 and desktop version today (.NET 1.1) and tomorrow (CF 2.0).

You can download the dll from here (so you get the BackgroundWorker as a bonus) or get the code at the end of this entry.

The interface is very simple:
1. Create an instance of a Stopwatch class.
2. Start it and stop it at will, or reset it back to zero.
3. At any moment in time, access one of its Elapsed properties (returning TimeSpan, milliseconds or ticks)
4. You can check if an instance is running

There are also a bunch of static (Shared in VB) calls you can make:
5. If you are lazy and want a new already started Stopwatch with one call, use the StartNew static method
6. If you just want to know the current number of ticks in the timer mechanism, call the static GetTimeStamp
7. The number of ticks per second is accessible via another static: Frequency

Cannot get much simpler, can it :-) In addition, on MSDN you can find: .NET Client Stopwatch Application Sample

My implementation uses the high resolution QueryPerformanceCounter/Frequency APIs. If they are not supported on your device, you will get an exception when creating a Stopwatch [note that the .NET 2.0 version copes with a fallback mechanism, I have not implemented that]. If you are the unfortunate owner of such a device then I suggest you use Environment.TickCount.

Download the DLL here
Download the VB code here
Download the C# code from OpenNETCF

Multifile assemblies in CF 2.0

Thu, December 9, 2004, 04:05 PM under MobileAndEmbedded
A question came up in the ng, and my reply included the statement "CF 1.0 does not support multi-module assemblies [...]". So I thought I'd check to see if that changed in CF2.0. The short answer is "yes, they are supported"! If you are on the CF team, please let me know why you are offering this feature. What was the driver for it? Anyway, read on to see an example of multifile assemblies in CF 2.0.

If you don't know about multi module/file assemblies, I suggest you search the web for definitions, as I am not going to describe the principles (the feature is available in the .NET full framework today). In a small nutshell, you compile code in modules (.netmodule extension and nothing to do with VB's module) that you can link to from an existing assembly. (Alternatively, using al.exe you create an assembly that holds the manifest only and references the real code in one or more netmodules).

So here is how to do it with CF 2.0

1. Create a ProgramMixed.cs file with this code in it
namespace MixedLanguages {
static class Program {
[System.STAThread]
static void Main() {
System.Windows.Forms.Application.Run(
new MixedLanguages.Form1());
}
}
}

2. Create a Form1Mixed.vb file with this code in it
Namespace MixedLanguages
Public Class Form1
Inherits System.Windows.Forms.Form

Public Sub New()
Me.Text = "Run from Csharp code"
Me.MinimizeBox = False
End Sub
End Class
End Namespace

3. In the command line type the following (assuming you have all the PATH variables set and you are pointing to the right directories):


vbc /netcf /noconfig /nostdlib /r:"E:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\CompactFramework\WindowsCE\mscorlib.dll","E:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\CompactFramework\WindowsCE\System.dll","E:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\CompactFramework\WindowsCE\System.Windows.Forms.dll" /t:module Form1Mixed.vb


You should get a Form1Mixed.netmodule file created (note that /sdkpath crashes with Beta 1).

4. Also type this:


csc /noconfig /nostdlib /r:"E:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\CompactFramework\WindowsCE\mscorlib.dll","E:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\CompactFramework\WindowsCE\System.dll","E:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\CompactFramework\WindowsCE\System.Windows.Forms.dll" /addmodule:Form1Mixed.netmodule ProgramMixed.cs


You should have a ProgramMixed.exe created.

In both successful command line compiles, the output looks something like this:

Microsoft (R) Visual Basic .NET Compiler version 8.0.40607.16
for Microsoft (R) .NET Framework version 2.0.40607.16
Copyright (C) Microsoft Corporation 1987-2003. All rights reserved.


5. You now have 2 files. Copy them to your device or the emulator and run the exe (in fact, since they are retargetable, you can run the exe on the PC as well). That's it!

So, apart from the ability to mix languages without having to create separate dlls, what is the advantage of multifile assemblies? I am not sure. Maybe the search you did earlier has given you the answer, in which case let me know. There are some benefits listed here (and an example).

I would be much more excited if we could actually statically link the netmodules into a single file. This becomes reality in VS2005 on the desktop, but only for C++.

UPDATE: Turns out we can merge the netmodule into a single exe file.

.NET CF MVP Chat

Thu, December 9, 2004, 11:28 AM under MobileAndEmbedded
I've blogged before about the SDP chat. Today it was the MVP's turn to host the monthly chat. These are not MSFT employees and therefore the format of the chat is more of a troubleshooting session; there isn't much opportunity of obtaining official info on future features, etc. As always the experts got a standing ovation in the end.

So, once more, update your calendars with the chat dates you are interested in or keep missing out!

BackgroundWorker for CF 1.0

Mon, December 6, 2004, 10:50 AM under MobileAndEmbedded
TIP: Download the class at the bottom of this post

.NET 2.0 makes threading easier by offering a BackgroundWorker class (not sure if CF 2.0 will have it, though). Read on to find out how to take advantage of it today in the CF 1.0 (also works on the desktop .NET 1.1).

The beauty (for someone not into documentation like me) of implementing a desktop class for the CF is that you don't need to document its usage (to an extent). There are already MSFT samples (and others) for the full Fx's class, so all you have to do is preserve the interface and behaviour.

So this is my summary of the BackgroundWorker story with hyperlinks to msdn.

In its simplest:
1a. Create an instance of the class (new BackgroundWorker())
2a. Hook up to its events (DoWork, RunWorkerCompleted)
3a. Tell it you want to do some background work (RunWorkerAsync)
4a. It raises the event. In your DoWorkEventHandler method do your background stuff (without touching GUI of course)
5a. When done, your RunWorkerCompletedEventHandler method will run on the GUI

Let's add value [Pass state in, cancel from job]:
3b. Optionally pass an object to the worker method (RunWorkerAsync, DoWorkEventArgs.Argument)
4b. Optionally decide in your background work to cancel (DoWorkEventArgs.Cancel=true)
5b. In your RunWorkerCompletedEventHandler method, check whether the operation was cancelled (RunWorkerCompletedEventArgs.Cancelled)

It gets better [Get a result back]:
4c. From your background work, optionally pass a result to the GUI when it's finished (DoWorkEventArgs.Result)
5c. Check for it (RunWorkerCompletedEventArgs.Result)

Wait, there is more! [Progress notification]
2b. Additionally hook up to a progress event (ProgressChanged) if you configure the object to allow it (.WorkerReportsProgress)
4d. From your worker method, let the object know the percentage (ReportProgress) optionally passing some state (ReportProgress)
6. In your ProgressChangedEventHandler method that runs on the GUI, check the percentage (ProgressChangedEventArgs.ProgressPercentage) and optionally the state given (ProgressChangedEventArgs.UserState)

Finally [Cancel from outside the job]
2c. Optionally Configure the object to allow cancellation (WorkerSupportsCancellation) other than just from the background worker method itself
4e. In your worker method check periodically if a cancel has been issued (CancellationPending) and if it has proceed as 4b
7. From any place in the code, ask the worker to cancel (CancelAsync)

If you have VS2005 just drag and drop it from the toolbox and start playing with it (on the desktop, not the CF). Browse its interface in object browser (it is under System.dll in the System.ComponentModel namespace)

Also read:
How to: Run an Operation in the Background
Walkthrough: Implementing a Form That Uses a Background Operation (Highly recommended)

Note that with my CF implementation you cannot drag the component on a form, but instead you have to manually create it from code (the assumption being you will do that from the GUI thread).

Download the DLL here (works on all platforms/versions)
Get the VB source here
Get the C# source at the next drop of the SDF

UPDATE: Also read this comprehensive BackgroundWorker sample

Satellite Assemblies

Wed, December 1, 2004, 12:48 PM under MobileAndEmbedded
So we looked at how you change the language in a Compact Framework scenario and how we can read the current locale. The most popular reason for which users change language, is to read the text of your UI in their own language (profound statement or what? :-)

The .NET way of doing that is using RESX files and resource dlls (a.k.a. satellite assemblies). The process is very similar to the desktop scenario, but the file formats are incompatible (and that will be the case for CF 2.0 too). There is a lot of info on using RESX files, so I won't go into any detail here. (In a nutshell, in the designer you can set the Localizable property of your forms to true and then change the strings once per language; this creates a RESX file per form per language and, on compilation, all RESX of a language are rolled into a resources dll. When deploying your app, place each .resources dll in its own folder under your app's directory, naming each directory as per the two-letter language code. At runtime, the CLR picks up automatically the system's locale and hence which resources dll to load and life is goodness).

Note that the SatelliteContractVersion attribute is supported at compile time but does not work at runtime so don't use it. Essentially you must deploy all your satellite dlls with your exe every time you roll the version (unless the only change is the revision in which case they are considered compatible as per the CF rules).

Also note that, if you need additional strings for translation (e.g. MessageBox strings), they have to reside in their own resx file (that you create manually and must include as an embedded resource). To retrieve these you need to explicitly use the ResourceManager (i.e. like this).

Finally, you may find the CFResgen tool useful. It allows for conversion between txt/resx/resources files (tip: save your txt file as utf-8).

So I leave you with my approach:
I do not use the RESX files created by the forms, and in fact I leave Form.Localizable to false. Instead, I maintain one text file of name/value pairs and whenever I need a string in my app I add it to the txt file. The implication is that I set the Text for all controls outside the InitializeComponent method (ctor or OnLoad as appropriate). I then run cfresgen on the text file to get a single RESX file, which is the one included in my project as a resource. I send it to the translators and they send me back a translated RESX file that I also add to my project; from those, the compiler spits out the satellite assemblies. Note that our translators use a localisation tool that works great with RESX files, but we had one who did not have access to the tool, so sending them the txt file and then performing the conversion to RESX on our end worked out great. The attraction to the aforementioned method is the simplicity of dealing with a single txt file from which everything else stems.

CultureInfo

Tue, November 30, 2004, 11:45 AM under MobileAndEmbedded
One of the FAQs on the CF newsgroup is regarding changing the Thread.CurrentThread.CurrentCulture. The answer is that it is not supported. Instead, the user must change the language on the device and restart your application for changes to take effect [Not restarting the application is possible by reloading ALL resources but the approach is dirty and is as good as restarting the app anyway, so there is no point going through the hassle to do it - trust me].

If your app is running in kiosk mode (or for whatever other reason you wish that the user changes the language through your UI), it is easy to set a dialog up for the said purpose. Just list the languages in a combobox associating with each comboxitem a LCID; when the user selects the language and confirms their selection, you have to change the system language via the SetUserDefaultLCID API (and restart your app). Some devices support MUI, so in those cases you also have to call the SetUserDefaultUILanguage API (and reset/restart the unit).

To finish the story on language change, on our platform I don't go through the APIs but instead apply the changes via the registry (the API is the way to go, but I am not doing that for our own historical reasons - not relevant here). In case it helps someone, these are the registry entries (shouldn't be too different to others):
-HKLM\nls\DefaultLCID
-HKLM\nls\overrides\LCID
-HKLM\SOFTWARE\Microsoft\International\LCID
-HKLM\MUI\SysLang
-HKCU\MUI\CurLang
As you'd expect, I set the LCID in each one of these DWORD values, flush the registry (RegFlushKey) and perform a soft reset (KernelIOControl\IOCTL_HAL_REBOOT).

After your app restarts you may want to know what the locale is. You may do this through CultureInfo.CurrentCultre (and CultureInfo.CurrentUICultre).

Note that sometimes you just need to perform some formatting based on a locale other than the system-wide one e.g. the French decimal point is comma "," and you may want to parse a string containing doubles that come from a network where dot "." is the decimal point. In those cases you have to use overloads of the framework's methods that can accept a CultureInfo (or any other IFormatProvider object) as a parameter, e.g. Double.Parse or DateTime.Parse

Next we look at resources in satellite assemblies.

QFE 4.2 - CF update

Mon, November 29, 2004, 12:52 PM under MobileAndEmbedded
This just appeared:
http://www.microsoft.com/downloads/details.aspx?familyid=e0e66c77-dee2-4aba-9623-a3bfff434b5c&displaylang=en

CF version number appears to be: 1.0.4292.0

Fixes made (from the readme):
This update addresses the following issues:
a.. Transitions between managed and native code may cause memory leaks on ARM platforms.
b.. A NullReferenceException may occur when a Web Method returns an empty array using the xsi:Nil attribute.
c.. Modifying the SoapClientMessage.ContentType property does not modify the Http requests ContentType header.
d.. Stack corruption may occur on SHx, MIPS and x86 platforms when local variables are created but never used.
e.. Invoking a multicase delegate from a catch handler may cause a MissingMethodException on SHx, MIPS and x86 platforms.
f.. Command line arguments containing double byte characters may get truncated to a single byte.
g.. An ObjectDisposedException may occur when a asynchronous web request is aborted before the response is received.
h.. Invoke on a disposed control may hang the application.
i.. An array containing one or more elements may be sent to the Web Service incorrectly.
j.. An application may hang when invoking a Web Method that uses multiple XmlElementAttributes on a single argument, member or property.
k.. Memory corruption may occur on devices that have the native security model enabled and both .NET CF V1 SP3.
l.. Deadlocks may occur when running under severe resource constraints.
m.. The issue of the Tool Bars loosing their image on Windows Mobile 2003 SE when removed from the form is addressed by this update.
n.. An ObjectDisposedException may occur when the server closes the socket connection.
o.. Setting the Minimum and Maximum properties of a progress bar may crash the application.
p.. An exception may occur when adding an image to an imagelist on an Hx4700 and Hx4705.
q.. Data misalignment may occur on decimal fields in MIPSIV devices.

mouse_event

Thu, November 25, 2004, 02:46 AM under MobileAndEmbedded
Assuming you read ToolBarButton BUG and ContextMenu.Show...

Let's look at the real solution. The title gives it away really: PInvoke mouse_event. The API is pretty straightforward, but you must RTFM and in particular the bit where it says "...dx and dy contain normalized absolute coordinates between 0 and 65,535".

The DllImport is very easy (all parameters are Int32) and if you STFNG you'll find this. So here is a short sample for performing mouse clicks from code, using mouse_event. Create a winforms smart device project with a Form, 2 buttons and a MainMenu. The code should be self-explanatory and easily translatable to C#.
		

' Wrapper for mouse_event, performing click action on coordinates given
Public Shared Sub PerformMouseClick(ByVal aX As Int32, ByVal aY As Int32, ByVal aForm As Control)
Dim p As Point = aForm.PointToScreen(New Point(aX, aY))
Dim m1 As Int32 = (65535 \ Screen.PrimaryScreen.Bounds.Width)
Dim m2 As Int32 = (65535 \ Screen.PrimaryScreen.Bounds.Height)
Dim x As Int32 = m1 * p.X
Dim y As Int32 = m2 * p.Y
Win32Api.mouse_event(2 Or &H8000, x, y, 0, 0)
Win32Api.mouse_event(4 Or &H8000, x, y, 0, 0)
End Sub

' Button1 event handler. Simulates button click OR opening a main menu. Same principle applies for ToolBarButton
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PerformMouseClick(Button2.Left + 1, Button2.Top + 1, Me) 'performs click on other button
'PerformMouseClick(5, 5, Me) 'opens main menu on full screen WinCE app
'PerformMouseClick(Me.Left + 5, Me.Height + 5, Me) 'opens main menu on PPC app
End Sub

Finishing off, here are a few tips for playing with mouse coordinates and the above:
1. Use the static method Control.MousePosition to determine where the mouse pointer is (or where you have sent it). E.g. run a timer and when it ticks update a listview with the coordinates.
2. Even better than 1, but only applicable if you are using Platform Builder, add the cursor to your image [it is under Shell_and_UI -> UI -> Mouse]. Now you can see where you are sending the mouse and where you exactly last tapped :-)
3. When passing the coordinates to mouse_event be sure to use the instance method Control.PointToScreen as in the example given above (otherwise e.g. you'll be aiming for the toolbar and hitting the title bar)

Let me know if it (or anything else on this blog) doesn't work for you.

STFNG

Thu, November 25, 2004, 02:37 AM under MobileAndEmbedded
Regular readers of this blog (but also anybody that has been developing with the CF for more than a week), know that there is a one-stop shop for all your CF answers, and it is of course the CF newsgroup. Anybody hanging out there for more than a month will know that the same questions get asked over and over and over and over again (trust me, there are not enough "overs" in this sentence).

Sometimes I wish I could just ask people to STFNGTM

Search The Freaking NewsGroup

The FAQ is also a good place to start.

ContextMenu.Show

Wed, November 24, 2004, 11:07 AM under MobileAndEmbedded
Here we will look at a solution for the bug reported previously. In a nutshell, we have a situation where we would like a menu to automatically appear, but instead the onus is passed onto our code. The solution is more interesting than the problem, and in fact in this case applies to other problems as well, so without further ado...

The initial (obvious) solution is to manually show a ContextMenu, which is easy given the Show method. This takes two arguments (the control and position) and is easy to call. The approach does indeed solve the problem and can be adequate for some scenarios, but is not without its problems. They all stem from the fact that when putting up a ContextMenu you are blocking: "This method does not return until the menu is dismissed".

Consider for example what happens if you are performing asynchronous operations (e.g. network requests) that are Control.Invoked to the GUI (e.g. populate a listview) and suddenly the user taps the ToolBarButton to get a menu and you use ContextMenu_Show: all those threads/messages are blocked in a queue only to be released (all at once!) when the menu is dismissed - I don't fancy that myself.

As a workaround to the aforementioned condition (and also a standalone requirement for some scenarios), you will want to stop other activities before showing the ContextMenu, and restarting them after it is dismissed. But wait, how do you know that they must be restarted when it is dismissed? The conditions/scenarios are different if it was dismissed due to a menu item being clicked (which as a result may have now navigated the user to different forms, for example) and different if the user tapped somewhere else, hence dismissing the ContextMenu. A solution to the new problem is to use a global flag tracking if a menu item was clicked or if the ContextMenu.Show call returned without a menu being clicked (and based on the state of the flag make the decision). As you can see, it gets messy.

Other differences compared to a plain menu include the following scenario: Form A shows form B; form B shows a ContextMenu; Form A decides (e.g. based on a Forms.Timer event) to close form B. The result is you are now looking at Form A while the ContextMenu from form B is still up! The workaround to this is to place a this.Capture = false in the Closing event of the Form.

Talking about the problems of manually showing ContextMenus, it is worth capturing (for the record) a known issue with showing them from the AfterSelect event of a TreeView. Rather than describe it here, I point you to the ng archives here and here [my posts there also include a workaround].

From my previous four paragraphs I hope you can see that ContextMenu.Show is useful and can solve some simple scenarios, but is definitelly not a one-to-one replacement for the user tapping on the arrow part of a ToolBarButton and having the menu auto-displayed for them (where none of the problems above apply).

Next time we look at a much nicer workaround to the original problem.

ToolBarButton BUG

Tue, November 23, 2004, 07:38 PM under MobileAndEmbedded
This blog entry serves as a description of what I call a bug (others might call it a limitation by design). The post after this will describe the workaround solution.

We are all familiar with the Toolbar and ToolBarButtons, right? There is different behaviour in this area of the OS, depending on the platform. On CE they appear at the top, whereas on PPCs they are at the bottom of the screen (no problem so far, but there is more). ToolBarButtons in .NET have a Style property, which by default is ToolBarButtonStyle.PushButton and hence we get normal buttons that we can click on (which we usually assign an icon to). When setting the Style property to DropDownButton, the ToolBarButton becomes “split” and effectively has two parts: the "icon" part and the "arrow" part, the implication being that you will also assign a ContextMenu to the DropDownMenu property.

So, assuming we've setup a toolbar button as described, what does it look like and what does it behave like on the PPC versus vanilla-CE device? (For the following discussion, if you don't have a device handy and wish to check my observations, you can use the emulators. The CE one with VS.NET 2003 is based on 4.1, the bug is only present on 4.2 - trust me!)

Appearance
- On PPCs, the line separating the arrow and icon parts is always visible. So the user (with their handy stylus) gets a hint that, if they click on the arrow part, something different will happen compared to if they tap on the icon part of the toolbar button.
- On vanilla windows CE 4.1/4.2 devices there is no line separating the two, ever! [point A].

Windows Behaviour (native)
- I could not find a native application running on a PPC that uses ToolBarButtons with an arrow (if you let me know of one I'll update this entry - it is irrelevant to my overall point)
- On WinCE 4.1/4.2 we can launch Windows Explorer. Notice that there is a ToolBarButton with an arrow ("Views" - just like on the desktop). The punch line is that tapping anywhere on that button (arrow part OR icon part) will show a menu; there is no separate click action [point B].

.NET Behaviour (managed)
- A managed app on PPC visually separates the icon part from the arrow part, as we established earlier; behaviourally they are also separate, i.e. tapping on the arrow part shows a menu, whereas tapping on the icon part performs a click action. In code you can trap the click action but not the arrow_tap (it will automatically put a menu up).
- A managed app on CE 4.2 behaves the same! [Hint: It shouldn't] On CE 4.1 the behaviour is correct i.e. different to the PPC (and same as the native Windows Explorer)

Conclusion
This is an area where the CF does not conform to the platform it runs on. My claim is that a CF app should not behave the same on PPC and CE devices in this area.
- The main reason it shouldn't is that, as per point A above, there is no visual distinction between the two areas (either fix the bug of the OS or fix the bug of the CF - preferably the latter).
- The second reason it shouldn't is because typically on non-PPC CE devices there is no stylus or mouse, so asking a user to tap within 9 pixels using their finger is a bit much.
- The third reason it shouldn't is because, as per point B above, even native apps don't treat the button as having two behaviours.
- Finally, why break the correct behaviour of CE 4.1?

Next time we'll explore a workaround.

Debug.WriteLine

Wed, November 17, 2004, 09:58 AM under MobileAndEmbedded
One of the first complaints .NET desktop developers have when targeting the CF v1.0 for the first time is "Debug.WriteLine doesn't work".

The fact is that with Smart Device projects the debug output does not come back to Visual Studio; rather it goes to the console on the target device. It is true that Debug/Console WriteLine statements do not appear when debugging on PocketPC devices/emulators, but this is not a CF issue; it is rather due to a lack of console on the PPC platform. Debugging a CF app on the CE emulator or a CE-based device results in the display of a console window on the target with the debug statements. Note that even on a CE device, if you build it without the console (cmd.exe) you will get no debug output (I should know, since I have accidentally run into that scenario when we ported from CE 4.1 to 4.2, but I digress).

So what can you do about it? There are a number of options and I will link to them in this entry, ready for the next time someone asks :-)

Add a console to the target, e.g. this one

Redirect the output to a file, e.g. like this

Send the output back to the dev machine, e.g. like that or that

Of course you could switch away from using System.Diagnostics directly and write your own logging framework. As you'd expect, this has been done before and there are a number of 3rd-party solutions, some of which may be too simple and others too complex for your project's liking. So here are some options:

MSFT offer the Enterprise Instrumentation Framework, but I doubt it supports the CF.

I have met references to log4net a few times, but I don't think it supports the CF it is under the Apache license.

Over at the useful openetcf there is a logging system, but I must admit not having played with it, and I don't know if it works on the desktop

For my own projects (CF and full Fx), I have been using a class I wrote years ago. Features include:
1. Just one file to include in your project. Only one class with static methods.
2. Use of the standard Debug class internally, so the output goes to VS console (desktop) or device's console (CF)
3. CSV formatted output (inserting additional info such as timestamp etc.)
4. Redirection of output to a HyperTerminal on the desktop, when running a debug OS on your CE target
5. Support of 3 severity levels (Info, Warning/Assert and Error). Auto detectable based on project configuration (e.g. DEBUG, TRACE)
6. Further configuration available via TraceSwitch (both platforms) and optionally via config file (desktop only)
7. Writing to a file (on both platforms, path and name computed internally also take into account COM Interop clients)
8. Rolling of the filename, thus preserving debug info between different runs of the application

Feel free to play with it.

If you are interested in the subject of tracing, you will love a new feature in Whidbey: Tracepoints. I was going to write about it, but many others have done so already [1,2,3]

UPDATE:
Visual Studio 2005 (and .NET Compact Framework v2.0) support Debug.WriteLine :-D

CF article on MSDN mag

Tue, November 16, 2004, 09:08 AM under MobileAndEmbedded
The December issue of the MSDN Magazine comes with a nice CF article, go read it:
Optimize Your Pocket PC Development with the .NET Compact Framework

Here is its outline:
-Essential Goodies and Our Test Bench
-Bad, Wicked Dialogs
-Chilling Out the Context Menu
-Designable Custom Controls
-Optimization
-Getting Resourceful
-Load Only What You Need; Chuck What You Don't
-Putting It All Together—the TabControlEx Class
-Adding Toolbar Buttons to TabControlEx
-Conclusion

AssemblyFileVersion on CF

Mon, November 15, 2004, 03:58 AM under MobileAndEmbedded
The Compact Framework does not support the AssemblyFileVersion attribute. Instead, whatever .NET version you give to your assembly (via AssemblyVersion) will also be its Win32 file version. Neil shows you how to give an alternate Win32 file version to your CF assemblies without resorting to command line compile. Go read it and let me know when you are back!

OK, so although I am an advocate of everybody understanding both languages, I have done the VB version for you here. Note that this will only work if you have not chosen to use the Root namespace in your VB project properties (which as I've said before is a bad habit anyway).

Namespace System.Reflection
    <AttributeUsage(AttributeTargets.Assembly, AllowMultiple:=False)> _
    Public Class AssemblyFileVersionAttribute
        Inherits Attribute
 
        Private mVersion As String
        Public ReadOnly Property Version() As String
            Get
                Return mVersion
            End Get
        End Property
        Sub New(ByVal aVersion As String)
            If aVersion Is Nothing Then
                Throw New ArgumentNullException("version")
            End If
            mVersion = aVersion
        End Sub
    End Class
End Namespace


While on the subject of versions, it is worth pointing out that the Product Version of your file can be set with the AssemblyInformationalVersion.

Smart Device Programming Chat

Thu, November 11, 2004, 12:58 PM under MobileAndEmbedded
Earlier today the Compact Framework chat of the month took place. For those of you that don't know about them, check out the schedule for online chats and search the archive of previous transcripts here. So these are opportunities to ask MSFTies and/or MVPs questions regarding a particular technology (in this case the CF).

Some times we may get interesting news out of them as well but, as always, nothing communicated in a chat is a commitment (more like "this is what we believe now"). Example: In a previous chat, I was told that the TreeView in CF 2.0 will support the NodeMouseClick event
"Q: Will CF 2.0 support TreeView.NodeMouseClick (since AfterSelect does not fire when selecting an already selected tree node)?
A: Yes, the NodeMouseClick event will be available in CF 2.0."

Today I was told it is not in CF 2.0 "for reasons of ROM size". Oh well, still if we all go and vote for it, I will feel better.

Other interesting points from today's chat:

Service Pack 3 for CF 1.0 will be out within a month (good news for me, as my next IQView release depends on a SP3 bug fix)

There will be no deterministic GC in CF 2.0 - it is on the consideration list for v3
Same goes for Code Access Security (not in CF2 but planned for future release).

It was confirmed that COM Interop in CF 2.0 is limited to managed clients activating unmanaged COM types. Unmanaged COM code can call managed code in terms of events/callbacks only.

That's all I recall. For the full story, keep an eye out for when the transcript becomes available.

More Windows Mobile 2005 Details Emerge

Wed, November 3, 2004, 12:29 PM under MobileAndEmbedded
If you are PocketPC enthusiast you might be interested in Windows Mobile 2005 (codename magneto).

There are some details about it here [found the link via this (Greek) site]

HideSelection

Wed, October 27, 2004, 10:40 AM under MobileAndEmbedded
"[HideSelection] controls whether the current sub-selection is visibly hidden when the control loses focus. Most controls highlight the currently selected contained item and make its background color the selection color. If this property were set to True, then the background color would revert to normal when the control loses focus."

Some Windows Forms controls of the .NET Framework offer the HideSelection property (e.g. TextBox, ListView and TreeView). So, if for example you have a form with the 3 aforementioned controls on it and you clicked on each one of them, you would be able to see which TreeNode is selected, which ListViewItem is selected and what text is selected without further interaction (presuming you set their HideSelection property to false, which is not the default by the way). So the highlighting is preserved after the control loses focus.

Unfortunately, the Compact Framework does not offer the HideSelection property. Furthermore, the default is not consistent: it is true for TreeView but false for ListView!

You would have thought that with CF 2.0 they would offer us the HideSelection property or change the defaults to be consistent, but my suggestion was postponed.

So this entry serves as a container for the code that I use to simulate the HideSelection property (based on SetWindowLong). The sample should work for CF 2.0 as is and if you wish you can access the TreeView handle without resorting to any tricks (Control.Handle is available in CF 2.0). Place the code on a form that also contains a TreeView. It simulates TreeView.HideSelection = false.

' VB
Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
MyBase.OnGotFocus(e)
Static doneOnce As Boolean
If Not TreeView1 Is Nothing Then
TreeView1.Focus()
If doneOnce = False Then
doneOnce = True
Dim hWnd As IntPtr = Win32Api.GetFocus()
Dim lS As Int32 = Win32Api.GetWindowLong(hWnd, -16)
lS = lS Or &H20
Win32Api.SetWindowLong(hWnd, -16, lS)
End If
End If
End Sub

// C#
private bool doneOnce;
protected override void OnGotFocus(System.EventArgs e) {
base.OnGotFocus(e);
if (TreeView1 != null){
TreeView1.Focus();
if (doneOnce == false){
doneOnce = true;
IntPtr hWnd= Win32Api.GetFocus();
Int32 lS = Win32Api.GetWindowLong(hWnd, -16);
lS = lS | 0x20;
Win32Api.SetWindowLong(hWnd, -16, lS);
}
}
}

Share Code (#if FULL_FRAME)

Fri, September 17, 2004, 11:00 AM under MobileAndEmbedded
When talking about .NET code running on both CE platforms (against CF) and the PC (full FX), usually what follows is a discussion on sharing the same binaries. This is possible and we looked at retargetable previously. My prefered approach is to share code instead. Two projects, two outputs, same set of code files. Before talking about the advantages of this approach, let's briefly summarise the process.

Basically we create two projects, one for the full FX and one for the CF. In the full FX project we add a conditional compilation constant; I name it FULL_FRAME, but obviously it can be whatever you fancy. Then we share the same code files between the two projects. This can be done by creating the file in one project and then adding a link to it from the other or even better, place the projects in the same directory and include the code files in both projects. Either way you are working on the same file, not a copy. I rename the output of the CF assembly by appending a CF to it before the extension, but obviously the namespaces etc inside are the same. Build both projects and you get two outputs (make sure one does not overwrite the other). Now, whenever you need to add some desktop-only functionality, you just surround the code with FULL_FRAME e.g.

using System.Threading;


Thread t = new Thread(new ThreadStart(this.SomeMethod));
#if FULL_FRAME
t.Name = "CF2.0 supports both of these";
t.IsBackground = true;
#endif
t.Start();

If any of the above is unclear, drop me a comment (it is also described here). I maintain a fairly large set of dlls between the two platforms (the desktop side uses remoting and COM interop which are non-existent on the CF) and it works great.

The advantages of this approach are obvious. You can enhance the desktop assembly with full FX specific features and vice-versa for the CF assembly. In fact, even when there is no business case for it, I do this for every CF dll I write. By running your CF code on the desktop you can debug using features not available when debugging on the device/emulator, such as "Set Next Statement" and full tracing support; there are a whole bunch of profilers (none for CF) you can use, e.g. for examining allocation patterns of your code; modelling tools that don't work with CF projects can be used to design or reverse engineer your code; same goes for unit testing tools and so on and so forth: I hope you get the point. Through simple, short tasks you can get great benefits and it amazes me how very few devs use this technique.

When discussing retargetable, I offered my opinion on why it didn't make sense for EXEs. With the shared code approach I create an EXE project per platform, but no code sharing takes place; they just reference the corresponding dlls. This is one of the reasons I make my EXE assemblies very thin, typically containing only Forms. The difficulty is that the forms designer is very different between the two project types (in terms of auto generated code). Trying to share the form code would effectively mean not using the designer at all. However, with VS2005 and partial classes the story might get better. I'll be looking at having different designer code files while sharing the partial form class which contains the event handlers and other methods. You can imagine how the form can be designed (and properties of its controls set) in such a way as to fit in both platforms, while the real logic is the same. Too excited about this now, I must go play with it!

Retargetable (=256)

Thu, September 16, 2004, 03:07 PM under MobileAndEmbedded
One of the FAQs on the CF newsgroup is about running assemblies on both desktop and CE device. The answer is that on a CE device you cannot run assemblies built against the desktop/full framework. The reverse is possible, due to the System.Reflection.AssemblyNameFlags enumeration and specifically its Retargetable value. Basically, almost all of the CF assemblies are retargetable to the desktop v1.1 assemblies, which means that your CF app will run on the desktop against the full framework. There is a caveat, which is obvious once you understand the previous sentence:

* You must only use functionality that is common on both platforms *

At first this may sound superfluous, given that the CF is a subset of the full framework, but a closer look reveals functionality specific to the CF in the Microsoft.WindowsCE namespace (such as MessageWindow and InputPanel), the infrared classes and of course the SQL stuff is different. In addition, no real CF 1.0 application survives without pinvoking, so you'll have to detect what platform you are on (System.Environment.OSVersion.Platform) in order to call the right dllimport (i.e. not pointing to coredll.dll). So, break these rules and look forward to TypeLoadExceptions and the like; follow them and you are good to go...for class libraries projects (dlls).

Do expect to encounter differences in functionality. On the desktop your app is running against a different implementation of the .NET library. Although interface-compatible and in most cases functionality compatible, there are differences due to bugs or design decisions based on platform applicability.

For GUI apps (exes), I don't think there is much point in attempting the above. Technically it will work (just run your exe from the build folder) and it also makes a nice demo for your boss, but how will a WinForms app look good on two platforms that are so different to each other? The difference in screen size should put the argument to rest but, in addition, the user input is typically very different too (keyboard vs soft input panel, mouse vs stylus), not to mention non-resizable windows etc.

It is worth mentioning that VS2005 with CF 2.0 makes this approach even easier. All the same issues apply, but there is help for debugging this scenario. When you choose Debug->Run, you are presented with a Deploy window that includes a bunch of emulators (so far the same as VS2003) but also includes the 'My Computer' option! Choosing this actually runs your app on the desktop, providing you with the same experience you'd have if it were a normal Windows app.

To sum it up, my attitude towards the "retargetable" approach is not to use it. I prefer the alternative of sharing the same code base between desktop and CF apps and I use that successfully everyday. More on that approach next time.

IPC with CF on CE part 2

Sun, September 12, 2004, 05:16 PM under MobileAndEmbedded
Continuing from previous entry on IPC options with Compact Framework there are only two left - they are very similar.

7. Named Events + registry
8. Directly Share memory

7. For simple data sharing, it is easy for an app to write data to predefined regisrty entries and signal a named event; at that point the other side can read from the registry. It looks something like this:

// SERVER PROCESS
//write data
private void cmdWrite_Click(object sender, System.EventArgs e) {
IntPtr hWnd = Win32Api.CreateEvent(IntPtr.Zero, true,
false, "YOUR_NAME_HERE");

// TODO write to reg
//e.g. with opennetcf Registry class

Win32Api.SetEvent(hWnd);
System.Threading.Thread.Sleep(500);
Win32Api.CloseHandle(hWnd);
}

// CLIENT PROCESS
private System.Threading.Thread mMonitorThread;
private bool mStayAlive;
private IntPtr mMonitorHwnd;

//read data
private void cmdRead_Click(object sender, System.EventArgs e) {
mStayAlive = true;

mMonitorHwnd = Win32Api.CreateEvent(IntPtr.Zero, true,
false, "YOUR_NAME_HERE");

mMonitorThread = new System.Threading.Thread(
new System.Threading.ThreadStart(
this.MonitorOtherProc));

mMonitorThread.Start();
}

// on background thread so make sure we don't
// touch GUI controls from here
private void MonitorOtherProc(){
while (mStayAlive){
Win32Api.WaitForSingleObject(mMonitorHwnd, -1);
if (mStayAlive == false) return;

MessageBox.Show("Got data "+
DateTime.Now.ToString(), "TODO read from reg");
// TODO read data from reg

Win32Api.ResetEvent(mMonitorHwnd);
}
}

// must call this before closing app - e.g. from Form_Closing
public void Shutdown(){
if (mMonitorThread == null) return;
mStayAlive = false;
Win32Api.SetEvent( mMonitorHwnd);
System.Threading.Thread.Sleep(500);
Win32Api.CloseHandle( mMonitorHwnd);
mMonitorThread = null;
}


8. Directly sharing memory is not advisable but we can do it. The logic is identical to case 7 with named events but instead of writing/reading from registry, we access memory directly. It looks something like this:


// BOTH CLIENT & SERVER PROCESS NEED THESE

// Returns pointer to shared memory
private IntPtr ObtainHandleToSharedMemory(){
const uint PHYS_ADDR =0x80230000;//Make sure this is not used
on your platform
const int MEM_SIZE = 10;

IntPtr hwnd =
Win32Api.VirtualAlloc(0, MEM_SIZE, Win32Api.MEM_RESERVE,
Win32Api.PAGE_READWRITE|Win32Api.PAGE_NOCACHE);
if (hwnd.ToInt32() != 0){
if (Win32Api.VirtualCopy(hwnd, PHYS_ADDR, MEM_SIZE,
(Win32Api.PAGE_READWRITE|Win32Api.PAGE_NOCACHE))
== true){
return hwnd;
}
}
MessageBox.Show(
Marshal.GetLastWin32Error().ToString(),"Failed");
return IntPtr.Zero;
}

// Define common structure/class in both client and server e.g.
private class SharedMemory{
public byte b1;
public byte b2;
public char c;
public bool flag;
public int i;

public SharedMemory(bool aFlag){
flag=aFlag;
if (aFlag){
b1=1;b2=2;c='!';i=3;
}else{
b1=0;b2=0;c=' ';i=0;
}
}

public override string ToString() {
return "b1=" + b1.ToString() + ", b2="+b2.ToString()
+ ", c=" + c + ", i=" + i.ToString();
}
}

// CLIENT
// As in previous example but instead of reading the registry
// read the following in MonitorOtherProc
IntPtr memHwnd=ObtainHandleToSharedMemory();
if (memHwnd.ToInt32() !=0 ){
SharedMemory sm=new SharedMemory(false);
Marshal.PtrToStructure(memHwnd,sm);
MessageBox.Show(sm.ToString(),sm.flag.ToString());
}

// SERVER
// As in previous example but instead of writing to registry
// do the following in cmdWrite_Click
IntPtr memHwnd=ObtainHandleToSharedMemory();
if (memHwnd.ToInt32() !=0 ){
SharedMemory sm=new SharedMemory(true);
Marshal.StructureToPtr(sm,memHwnd,false);
}


IPC with CF on CE part 1

Sun, September 12, 2004, 05:13 PM under MobileAndEmbedded
With no remoting in the Compact Framework or named pipes on Windows CE there are still other ways to achieve Inter-process communication. Here is a list (feel free to tell me if I have missed any):

1. Sockets
2. Memory Mapped Files
3. Windows Messages
4. Point to Point Message Queues
5. MSMQ
6 Out-of-proc COM
7. Named Events + registry
8. Directly Share memory

1. Sockets are accessible to .NET apps via the System.Net.Sockets namespace. You could use a TcpListener (on 127.0.0.1 and some port you fancy) and a TcpClient or even get down to the Socket class which the other two aggregate. The msdn links given are good and as always search the web and newsgroup.

2. CF code for memory mapped files can be found here and an example of their use here

3. Passing windows messages between apps requires a windows handle of course. CF has the Microsoft.WindowsCE.Forms namespace not available on the desktop that includes the MessageWindow class. [This class was necessary to overcome the CF's limitation of not being able to pass delegates to pinvoke and hence achieve windows callbacks - this limitation is no longer in CF 2.0]. Learn about the MessageWindow here, here, here and here.

4. Point-to-Point Message Queues with the .NET Compact Framework

5. Pinvoking MSMQ is not easy (apparently, I haven't tried it myself) and I am aware of no sample code for that. CF 2.0 will support it via the System.Messaging namespace. For further details and a bunch of links on this subject check out these blog entries here.

6. COM interop is not supported in CF. A commercial offer is available. CF 2.0 will have some support for COM Interop but I don't know if out-of-proc servers will be supported. If you know drop me a note.

This is getting long enough already so we look at options 7 and 8 next time.

Global Exception Handling (.NET CF v1.0) - PART II

Sun, August 15, 2004, 11:19 AM under MobileAndEmbedded
Following from previous entry. If you are working with the Compact Framework 1.0, you should know that exceptions on background threads do result in the unhandled exception dialog appearing on screen. Also on the CF there are no registry entries to configure.

If you wish to add global exception handling to CF apps, you are out of luck. There is no support for Application.ThreadException or AppDomain.UnhandledException. You might think that using a try..catch around the entry point would work, however that is a bad idea. There are three scenarios when you do that:
1. Exceptions on the main GUI thread
2. Exceptions on background threads
3. Exception occurs in the GUI thread as a result of a Control.Invoke from a background thread (which you must do to update GUI areas)

The first scenario is OK - the exceptions are caught and your catch code will run. Your catch code will not run for the second case; in fact the built-in dialog will appear.

The third case is the worst, and I classify this as a bug: in this scenario your app will freeze/lock (and of course your catch code after Application.Run will not run).

So, no centralised global error handling on the CF.

Next time we'll look at how things change with VS2005 and .NET v2.0

My CF application and the platform it targets

Tue, August 10, 2004, 03:29 PM under MobileAndEmbedded
I work for a Building Management Systems (BMS) manufacturing company. Our main products are intelligent building controls. In January we replaced our old network display panel with a new hardware platform running Windows CE 4.2. The product's name is IQView.

Our hardware is based on an XScale PXA255 processor 200 MHz with 32 MB RAM. There is no stylus/keyboard/mouse, so user interaction is via 1/4VGA color touchscreen using a finger :-) Connectivity includes rs232, Ethernet and our own proprietary current loop. The unit is always connected to one of the previous options. It can be panel mounted or fixed to the wall (either way this is not a mobile device). In summary, it also has an SD card slot, LED, buzzer and relay output.

IQView allows for discovery of controllers, navigation of modules within them and adjustment of parameters, graphing, alarm reception etc. The application itself is written by myself using .NET CF. This is effectively (not literally) the only process running on the system and the only GUI that the end user interacts with - there are no OS components (control panel applets, taskbar, menus etc) ever visible. It runs 24x7 (assuming none of my bugs creep up :-).

If you want to know more about our choice of CE over other operating systems, our choice of the CF over eVC or want to see an image of the product, then you may find this article [pdf , html] useful. It appeared in EmbeddedSystemsEurope in April and includes quotes from our technology and business managers - us devs never get air time like that :-[

Other references to IQView on the web are
here (Swedish)
here (Finnish)
here (French)
here (German)
here, here, here (English)

Performance Statistics for .NETcf apps in CF 2.0

Sun, August 8, 2004, 05:39 AM under MobileAndEmbedded

By creating on the device a registry key and editing a value under it one can have a file automatically created containing statistics for a .NET CF 1.0 application. For more info on this go here (the counters are also described here amongst other performance advise).

In CF 2.0 (that comes with VS2005 Beta 1) there are more statistics added. For a list of the 30 previous counters, which are still with us, I refer you to the two links already provided. Here is the list of the 23 new counters only (can broadly be grouped as Threading, GC, COM):

UPDATE: The list below has changed. See here

Number of Uncontested Monitor.Enter Calls
Number of Contested Monitor.Enter Calls
Number of recursive Monitor.Enter Calls
Number of threads in thread pool
Number of pending timers
Timer latency

Number of objects in block move
GC Number Of Mark Stack Overflows
GC Number Of PInvoke Args Encountered
GC Number Of Eval Stack Pointer Lookups
GC Number Of Object Pools Created
GC Number Of Pinned Objects
GC Number Of ByRef Types Encountered
GC Number Of Pinned ObjRefs
GC Number Of Items Pinned At JIT's Request
GC Number Of Normal ObjRefs
GC Number Of Objects Moved by Compactor
GC Number Of Objects Not Moved by Compactor

Number of Runtime Callable Wrappers
Total number of Runtime Callable Wrappers
Number of generated Com wrapper classes used by the system
Number of Com Methods
Number of Com Calls


Threads and ThreadPriority with the .NET Compact Framework

Thu, August 5, 2004, 12:00 AM under MobileAndEmbedded
There are many who believe that the ThreadPriority property is not available on the .NET CF (some articles, books and MS documentation got this wrong in the past). The fact is that the property is available (5 priorities like the desktop version - these map to 249-253 in Windows CE terms). However I believe it is a bad idea to change the priority of managed threads.

For every CF application there are 3+1 threads [Quote from MSFT reply to my question in the ng] :
#1 The main application thread.
#2 is used to control various period timers and timeouts that can be scheduled by the system or applications.
#3 is used to track changes to the active TCP/IP interfaces (simulating the media sense behavior that is present on Windows XP but not Windows CE).
#4 [...] the thread that is used to run object Finalizers. It is created when the first finalizable object is garbage collected.

[Note that the 2nd thread is created only when needed in the CF 2.0 Beta 1]

Apart from the first one you cannot change the priority of the threads above (they are all at 251). So if you change the priority of other threads in your app how will they play nicely with the above four?

When a NETCF garbage collection occurs there isn't a special thread that performs the collection rather it is whatever thread happens to be running when the need for a collection occurs (do not confuse the GC thread with the finalizer thread). What will the results be if that happened to be one of your own threads whose priority you lowered?

Finally, note that the ThreadPool in the CF 1.0 does not have a limit of 25 threads like the desktop framework does; instead it is 256. [CF 2.0's ThreadPool is broken in the Beta so cannot comment on that but is fixed for the next CTP. Apparently CF 2.0 will bring parity with the desktop with a limit of 25. Let's hope that will be configurable]

So if you are going to be creating threads and changing their priority you must first be sure you understand the above and cater for them in your design. I have personally elected to keep all threads at their default normal priority in my CF apps and have only had unexpected results when I experimentally deviated from that policy.