Archive for January, 2008

Aspect Ratio Picture Box control

Tuesday, January 29th, 2008

Screenshot of sample application showing the use of an AspectRatioPictureBox controlOne feature missing from the PictureBox control within the .NET Compact Framework is the Zoom SizeMode. This mode makes the image contained within the PictureBox as large as possible while still maintaining its original aspect ratio. Luckily this feature is easy to implement as a custom control.

Scaling an Image

The ratio of a picture’s width to height is known as its aspect ratio. An image with an aspect ratio greater than 1 means that it is wider than it is high (landscape image). While an image with an aspect ratio of less than one is taller than it is wide (portrait image). If the aspect ratio is exactly 1 the image is square.

By comparing the aspect ratio of an image against the aspect ratio of our control we can determine if the best axis to stretch the image (in order to maximise its size) is vertically or horizontally. Once we have determined the maximum width or height of our scaled image we can then utilise the aspect ratio to calculate the other dimension in order to keep the same aspect ratio.

Creating a custom control

There are two main types of custom controls within a System.Windows.Forms based application, those that derive from the Control base class and those that derive from the UserControl base class. For this kind of custom control, deriving from System.Windows.Forms.Control is the best approach since we are after a fairly light weight control.

To make a custom control we simply need to declare a class which derives from Control:

using System.Windows.Forms;
 
public class AspectRatioPictureBox : Control
{
}

The code sample above is a complete custom control. Once it is compiled you will be able to place an AspectRatioPictureBox control onto a form, in the same way you would any other control such as a Button or Label.

The control however is quite boring, being a completely white rectangle making it indistinguishable from the form it is placed upon. Before we cover how to paint more attractive contents, we need a way for the user to specify the image they would like to display. The easiest way to do this is to implement a public property by adding the following to our class definition:

private Bitmap photo;
 
public Bitmap Image
{
   get { return photo; }
   set
   {
     photo = value;
 
     // Redraw the contents of the control
     Invalidate();
   }
}

Any public property exposed by our control will be accessible via the Properties window within the Forms Designer when the user utilises our control.

Notice the call to the Control.Invalidate method within the Image property setter? This is important, as this is the call which notifies the operating system that our control has changed state and needs to be redrawn. If the control is not invalidated, the OS will not attempt to redraw it and the user would not be able to see the new image that has just been provided. In general any property which affects the onscreen presentation of a custom control should invalidate it.

Now that we have a way to specify the bitmap we want to display, we can finally implement the code that will paint the contents of the control. We do this by overriding the OnPaint method as follows:

protected override void OnPaint(PaintEventArgs e)
{
  if (photo != null)
  {
    float controlAspect = (float)ClientSize.Width / (float)ClientSize.Height;
    float photoAspect = (float)photo.Width / (float)photo.Height;
 
    if (photoAspect < controlAspect)
    {
      // Stretch the height of the photo to match
      // the height of the control
      ....
    }
    else
    {
      // Stretch the width of the photo to match
      // the width of the control
      ....
    }
  }
}

The framework will call the OnPaint method each time the OS needs the control’s contents to be repainted onto the screen. For a complete implementation of this method see the sample application downloadable below.

Using a custom control

Screenshot showing AspectRatioPictureBox control within the Toolbox of Visual StudioUsing custom controls within your projects is reasonably straight forward. Once you have created your new custom control class you simply need to recompile your project in order for the control to be picked up by Visual Studio and displayed in the Toolbox as a custom control. This is shown in the above screenshot. Once an instance of the custom control has been placed onto a form its properties can be configured via the standard Property window.

Unlike the Desktop development environment, Smart Device custom controls do not directly utilise attributes such as [Description()] to configure their appeance and behaviour within the Visual Studio IDE. Instead Smart Device custom controls utilise what is called an XMTA file. Customising the design time experience of your custom controls will be discussed in a future blog post.

Sample Application

[Download aspectratiopictureboxtest.zip - 25.7KB]

A small sample application is available for download. It demonstrates the use of the AspectRatioPictureBox custom control developed within this blog entry in a number of different scenarios.

Feel free to utilise the included AspectRatioPictureBox.cs file within your own projects. As an added feature an additional property called “Restricted” has been added. When the Restricted property of the control is set to true the image will not be stretched any larger than it’s original size. When “unrestricted” the image will be stretched to take the full width or height of the control, even if that means stretching the image beyond it’s original size. The restricted mode is useful for image viewing applications where you don’t want to stretch small images and degrade their quality, while still ensuring large images are scaled down to fit the screen.

Create a SQL Server 2005 Compact Edition database visually by using the Data Source Configuration Wizard in Microsoft Visual Studio 2005

Monday, January 28th, 2008

Since developers spend a lot of their time within the Visual Studio 2005 IDE it is only natural that this tool has many features designed to create and maintain the contents of SQL Server 2005 Compact Edition databases.

NOTE: If any of the dialogs within your copy of Visual Studio 2005 refer to “SQL Mobile Database” or something similar you have an older version of SQL Server CE installed. See my Installing SQL Server Compact Edition blog entry for details on how to upgrade.

Creating a database

Screenshot showing Add New Item dialog

The quickest way to add a blank SQL Server Compact Edition database to a smart device project is to right click on the project within Solution Explorer and select the “New Item…” option within the “Add” submenu. This allows you to select the “Database File” item template, as shown in the above screenshot.

Once you have named the database file and clicked the Add button, the last step of the “Data Source Configuration Wizard” appears. You can press the cancel button to skip this wizard since our database is currently empty.

Another approach to creating a database file is to use the complete Data Source Configuration Wizard. This is accessible in a number of different places within the Visual Studio IDE, perhaps the easiest being via the “Add New Data Source…” menu item found within the main Data menu.

Screenshot showing first step of Data Source Configuration Wizard

The first step of the wizard asks what type of data source you would like to configure. For a SQL Server Compact Edition database we select “Database” and select the “Next” button to move to the second step of the wizard.

Second step of the Data Source Configuration Wizard

Since we are creating a new database our database will not be listed in the database combo box, so we press “New Connection…” to display the “Add Connection” dialog.

Screenshot showing the Add Connection dialog

This dialog can be used to configure a wide range of database products. If the read-only text box at the top of the dialog does not mention “Microsoft SQL Server 2005 Compact Edition” click the “Change…” button and select it from a small popup dialog that appears.

To create a database select the “Create…” button. This will display a dialog similar to the one seen within SQL Server Management Studio as discussed earlier.

Screenshot of Create New SQL Server Compact Edition Database dialog

Specifying the location we want the new database file to be stored in and pressing the OK button twice will return us to step 2 of the Data Source Configuration Wizard. Pressing the Next button takes us to the third and final step of the wizard. If the database file isn’t located within a subdirectory of the project you will get a prompt “the connection you selected uses a local data file that is not in the current project, would you like to copy the file to your project and modify the connection?”. Selecting yes is probably the best option, and will move a copy of the newly created database file into the project folder.

Screenshot showing third step of the Data Source Configuration Wizard

This last wizard step enables us to create a type-safe dataset for the database. Since we have just created a blank database there is not much use for this, so we can press the Cancel button to dismiss this step.

Opening a database

Double clicking on a SQL Server 2005 Compact Edition database file (*.sdf) within Solution Explorer will automatically open the Server Explorer pane and provide a view similar to the Object Explorer pane found within SQL Server Management Studio.

If the database file is not currently part of our solution we can use the “Connect To Database” toolbar button within the Server Explorer window to display the Data Source Configuration Wizard (as discussed above) to connect to the existing database file.

Creating tables

Screenshot of Server Explorer windowTo create a Posts table that looks like the example table we created in the previous tutorial we can use the Server Explorer window.

Right clicking on the “Tables” node underneath our database file will allow us to select a “Create Table” menu option. This will display a “New Table” dialog that allows us to graphically specify the details of our new table.

Screenshot showing the New Table dialog within Visual Studio 2005

Installing SQL Server Compact Edition (v3.1)

Monday, January 28th, 2008

SQL Server 2005 Compact Edition is available via a number of Microsoft downloads including:

Knowing which components are required and need to be installed for a given situation is important but can be confusing due to the various ways the SQL Server Compact Edition components can find their way onto your machine.

Installing onto a PDA

If your application makes use of a SQL Server Compact Edition database you must ensure that every PDA it runs on has the SQL Server Compact Edition database engine installed. If your target device is running Windows Mobile 6.0 it should have SQL Server 2005 Compact Edition in ROM, meaning nothing needs to be manually installed.

If your target device does not have a version of SQL Server Compact Edition installed or you would like to ensure that the latest service pack is installed you will need to manually install the database engine via one or more CAB files as part of your application installation process.

There are three different CAB files that make up the SQL Server 2005 Compact Edition product.

  • sqlce30.platform.processor.cab – The actual database engine.
  • sqlce30.repl.platform.processor.cab – An optional component that is required if your application makes use of the Merge Replication or Remote Data Access (RDA) APIs.
  • sqlce30.dev.lang.platform.processor.cab – Additional features for development purposes such as improved error messages for exceptions, and a query analyzer utility that runs directly on a PDA.

Once SQL Server 2005 Compact Edition support has been installed into Visual Studio 2005 (see below) you can find the required CAB files within the %programs%\Microsoft Visual Studio 8\SmartDevices\SDK\SQL Server\Mobile\v3.0\platform\processor\ folder.

One tricky bit is the fact that references to “platform” and “processor” in file and directory names above need to replaced with values specific to the version of Windows Mobile your target device is utilising.

In general you can use:

  • wce500\armv4i\sqlce30.ppc.wce5.armv4i.CAB – For Windows Mobile 5 Pocket PC or above devices.
  • wce500\armv4i\sqlce30.phone.wce5.armv4i.CAB – For Windows Mobile 5 Smartphone or above devices.

Although you will find support for a range of platforms and processor types within the specified folder.

Installing onto a desktop (or TabletPC, or UMPC etc)

One advance of SQL Server CE with the SQL Server 2005 Compact Edition release is the ability to run the database engine on desktop PCs.

If your target machine does not have Visual Studio 2005 or SQL Server 2005 installed you need to install the SQL Server Compact Edition Runtime (SQLServerCE31-EN.msi) on each machine your application is deployed to. This may be able to be done automatically if you are using Click-Once deployment functionality for your product. Alternatively the MSI can be directly downloaded, or found on your development machine within the %programfiles%\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\SQL Server Compact Edition folder.

Developer Tool Support

Different versions of Visual Studio support different versions of SQL Server CE.

Visual Studio version SQL Server CE version
VS2003 SQL Server 2000 Windows CE Edition (v2.0)
VS2005 (RTM) SQL Server 2005 Mobile Edition (v3.0)
VS2005 (SP1 + update) SQL Server 2005 Compact Edition (v3.1)
VS2008 SQL Server Compact 3.5 (v3.5)

As João Paulo Figueira pointed out SQL Server 2005 Mobile Edition (v3.0) and SQL Server 2005 Compact Edition (v3.1) are both compatible at the file level. The major changes between these two releases related to the high level SQL query processor and the number of platforms supported by the product.

Using the supported version of SQL Server CE for a particular version of Visual Studio means that you get access to all the graphical designers and database manipulation tools within Visual Studio such as Server Explorer and the Data Source Configuration Wizard. It is generally possible to utilise an older or newer version of the SQL Server CE database engine with a given version of Visual Studio, but in doing so you will loose the ability to use the graphical tools.

When Visual Studio 2005 shipped it orignally supported Mobile Edition. In order to update your copy of Visual Studio 2005 to support Compact Edition you need to perform the following steps:

  1. Install Visual Studio 2005 Service Pack 1.
  2. Install SQL Server Compact Edition Runtime.
  3. Install SQL Server Compact Edition Tools for VS2005 SP1.
  4. Optionally install SQL Server Compact Edition Books Online.

The second step of these instructions installs the updated (SQL Server 2005 Compat Edition) database engine, while the third step updates the Visual Studio 2005 user interface. You need to be careful, if you only install Visual Studio 2005 SP1, some elements of the user interface will have been updated, but this is only a change of a couple of strings within the dialog resources. Even though Visual Studio will refer to SQL Server Compact Edition, underneath the covers it is in fact still utilising the SQL Server 2005 Mobile Edition database product. For a more detailed coverage including solutions to the most common problems you may find along the way please review Steve Lasker’s Configuring Visual Studio 2005 for use with SQL Server 2005 Compact Edition blog post.

If you are using a development environment other than Visual Studio, or are looking for a way to obtain the CAB files without needing to install Visual Studio 2005 you could download the SQL Server Compact Edition Developer SDK. This package contains the installers for the SQL Server Compact Edition Runtime, the CAB files required for installation onto a PDA, a local copy of the SQL Server Compact edition Books Online documentation, as well as an example of how to access SQL Server Compact Edition databases in native C++ code.

Create a SQL Server 2005 Compact Edition database visually by using SQL Server Management Studio

Saturday, January 26th, 2008

Microsoft SQL Server 2005 Management Studio (commonly also referred to as SSMS) is a replacement for the Enterprise Manager tool found in earlier versions of SQL Server. As well as administering SQL Server 2005 (or earlier) database instances the tool can be used to administer SQL Server 2005 Compact Edition databases that live on a PDA.

If you don’t have a version of the SQL Server 2005 developer tools installed on your desktop, you can download and install the free SQL Server 2005 Management Studio Express edition (service pack 2 or later), as this product also supports Compact Edition databases.

Creating a database

When SQL Server Management Studio is started on your desktop PC the “Connect to Server” dialog will appear.

Screenshot of SQL Server 2005 Management Studio's Connect To Server dialog

To create a new SQL Server 2005 Compact Edition database,

  1. Select “SQL Server Compact Edition” as the server type
  2. Select the <New database…> option within the Database File combo box

This will display a “Create New SQL Server Compact Edition Database” dialog, as shown below:

Screenshot of Create New SQL Server Compact Edition Database dialog

The most important option to specify is the location of the new database file. Selecting the browse button allows you to graphically select a location on your local harddrive, or an ActiveSync connected PDA. Alternatively you could type in the path manually. To create a database on the PDA you use the prefix “Smart Device” instead of a drive letter. For example “Smart Device\Program Files\MyApplication\MyDatabase.sdf”.

The encryption and sort order properties will not be discussed at this point in time, as I am planning to cover these in greater depth in future blog entries. In the mean time they can be left at their default values.

To complete creating the database we need to select the OK button. Since no password has been specified for the database, a warning that the “password is either not provided or blank” will be displayed. This can be safely ignored by pressing the Yes button.

After SQL Server 2005 Management Studio has created the database you will be returned to the “Connect to Server” dialog, however this time the Database File field is populated with the name of the newly created database.

Opening a database

Once a SQL Server 2005 Compact Edition database has been created it can be opened within SQL Server Management Studio 2005 by using the same “Connect to Server” dialog discussed above (also accessible via the File, Connect Object Explorer… menu option).

To open an existing SQL Server 2005 Compact Edition database,

  1. Select “SQL Server Compact Edition” as the server type
  2. Specify the database filename within the Database File combo box

Recently accessed databases are available in the Database File drop down combo box. To browse the file system to graphically select another database file you can select the <Browse for more…> option within the combo box.

Creating Tables

One of the advantages of using SQL Server Management Studio is its rich support for the management and manipulation of databases and their contents. When targeting SQL Server 2005 Compact Edition databases many Management Studio features are disabled, but the subset provided is still pretty useful.

Screenshot showing how to create a new table via the Object Explorer pane

Within the Object Explorer pane you can view the various objects within your database. To create a new table, you can right click on the Tables node within the Object Explorer and select “New Table”. This will display a dialog which allows you to specify the details of the new table, such as its name and the properties of the columns it contains. Using this view also allows you to rename and delete database objects.

Alternatively you can interact with the database via Transact-SQL queries. The SQL Server 2005 Compact Edition database engine supports a subset of the query language supported by SQL Server 2005 on the desktop. To create a new query select the “New Query” toolbar button (Ctrl + N is the keyboard shortcut), and enter the query in the new window that appears. Pressing F5 or the execute toolbar button will then execute the query and show its results.

To create a new database table we could execute the following query (for more details see the CREATE TABLE (SQL Server Compact Edition) section of SQL Server 2005 Compact Edition Books Online).

CREATE TABLE Photos
(
  id INT NOT NULL IDENTITY PRIMARY KEY,
  name NVARCHAR(100) NULL,
  filename NVARCHAR(256) NOT NULL,
  description NVARCHAR(2048) NULL
)

By default after executing such Data Definition Language (DDL) statements changes in the database schema are not reflected in the Object Explorer pane. In order for the new table to show up you need to right click and select “Refresh”.

The many versions of SQL Server CE

Tuesday, January 22nd, 2008

If you refer to the 70-540 Exam study guide you will see references to a database product called SQL Server 2005 Everywhere Edition. This product technically doesn’t exist!

Logo of SQL Server 2000 Windows CE Edition product

Originally there was a database product for Pocket PC devices called SQL Server CE (aka SQL CE). For similiar reasons to those mentioned in my blog post about Windows Mobile naming conventions, the product name for the SQL Server CE database engine has changed over time.

This leads to a confusing mismatch of names through out the various developer tools and documentation, especially when Visual Studio and SQL Server CE releases were not in sync with each other. As a simple example the ADO.NET data provider for SQL Server 2005 Mobile Edition databases still lives within the System.Data.SqlServerCe namespace for backwards compatability reasons.

A brief version history

There have been atleast 5 major releases of the SQL Server CE database engine as follows.

Offical Name Nickname
SQL Server 2000 Windows CE Edition SQL CE 1.0
SQL Server 2000 Windows CE Edition SQL CE 1.1
SQL Server 2000 Windows CE Edition SQL CE 2.0
SQL Server 2005 Mobile Edition SQL CE 3.0
SQL Server 2005 Compact Edition* SQL CE 3.1
SQL Server Compact 3.5 SQL CE 3.5

* Was also called SQL Server 2005 Everywhere Edition.

Visual Studio 2005 originally came with support for SQL Server 2005 Mobile Edition. However with Service Pack 1 (and an optional download) it is possible to update it to support development against SQL Server Compact Edition.

The 70-540 Study Guide was obviously produced before SQL Server Compact Edition was officially released. Prior to final release the product was scheduled to be named SQL Server Everywhere edition.

There is little difference between SQL Server 2005 Mobile Edition (v3.0) and SQL Server 2005 Compact Edition (v3.1) on PDAs, the major difference is that SQL Server 2005 Compact Edition was the first release to support running the database engine on an X86 desktop PC. Prior to this release SQL Server CE only supported running on Windows CE based devices such as Pocket PC PDAs.

I am about to renew my effort to post blog entries for my 70-540 Study Guide. This blog post was designed to setup the stage for a series of posts about database access within the .NET Compact Framework environment.

Community Interview: Dale Lane

Thursday, January 17th, 2008

1) Can you introduce yourself?

Photo of Dale Lane and his daughter GraceMy name is Dale Lane. I live in the south of England, in Eastleigh. My job is a Software Engineer for IBM working in the R&D lab at Hursley Park, near Winchester.

I’m currently working in development for IBM WebSphere Process Server on the z/OS mainframe operating system – a different world to mobile development work!

2) When and how did you initially become involved with Windows Mobile based PDAs? And leading on from this how did you become interested in developing custom applications for this platform?

I have been an owner and fan of Palm OS PDAs for years – starting with the Palm III. My favourite Palm was the Sony Clie UX50 – a small clamshell PDA that looked like a minature laptop. When the Clie started to die and Sony stopped making PDA’s, I struggled to find a replacement, until the O2 XDA Exec (HTC Universal) was released. Despite meaning a shift to Windows Mobile, I loved the form-factor and bought one the week they came out. I’ve been a fan of Windows Mobile ever since.

I came across the free developer kit for Windows Mobile by chance – I was investigating Microsoft’s Windows Mobile webste, and saw a link to the page to order the dev kit. I am a software developer and a geek – so any chance to tinker with something new is always fun. But this was entirely an impulse thing – I hadn’t considered doing Windows Mobile development before that, and had I not stumbled across the offer of a free SDK, I might not have gone looking for how to get into it.

When I got the kit, I was amazed at how easily you could access so much of the device – intercept incoming messages, get system info like battery level or mobile signal strength, read the data stores used in core Outlook apps like your Calendar or Task list, and more. It meant I could start playing quite easily without needing to write a whole standalone application from scratch. The more I played, the more interested I got… until I got hooked.

3) What is your favourite development environment?

I use Visual Studio 2005 – it does so much of the stuff needed to create a Windows Mobile app for you.

I’m torn between whether my favourite language is managed C# or native C++. The Windows Mobile C# API, and the visual interface development tooling you get in VS2005, makes it very quick and easy to throw together applications. As Windows Mobile development is a side hobby for me, the ability to take a random idea from conception to first prototype in an evening or two is a big bonus.

On the other hand, as an old C programmer, there is a fairly snobby part of me that thinks it’s somehow cheating if you aren’t doing your own memory management, and I like the way writing native C++ lets me do everything myself. The extra time it takes means that the only time I write C++ code for Windows Mobile is when I want to do something not exposed in C# – like adding context menus to existing Windows Mobile core applications or extending the Today Screen.

4) You seem to have developed a number of interesting Windows Mobile applications, how do you come up with some of your ideas?

“Ooh – I wonder if I can do…” is normally where most projects start. The vast majority of projects start and end in an evening or two and never really see the light of day. Once I’ve got the general idea of how something works, or prove to myself that something is possible, that’s pretty much where it ends. Probably 75% or more of these projects never see the light of day – never finished enough to really be usable as an application, but just enough to teach me something about the API or platform. Again, this is a strength of the API exposed in managed code – C# lends itself well to this kind of rapid sandbox experimentation.

Occasionally, something about an idea sticks with me, and I actually develop a project to the point where I can use it as an application. For example, I wrote some GPS tracker code to put my current location on a Google Maps map. It works for me, but isn’t in a state where I could give it to anyone else. The interface could improve, too many bits are hard-coded for my own needs, and there is still too much left to finish. I’ve got maybe a dozen apps like this.

Very very rarely I finish something to the point where it can be shared with other people. This can be because I’ve shown or talked to someone about one of my random ideas and they like it enough to ask for a copy, or just because I think other people might find it useful.

5) Do you carry a Windows Mobile device with you at present?

I always have some PDA with me… either the O2 XDA Exec (aka HTC Universal), T-Mobile Ameo (aka HTC Advantage) or Palm Treo 650. Most often, I carry the HTC Advantage. It’s definitely my favourite – it’s got the mini-laptop form factor that I like, with a full QWERTY keyboard, a huge bright VGA screen, inbuilt GPS, and more. It’s ridiculously powerful for a phone, and if I’m away from my desk for a long while and can carry nothing else, it’s my first choice.

It’s a bit big, so if I’m just going to the shop or going out to meet a friend, it is useful to have something smaller like the Treo.

6) You seem to have had the opportunity to play with a range of interesting PDA type devices recently. How do these devices compare to your Windows Mobile device(s), and is there anything these devices could teach Windows Mobile?

My biggest Windows Mobile bugbear is it’s responsiveness. Sometimes (and especially, it seems, when I’m in a hurry!) it feels like I spend half my time staring at the spinning wait cursor that is our equivalent of the Windows hourglass. For all the iPhone’s limitations (and it has a *lot*), it does at least seem to be a snappy little device. The same goes for skypephone, or any other mini feature phone I’ve played with – it’s limited, I can’t do most of the things I want to be able to do… but at least whatever it does do, it does fairly quickly.

My Palm devices (a Treo 650 and a Clie UX50) are both much quicker at the most common PIM tasks – I can look up a calendar event or contact’s phone number in a fraction of the time it takes me to do the same in Windows Mobile. I’ve said this before if I have some time on the road to sit down to some serious work, the power of Windows Mobile is fantastic. But for quickly retrieving some key information on the run, the (admittedly fairly old) Palm OS PDA’s still have their place.

The OpenMoko on the other hand… isn’t really ready for use. It’s a development sandbox that only rarely gets disconnected from my Linux desktop. It’s immature both in hardware (very short battery life) and software… but the ability to open a terminal and SSH to your phone still makes me smile. I’d love it if we could get a decent remote command-line access to Windows Mobile phones. I know the demand for this would be small… but I’m so much quicker at stuff like file management at the command line. I wrote a little SMS utility that lets me send text messages at the command line on my desktop and I use this several times every day. It’d be great if I could do more things like this.

7) You are also involved with youth charity work. Would you like to tell us a little about what your charity does etc?

My charity is called “Solent Youth Action” – and is a youth volunteering organisation. We work to encourage and facilitate positive voluntary contributions to the community from young people.

Introducing Community Interviews

Thursday, January 17th, 2008

Photo of a person holding the earth between a pair of handsThe internet has helped make the world a smaller place, but has also had a tendency to anonymise people. People are attracted to Windows Mobile development for a number of reasons, and although involved with them via their blogs, forum postings and presentations etc it can be difficult to put a face to the name, or place them within the Windows Mobile community.

I am aiming to have a new type of semi-irregular blog post on this blog in the form of interviews of interesting people within the Windows Mobile development eco-system that I have had the pleasure of communicating with.

To get the ball rolling I have interviewed Dale Lane, a professional IBM z/OS mainframe programmer by day, a Windows Mobile enthusiast by night. His interview is timely since he touches upon a number of general feelings held by many users within the Windows Mobile community at present with regards to the usability of the Windows Mobile platform and importance of cheap development tools.

If you would be willing to be interviewed, or would like to recommend some one to be interviewed please contact me via the newly configured contact me page on this blog.

.NET Compact Framework Platform support

Wednesday, January 16th, 2008

.NET Framework logoQuick! Will .NET Compact Framework 2.0 run on a Windows CE 4.1 powered device?

Today while helping someone with a development question, I rediscovered the Devices and Platforms Supported by the .NET Compact Framework page within MSDN. This page contains two handy charts. The first lists each .NET Compact Framework release and the various versions of Windows Mobile Pocket PC, Windows Mobile Smartphone and Windows CE it supports. The second table lists the version of .NET Compact Framework you can expect to find pre-installed in ROM on a given device.

A lot of questions within online forums come down to what platform support there is for a given .NET Compact Framework release. This page will come in handy in determining the compatibility and deployment requirements for applications using a particular .NET Compact Framework version. It’s particularly handy because it covers a number of corner cases not seen in similiar charts found elsewhere.

Creating a Redfly emulator

Monday, January 14th, 2008

The Redfly Mobile Companion (manufactured by Celio Corporation) is essentially a large external LCD screen and keyboard designed to display the contents of an attached Windows Mobile based PDA or smart-phone. One value proposition of the device is to improve the usability of applications such as Excel Mobile in large part due to the device’s 800×480 screen which enables more data to be displayed. If any device embodies the intent behind Microsoft’s Adapt Your App campaign and how far we have came from the days of a single 240×320 screen resolution this may be it.

Recently I became interested in understanding how well various applications coped with the Redfly’s larger screen resolution, as I imagine supporting such a resolution isn’t in the front of most developer’s minds at the moment. Not having access to a physical device I decided to configure the Windows Mobile Device Emulator to approximate the behaviour of a Redfly device.

Screenshot showing Excel Mobile running on a device with a 800 x 480 screen

Creating a custom emulator
Visual Studio uses an applicaton called Device Emulator for the emulation of ARM based Windows Mobile or Windows CE devices. This application is designed to also be used standalone (you can download it from Microsoft Downloads) and accepts a number of command line arguments to configure the emulated PDA.

To start a Windows Mobile 5.0 Pocket PC emulator with the same screen resolution of a Redfly device we could use the following command line:

"C:\program files\Microsoft Device Emulator\1.0\DeviceEmulator.exe"
  "C:\Program Files\Windows Mobile 5.0 SDK R2\PocketPC\DeviceEmulation\0409\PPC_USA.bin"
  /cpucore ARMv5
  /memsize 256
  /s "C:\Development\RedflyEmulator.dess"
  /tooltips ON
  /vfp false
  /video 800x480x16
  /vmname "Redfly Emulator"
  /speakerphone 7

Some of these paths may need to be altered to suit your installation of Visual Studio and the various Device SDKs. Full details on the meaning of the various command line arguments can be found on the Device Emulator Command-Line Reference page within MSDN.

Reusing a custom emulator
Screenshot showing Device Emulator Save State file (*.dess) within Windows ExplorerOnce a custom emulator has been started via the command line shown above you will be prompted when you attempt to exit the emulator to save the current state. If you select Yes to this prompt a Device Emulator Save State (*.dess) file will be created. This file contains a complete snapshot of the emulator’s configuration and memory contents. Double Clicking on this file within Windows Explorer will automatically launch the Device Emulator and restore the emulator back to the state it was in before you exited. There is no need to re-enter the rather long command line again.

Summary
Creating a custom emulator enabled me to determine the enhanced usability (or lack there of in some cases) of various Microsoft and Third Party applications on a device with the Redfly’s form factor. I could defiantly see the advantage of the larger screen in applications such as viewing and creating Excel spreadsheets (as demonstrated in the above screen shot). However other applications (such as Pictures and Videos) didn’t really take full advantage of the additional screen real-estate. Moving forward it would seem to be advantageous for ISVs to consider how to dynamically take advantage of extra screen real-estate when presented with a device such as the Redfly. In fact I see some real business oppertunities for those that truely take advantage of it.

Creating custom emulators as demonstrated in this blog posting is also useful for producing presentation material for Sales people. By making various save state snapshots it is possible to present your application in a number of different configuration/use case scenarios without constantly needing to reconfigure the standard emulator and it allows you to quickly revert back to a known good starting state for your demos.

Determining the depth of a node within a TreeView control

Sunday, January 13th, 2008

Given a TreeNode somewhere within a TreeView control, a desktop System.Windows.Forms developer would query the TreeNode.Level property to determine the depth of the node within the tree as demonstrated below:

MessageBox.Show(
  String.Format("Depth of node: {0}",
    treeView1.SelectedNode.Level));

However as stated by the MSDN Documentation this property is not available on the .NET Compact Framework. This is because one of the techniques Microsoft has used to reduce the size of the .NET Compact Framework is to remove methods and properties from the Base Class Library when the same behaviour can be implemented with a couple of lines of code written by the user.

So although the .NET Compact Framework does not provide a TreeNode.Level property we can implement our own, but first we must come up with a suitable algorithm.

General algorithm
Given a node within the tree (represented by the TreeNode class) we can determine the node’s Parent by querying the Parent property. If we repeat this process we will eventually get to a node which has null for it’s parent. This node is called the root (or top) of the tree. If we count the number of nodes we walked over to reach this node we have calculated the depth (or level) of the node we started at. This algorithm is implementable within C#.

Diagram outlining algorithm to determine depth of a node within a tree

Pre C# v3 Implementation
The best we can do with C# version 1 or 2 is to replace calls to missing methods with calls to static helper methods we manually write. For example we could write the following helper class to replace the TreeNode.Level property.

namespace MyProject
{
  public static class Utils
  {
    public static int Level(TreeNode node)
    {
      int i = -1;
 
      // Walk up the tree until we find the
      // root of the tree, keeping count of
      // how many nodes we walk over in
      // the process
      while (node != null)
      {
        i++;
        node = node.Parent;
      }
 
      return i;
    }
  }
}

and make use of it as follows

MessageBox.Show(
  String.Format("Depth of node: {0}",
    Utils.Level(treeView1.SelectedNode)));

C# v3 Implementation
C# version 3 (first available with the .NET 3.5 framework release) introduces a language feature called extension methods. This is basically a compiler trick which allows us to call helper methods such as the one created above with a slightly different syntax, that makes it appear as if the new methods we define are part of the existing objects. Behind the scenes the compiler is simply rewriting our statements to use the old syntax.

To convert our helper method into an extension method we only need to convert the method prototype from

public static int Level(TreeNode node) { ... }

to

public static int Level(this TreeNode node) { ... }

The magical “this” keyword is enough to get the following syntax to work

MessageBox.Show(
  String.Format("Depth of node: {0}",
    treeView1.SelectedNode.Level()));

Notice how our new Level() method can be called as it it was a member of the TreeNode class. This is very close to the original syntax that a desktop developer would utilise. In this example ideally we would create an “extension property”, which would mean we could utilise identical syntax on both platforms, however C# v3 does not support extension properties, only extension methods.

Sample Application

[Download TreeNodeLevelExample.zip - 19KB]

A sample application is available for download. The application shows a simple tree view and allows the user to select different nodes within it. As different nodes are selected a label is updated to show the depth of the currently selected node.

There are two versions of the sample application. The first is designed for .NET CF 2.0 and uses the first technique demonstrated, while the second is for .NET CF 3.5 and demonstrates the cleaner extension method based syntax.

Daniel Moth among others have discussed various techniques to support cross compiling code across both the .NET Compact and Full desktop frameworks. Extension methods are another tool to add to the toolbox, allowing you to provide your own implementations for methods missing from the .NET Compact Framework without requiring code changes to your main application source code.

Is anyone aware of any discussions available online about why it was decided not to support extension properties (or events)? Is this something we can expect to see in C# version 4?