Thursday, June 25, 2009

Over the past few months we've been working hard to consolidate the products we at OpenNETCF offer.  What this means is that products that didn't sell well or that had high support loads compared to sales got dropped.  Our Telephony library is one of those that we decided to discontinue.  But that's good news for all!  Instead of just letting it wither and die in the depths of our own source control server, we figure it might as well be thrown out to the community to see if it will flourish.

SO with that, we give you the OpenNETCF.Telephony Library, hosted over at Codeplex as tapi.codeplex.com.  Enjoy.

6/25/2009 7:06:39 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 

We're going to be adding a full set of custom-drawn and owner-drawn controls in the next version of the SDF.  These are not "new" controls, but wrappers around the existing native control, but we're adding the custom and owner draw hooks that the OS already provides (and that, honestly, the CF team should have given us by version 3.5). 

In testing them out, I wanted to dogfood the custom-drawn ListView in an application, but I needed to know when a user clicked on an item in the ListView.  Simple.  Or so I thought.  It turns out that the style bits that get set to make a ListView really usable means that the ListView's *parent* gets it's click actions, and to turn those into Click events in the managed control is a *lot* of work, and would likely have some performance penalty.

So that got me to wondering how the existing CF ListView deals with it.  Well after a very quick test it seems that the CF team made the same decision - they didn't support the Click event either

Well my application requires that I know the difference between when the selected index changes (that's about the only useful event you do get) due a click and and when it changes dues to a keyboard action like an up or down arrow. Being me, I refuse to change the way I want my application will work just becasue of some stupid limitation of a framework.  The OS knows when I click on that damned thing - after all, it changes the selected item - so it *will* tell my application when it happens.

The key here is pretty simple.  We know that the click event does come in, and it comes in as a Windows message.  Our application message pump routes it to the parent of the ListView - so we have two point at which we can try to get it.  Getting it from the parent would entail subclassing the parent Form, and that just does seem like fun, nor is it really extensible if I ever have another app where I want to get ListView item clicks.

So that leaves looking at the application message pump.  Unfortunately the CF team has again not seen fit in any version to provide us the ability to add an IMessageFilter, but this was something we overcame long ago in the SDF.  If you use the Application2.Run method, you can then add IMessageFilters.  So what I did here is created an IMessageFilter that looks for messages whose hWnd matches the ListView I'm interested in, and then looks for the WM_LBUTTONDOWN message:

internal class ClickFilter : IMessageFilter
{
  private Control m_control;

  public event EventHandler Click;
  public event MouseEventHandler MouseDown;

  public ClickFilter(Control control)
  {
    m_control = control;
  }

  private int LoWord(IntPtr param)
  {
    return (ushort)(param.ToInt32() & ushort.MaxValue);
  }

  private int HiWord(IntPtr param)
  {
    return (ushort)(param.ToInt32() >> 16);
  }

  public bool PreFilterMessage(ref Microsoft.WindowsCE.Forms.Message m)
  {
    if (m_control.IsDisposed) return false;

    if ((m.HWnd == m_control.Handle) && (m.Msg == (int)Microsoft.Controls.WM.WM_LMOUSEDOWN))
    {
      MouseEventArgs args = new MouseEventArgs(MouseButtons.Left, 1, LoWord(m.LParam), HiWord(m.LParam), 0);

      ThreadPool.QueueUserWorkItem(ButtonInvoker, args);
    }

    return false;
  }

  void ButtonInvoker(object o)
  {
    // let the system select the clicked listview item
    Thread.Sleep(10);
    Application2.DoEvents();

    if (m_control.IsDisposed) return;

    if (m_control.InvokeRequired)
    {
      m_control.Invoke(new WaitCallback(ButtonInvoker), new object[] { o });
      return;
    }

    // not truly a click, since it's not a down/up pair. Fix this later if we feel like it
    if(Click != null) Click(m_control, null);
    if (MouseDown != null) MouseDown(m_control, o as MouseEventArgs);
  }
}

Take note of the slight kludge in there though with the ThreadPool.  The reason for this is that if you just raise the event immediately on getting the mouse down event, the ListViewItem selection won't have happened yet, so if your handler looks at the SelectedItem, it would get the item that was selected before the click, not the one that the was clicked. 

Sure, maybe that's what your app wants, but in my case I wanted to know which item is actually clicked.  The ListView doesn't support a HitTest method (again, why don't we have this yet?), so knowing the x,y coordinates of the click is still a long way from giving us the ListViewItem.  This was a kludge to easily get me the info I wanted.

So using this filter in my application was as easy as adding this to the Form that contains the ListView:

InitializeComponent();

ClickFilter filter = new ClickFilter(listView);
filter.Click += new EventHandler(filter_Click);
Application2.AddMessageFilter(filter);

No, it shouldn't be this hard.  I wish the CF team would spend more time fixing fundamental stuff like this instead of tilting at the Silverlight windmill, but it is what it is, and as developers we still have to ship solutions.

6/25/2009 11:27:26 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [4]  | 
 Wednesday, June 24, 2009

It took a long time to get here, but we've finally release what I'm calling the version 1.0 (pervious version were 0.9.x) release of the OpenNETCF.IoC Framework.  In case you've not been tracking this project, it is a public-domain-licensed (you can't get any more free and unencumbered than that) framework that provides both inversion of control and dependency injection for .NET Compact Framework applications (it can be used on the desktop as well).  It's roughly modelled after Microsoft's SCSF and CAB frameworks, but it's scaled down and optimized for running on mobile and embedded devices, plus I "fixed" stuff that I think the SCSF got wrong (like having a static, globally available RootWorkItem and the ability to insert IMessageFilters into the application's message pump).

This framework is in use in a couple of commercial applications already, so it's been pretty heavily tested and vetted.  I still want to add a few more features as well and go back through it looking for performance optimizations, but it certainly has enough features to be used in applications today.

This release also ships with a full-blown, real-world sample application, not just the typical "Northwind" type of application.  The sample is called WiFiSurvey and it can be used to survey WiFi AP coverage of a site and to monitor associated AP changes as well as network addressability of a device.

WiFiSurvey has a Configuration service, a SQL CE 3.5-backed Data Access Layer, an Infrastructure module and a an application shell all of which are fully decoupled from one another and that are all loaded dynamically using an XML definition file.  The shell makes use of both a DeckWorkspace and a TabWorkspace, showing you not just how to use them, but also how to create your own workspaces if need be.

The WiFiSurvey application has a single source base for all target platforms and has been tested on the following platforms:

  • ARM-based CE 6.0 with a 320x240 (landscape) display.
  • Pocket PC 2003 240x320 (portrait)
  • WinMo 5.0 240x320 (portrait and landscape)

The IoC framework has additionally been tested on x86-based CE 5.0 and CE 6.0 devices.

As a side note, the WiFiSurvey sample application is also a good example of using the OpenNETCF Smart Device Framework for getting wireless information.

6/24/2009 2:54:24 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [2]  | 
 Wednesday, June 17, 2009

So it seems that something has changed in CE 6.0 in the way that user inactivity is detected by the OS.  In CE 5.0 and before, if we wanted to keep the backlight on we could periodically call SystemIdleTimerReset and all would be well.  In CE 6.0, this no longer works.  Now we have to set a named event that GWE is waiting on.  Here's what it looks like (this code uses the SDF for the named EventWaitHandle - the CF doesn't provide one).

private EventWaitHandle m_activityEvent;

[DllImport("coredll", SetLastError=true)]
private static extern void SystemIdleTimerReset();

private void ResetBacklightTimer()
{
  if (Environment.OSVersion.Version.Major <= 5)
  {
    SystemIdleTimerReset();
  }
  else
  {
    if (m_activityEvent == null)
    {
      using (var key = Registry.LocalMachine.OpenSubKey("System\\GWE"))
      {
        object value = key.GetValue("ActivityEvent");
        key.Close();
        if (value == null) return;

        string activityEventName = (string)value;
        m_activityEvent = new EventWaitHandle(false, EventResetMode.AutoReset, activityEventName);
      }
    }

    m_activityEvent.Set();
  }
}

6/17/2009 5:11:25 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Wednesday, April 01, 2009

I'm in the middle of adding a Passive View Model-View-Presenter(MVP) framework to the OpenNETCF IoC Framework.  I just checked in a working version (it's in the source downloads, not as a release).  If you're interested and want to have a say in how it ends up, go ahead and download it and give me your feedback.  There's a simple usage example in source control.

4/1/2009 4:10:37 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [3]  | 
 Tuesday, March 31, 2009

Another nice addition to the latest drop of the SDF is the ability to get the serial number and manufacturer ID of storage volumes that support it (like SD cards). We did this by simply extending the existing OpenNETCF.IO.DriveInfo class to add a couple new properties.  Here's a quick example of how it works:

foreach(var info in DriveInfo.GetDrives())
{
  Debug.WriteLine("Info for " + info.RootDirectory);
  Debug.WriteLine("\tSize: " + info.TotalSize.ToString());
  Debug.WriteLine("\tFree: " + info.AvailableFreeSpace.ToString());
  Debug.WriteLine("\tManufacturer: " + info.ManufacturerID ?? "[Not available]");
  Debug.WriteLine("\tSerial #: " + info.SerialNumber ?? "[Not available]");
  Debug.WriteLine(string.Empty);
}

3/31/2009 12:03:33 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [2]  | 

The latest drop of the SDF adds a nice little feature for playing tones with the device.  It works a lot like the old Beep API on the desktop where you provide a frequency and a duration and it plays the tone.

Here's a quick example of how it works:

Tone[] scale = new Tone[]
{
  // up fast, using MIDI
  new Tone { Duration = 10, MIDINote = 63},
  new Tone { Duration = 10, MIDINote = 65},
  new Tone { Duration = 10, MIDINote = 67},
  new Tone { Duration = 10, MIDINote = 68},
  new Tone { Duration = 10, MIDINote = 70},
  new Tone { Duration = 10, MIDINote = 72},
  new Tone { Duration = 10, MIDINote = 74},
  new Tone { Duration = 10, MIDINote = 75},

  // down slow, using freq (same notes as above)
  new Tone { Duration = 100, Frequency = 622 },
  new Tone { Duration = 100, Frequency = 587 },
  new Tone { Duration = 100, Frequency = 523 },
  new Tone { Duration = 100, Frequency = 466 },
  new Tone { Duration = 100, Frequency = 415 },
  new Tone { Duration = 100, Frequency = 391 },
  new Tone { Duration = 100, Frequency = 349 },
  new Tone { Duration = 100, Frequency = 311 },
};

SoundPlayer.PlayTone(scale);

You can see that this just plays an ascending scale of notes quickly, then the same scale descending, but slower.  Note that the PlayTone method takes in an array of Tones, and a Tone can be initialized with either a Frequency or MIDI note value.

3/31/2009 11:57:42 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Friday, March 20, 2009

OpenNETCF used to have a product that provided RAS capabilities.  Well Microsoft deprecated RAS in WindowsMobile - starting with WinMo 5.0 as near as I can figure - in favor of Connection Manager.  That depracation actually broke RAS in some scenarios.  FOr example, if you create a RAS connection and then try to use a managed TcpClient, it will try to create it's own connection through the Connection Manager instead of using the connection you created through RAS.

What this did was skyrocket our support incidents for something that we sold very, very few licenses for.  In the interest of keeping our sanity, yet allowing people using plain of Windows CE to still use RAS, we made the decision to just make it a shared source project.  It's now out on CodePlex.  If you need support for it, we still offer consulting services, but everything is there to get you going.

3/20/2009 12:54:05 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Wednesday, March 11, 2009

Articles in this series
Part I: Inversion of Control and the Compact Framework
Part II: The OpenNETCF.IoC Framework: Items and Services
Part III: The OpenNETCF.IoC Framework: Events (this article)
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


In the Part II of this series we looked at how the OpenNETCF.IoC framework provides dependency injection for the lists of Items and Services and if you look at the sample application that ships with the framework you’ll see that the application creates and displays 3 separate Froms and a Service without a single call to the ‘new’ operator anywhere in the solution and, more importantly, without having to pass object references around yourself.

While I find that both fun and useful, the real thing I love about the OpenNETCF.IoC framework (and the SCSF that it’s modeled after) is the implementation of inversion of control through event publication and subscription.

A New Paradigm for Events

In the traditional managed development, an object exposes an event, something like this:

public event EventHandler OnMyEvent;

And when a subscriber wants to get notified of that event, they add a handler delegate like this:

publisherInstance.OnMyEvent += HandleOnMyEvent;

void HandleOnMyEvent(object sender EventArgs args)
{
  // do something useful here
}

That’s all well and good, but in my mind there are two problems with it. First it’s just plain ugly.  I have code in two places, first to attach the event, and second to handle it.  I like to keep related code close together, and this coupling of attaching the handler and the delegate implementation makes that hard (unless you use anonymous delegates). 

The second, and far worse, problem is that it requires that you have the instance of the event publisher to wire this up.  In some cases this is fine, but in others it seems rather pointless.  Let’s go back to one of our early examples of People and Cars and extend it ever so slightly.  We’ll add an event to the Car class :

public delegate void WreckHandler(ICar car);

class Car : ICar
{
  public event WreckHandler OnWreck;
}

And let’s say we have a specialized person – a PoliceOfficer – and he’d like to know any time there is a car wreck.

class PoliceOfficer : Person
{
  public void HandleCarWreck(ICar car) {…}
}

How would we wire this up?  Should we pass every Car instance in town to the officer so he can wire up the event?

class PoliceOfficer : Person
{
  public void HandleCarWreck(ICar car) {…}

  public void WatchCar(ICar car)
  {
    car.OnWreck += HandlerCarWreck;
  }
}

When would we call this?  Every time a Car instance is created?  How would the new Car instance know about the PoliceOfficer?  What if we have multiple Officers?  You can see that this gets real ugly, real fast.  Wouldn’t it be nice if any PoliceOfficer could just listen for the OnWreck event globally and any time any Car instance raised it, he would get notified?  Well that’s what the OpenNETCF.IoC framework’s eventing structure is all about. You publish and subscribe to events based on a unique string name for the event of interest.

So for the event publisher, the Car in this case, we use the same event definition but we add a simple attribute:

class Car : ICar
{
  [EventPublication(“CarWreck”)]
  public event WreckHandler OnWreck;
}

The important piece here is the text string that is sent in to the EventPublication attribute.  It can be any string at all, but it’s that string that event subscribers will use.

Over on the subscriber end it, hooking up the event looks like this:

class PoliceOfficer : Person
{
  [EventSubscription(“CarWreck”, ThreadOption.Caller)]
  public void HandleCarWreck(ICar car) {…}
}

Notice that I’m using the same text string in both.

Now there are a few important notes on using events in the OpenNETCF.IoC framework.  First all of the objects (publishers and subscribers) have to be actually in the framework (in either the Items or Services collection).  In fact with the version of the Framework that ships as I write this, the objects actually have to be created by the framework.  This means that if you create the object manually and then use the Add method to get it into the collection (as opposed to calling AddNew or using an InjectionConstructor or ServiceDependency), then the events won’t get wired up.  I intend to fix this in a future version, but if you pull down the code today, be aware of that limitation.

The second note is in relation to the subscriber.  You’ll see that the EventSubscription attribute takes a ThreadOption as a second parameter.  The idea behind this parameter is that it should dictate the thread on which the handler runs – either in the context of the caller or in the context of the UI.  Well that attribute, for now, is just a placeholder.  It’s not actually used anywhere, so don’t be surprised if your worker thread raises an event and your subscriber tries to update the UI and gets an exception whining about the use of Control.Invoke.  Again, this is something I intend to complete but when I looked at the options of releasing the framework either earlier with a few missing features or later and feature complete, I thought that just getting it out would be a lot more useful.


Next up: Looking at the performance implications of all of this IoC and DI stuff

3/11/2009 11:23:45 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [2]  | 
 Tuesday, March 10, 2009

So I was reading the Windows Mobile Team Blog and to my surprise I saw "How to capture a screen shot with .NET CF" as a topic that actually made it to the top of their "upcoming articles" list.  Seriously?  I know the SDF provides that.  So I did some basic Googling and sure enough, unless you know what you're looking for, it's tough to find (but it's been out for over a year).  For the record, the code is way too simple for a full article.  Even with the P/Invokes directly it's pretty basic, but with the SDF, it looks like this (pulled from a sample web page for our Padarn web server):

// create a bitmap and graphics objects for the capture
Drawing.Bitmap destinationBmp = new Drawing.Bitmap(Forms.Screen.PrimaryScreen.Bounds.Width, Forms.Screen.PrimaryScreen.Bounds.Height);
Drawing.Graphics g = Drawing.Graphics.FromImage(destinationBmp);
GraphicsEx gx = GraphicsEx.FromGraphics(g);

// capture the current screen
gx.CopyFromScreen(0, 0, 0, 0, Forms.Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

// save the file
destinationBmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png);

// clean house
gx.Dispose();
g.Dispose();
destinationBmp.Dispose();

Simple enough, right?

3/10/2009 10:59:06 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 

Articles in this series
Part I: Inversion of Control and the Compact Framework
Part II: The OpenNETCF.IoC Framework: Items and Services (this article)
Part III: The OpenNETCF.IoC Framework: Events
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


The OpenNETCF.IoC Framework

 

Since I don’t expect that everyone has used the SCSF and since the OpenNETCF IoC framework is a very small subset, let’s walk through what it is and how it works.  First, the OpenNETCF.IoC framework is based on the concept of “Components.”  A Component is simply an instance of a class and our framework has two flavors of Components: an Item and a Service.  Generally speaking, the difference between an Item and a Service is that an Item is a uniquely-named instance of a Type (so you can have any number of them provided each instance has a unique name) whereas there can only be one Instance of a service per registered type (it acts somewhat like a Singleton).

Both Items and Services are contained as collections in a root container called the RootWorkItem (a name that comes from the CAB framework).  Let’s take a look more in depth at each of these components and how you might use them together.  For this example we’ll get a little more concrete that the Cars and People example from before, and instead look at classes more actual applications might use.

Items

As I mentioned, Items are simply uniquely named instances of objects.  They can be of any Type – the Items collection doesn’t need to contain only a set of a specific type.  The Items are contained, conveniently enough, in the RootWorkItem.Items collection.  So exactly what advantages to we gain by putting our items in this collection?  The primary benefit is that the RootWorkItem becomes an instance manager and, as we’ll see in a little bit, it can also be a factory.

Let’s assume that our application contains the following Forms: MenuForm, EntryForm and SettingsForm and to make things simple, we’ll assume that they are named with their type name.  If we have these forms in the IoC framework, then any time we need to reference one of them we can simply do something like this:

desiredForm = RootWorkItem.Items[“EntryForm”];

and ta-da, we get the instance of the Form.  We don’t need to pass around a reference to it or store it in some other application global location.  So that’s pretty useful right there.  But the RootWorkItem really is just an application global, right, so it must provide some other benefit.  Well it’s also a factory.  If we want to create the entry form we can use a basic create-and-insert mechanism like this:

EntryForm form = new EntryForm();
RootWorkItem.Items.Add(form, “EntryForm”);

But that really isn’t all that interesting.  Where it gets interesting is that you can let the framework do the construction for you by simply giving it a Type and name (the name is actually optional, as the framework will assign it a GUID if you don’t provide one):

RootWorkItem.AddNew<EntryForm>(“EntryForm”);

That’s handy.  No need to call the object contructor to get an instance and then stuff it into the collection.  Less code is always a good thing.  But what else can it do (right now I’m feeling a bit like Ron Popeil)?

Well that’s not all!  Where it gets fun is in its ability to do injection.  This requires a little more complex of a scenario.  Let’s assume that the MenuForm requires an instance of both an EntryForm and a SettingsForm.  Something like this:

class MenuForm
{
  public MenuForm(EntryForm entryForm, MenuForm menuForm) {…}
}
 

Well the OpenNETCF.IoC framework can actually do these injections for you – all you have to do it provide it a little direction with attributes.  If we simply decorate the constructor with the InjectionConstructor attribute, the framework will search the Items collection for existing items of the proper type to inject.  So the MenuForm looks like this:

class MenuForm
{
  [InjectionConstructor]
  public MenuForm(EntryForm entryForm, MenuForm menuForm) {…}
}

And construction now looks like this:

RootWorkItem.AddNew<SettingsForm>(“SettingsForm”);
RootWorkItem.AddNew<EntryForm>(“EntryForm”);
RootWorkItem.AddNew<MenuForm>(“MenuForm”);

And the magic of the OpenNETCF.IoC framework will inject the first two instances into the third.  An interesting note here is that the Injection Constructor does not have to be public.  The OpenNETCF.IoC framework looks for internal and private constructors as well so you can actually create objects that can only be generated via injection if you wish.

Of course the framework also supports Injection Methods as well, in the event that an InjectionConstructor doesn’t meet your needs:

class MenuForm
{
  public MenuForm() {…}

  [InjectionMethod]
  void InjectEntryForm(EntryForm entryForm) {…}

  [InjectionMethod]
  void InjectSettingsForm(SettingsForm settingsForm) {…}
}

But wait, there’s more!  In the examples so far the RootWorkItem.Items collection must contain the SettingsForm and EntryForm before the MenuForm is created.  Well what if we are lazy and don’t even want to do that?  Well the OpenNETCF.IoC framework can handle that too.  Just add the CreateNew attribute like this:

class MenuForm
{
  [InjectionConstructor]
  public MenuForm([CreateNew]EntryForm entryForm, [CreateNew]MenuForm menuForm) {…}
}

And the framework will create a new instance of the Type if it can’t find it in the Items collection. Construction of all three objects and injecting them now looks like this:

 

RootWorkItem.AddNew<MenuForm>(“MenuForm”);

Extremely simple and clean.

Services

The RootWorkItem also contains a collection of Services.  A Service is very similar to an Item except for the fact that there can only be one service of any given registered type (we’ll covered what “registered” means in a moment).  The collection provides a very similar set of methods and attributes as items.  Again, let’s consider a more concrete example.  Assume your application has a class that handles reading and setting configurations.  There really would only be one instance of this class and in a lot of classic cases people would use the global-wrapped-in-a-new-name called a Singleton.

In the OpenNETCF.IoC framework this would be a service.  Since there can only be one pre registered type, there’s no need to name a Service – the registration type becomes the identifier.  So as a simple construct/add/retrieve a Service operation would look  like this:

Configuration config = new Configuration();
RootWorkItem.Services.Add<Configuration>(config);

Configuration retrievedConfig = RootWorkItem.Services.Get<Configuration>();

As with the Items collection, there is a lot more power and convenience in the framework.  First, we can have the framework do construction for us:

RootWorkItem.Services.AddNew<Configuration>();

Like the Items collection, InjectionConstructor or InjectionMethod attributes can be used to control which constructor for the service class gets called.

The OpenNETCF.IoC framework also offers lazy loading of services, so the service instance isn’t actually created until it is first accessed (instead of when it’s added).

RootWorkItem.Services.AddOnDemand<Configuration>();

We saw earlier that the OpenNETCF.IoC framework would walk the Items collection looking for instances to use during injection.  Well what if an object depends on a Service rather than another Item?  The framework also provides a mechanism for that as well using the ServiceDependency attribute.  So to inject a Service into a consumer class using Constructor Injection it would look like this:

class ServiceConsumer
{
  [InjectionConstructor]
  public ServiceConsumer([ServiceDependency]Configuration config) {…}
}

And of course there is a way to do setter injection instead of constructor injection.  Here it injects into a property instead of using a method like the Items collection:

class ServiceConsumer
{
  public ServiceConsumer() {…}

  [ServiceDependency]
  public Configuration Config { set; get; }
}

And if you want the framework to construct the service if it doesn’t already exist, you simply set the EnsureExists member of the ServiceDependency attribute like this:

[ServiceDependency(EnsureExists=true)]
public Configuration Config { set; get; }

The only other aspect of a Service that an Item does not have is a “registration type”.  This allows you to register a service instance as a type other than its actual base type.  For example you may have a Configuration class that you want to register as a service, but you want to register it as an IConfiguration (this would allow consumers to extract the service by the interface type without ever knowing about or having a reference to the concrete implementation).


Up next: The OpenNETCF.IoC Framework: Event Publication and Subscription

3/10/2009 9:17:43 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [4]  | 
 Monday, March 09, 2009

Articles in this series
Part I: Inversion of Control and the Compact Framework (this article)
Part II: The OpenNETCF.IoC Framework: Items and Services
Part III: The OpenNETCF.IoC Framework: Events
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


Introduction

 

Periodically the software industry goes through a shift in underlying programming practices.  In the 80s the shift was from procedural code to object oriented.  In the 90s we saw the rise of things like “extreme” and “agile” programming.  Recently I’ve seen a shift toward using dependency injection (DI) and inversion of control (IoC).  They’ve been around long enough now that I think they’ll stick, and since any programmer should try to maintain some level of understanding of the latest technologies, I decided to dive into them.

What came out of my investigation were the following:

1.       I was already doing a lot of the stuff, I just didn’t know it

2.       That there really isn’t a reasonable framework in existence for the Compact Framework

3.       Dependency Injection and Inversion of Control, when followed well, can greatly improve extensibility, maintainability and testability of code.

4.       My own IoC framework

Definitions

Before we can talk about all of the benefits of using a framework for Dependency Injection and Inversion of Control, we really need to define them. 

Dependency Injection

Though the name sounds complex, Dependency injection really is what the name implies and is really simple, but explaining it in abstract terms tends to get convoluted.  For example, it could be defined as “with dependency injection you inject dependent objects into the object which depends on them.” Doesn’t really roll of the tongue, does it?  I read that I tend to see “blah, blah, object, blah, depend, blah” and want to move on to something else altogether.  But really, it is simple.  So let’s use an actual example and a picture.

Let’s say we have a couple classes,  Car and Person, and a person can own and drive a car. So it’s something like this:

class Car
{
  public Car() {…}
}

class Person
{
  private Car m_car;

  public Person() {…}

  public void Drive () {…}
}

Now the question here is how does the Drive method “get” or “know” what car to Drive?  One way would be to have the Person instance create the car along these lines:

 

 

public Person()
{
  m_car = new Car();
}


 

So the Person class knows what its dependency is.  It knows at compile time that it needs a Car and creates it.  That’s all well and good, and sure, it work, but it’s certainly not extensible.  To make it a little more extensible, we could use an interface for the Car instead:

 

class Person
{
  private ICar m_car;

  public Person()
  {
    if(this.IsAMoparGuy)

      m_car = new ShinyDodgeChallenger();
    else
      m_car = new RustBucket();
  }
}

 

This is a bit more extensible – the Person has some opportunity to decide what type of car it wants, but it still puts that decision in the Person class and the Person class still has to know about the concrete types of Car. So how do we make it even more extensible so that Person needs to only know about the interface?  Simple – we pass in the object.  That can be done, generally speaking, in two ways.  Either in the constructor:

 

class Person
{
  private ICar m_car;

  public Person(ICar car)
  {
    m_car = car;
  }
}

Or using a method to set it:

 

class Person
{
  private ICar m_car;

  public Person() {}


  public SetCar(ICar car)
  {
    m_car = car;
  }
}

It’s very likely that you’ve used patterns like this in the past, and in fact these are dependency injection.  The first is called “constructor injection” and the second is called “method injection.”  I’ve also seen references to “property injection” which you can probably guess sets the dependency using a Property instead of a method, but a Property really is nothing more than syntactic sugar around a pair of methods.  If you really want to consider it separate, then we can lump the Property and Method injections into something I’ll call “setter injection.”

Inversion of Control

Inversion of Control is a lot like Dependency Injection in that the name puts me off immediately because it sounds like an attempt to use overly large words to describe a likely simple thing, and indeed it is.  In “old school” programming you might have an object (like a Person) that controls another object (like a Car) and when you want to know if some state has changed, you simply query it.

So the Person instance might do something like this

if(m_car.HasCrashed) Call911();

Well Inversion of Control simply turns that around.  Instead of us asking the object for state, the child object (the Car in this example) will inform us of a change.  Sound familiar?  .NET events and delegates are a classic, and really often used, case of Inversion of Control.

So you might hook it up like this

m_car.OnCrash += new CrashHandler(
    delegate { Call911(); }
  );

It’s nothing more complex than that.

IoC and the Compact Framework

When I started out looking into IoC and DI, I was a little put off.  I dislike following programming fads or chasing after some technology simply because it’s all the rage and there are conferences touring the country talking about them.  But I was working on a desktop project and a friend said that I should check out Microsoft’s Smart Client Software Factory (or SCSF) as he thought it would be a good framework to achieve the goals we were after.

Well it turns out that SCSF is built on Microsoft’s Composite UI Application Block (also called CAB) and together they really are just a library that provides a very robust IoC framework.  I’m currenly working on porting that desktop project to use the SCSF and it’s turning out to be very, very useful.

When I needed an IoC framework for the CF, I found that Microsoft’s Patterns and Practices team ported the CAB/SCSF framework a few years back.  I also quickly found out that the people who did the port appeared to do a literal port of the code.  So while it compiles and runs, it certainly does not take into consideration the limited memory and processor power of a typical Windows CE device.  A very common complain about the Mobile Client Software Factory is that its performance sucks.  And I can attest to that.  It does suck.

So what to do?  There are a couple (and really only two that I could find) IoC frameworks that claim to be CF compatible.  I looked at them briefly, but I pretty quickly abandoned them because I really don’t feel like learning the object model for a whole new framework.  I’m using the SCSF and I’m comfortable with it, and I don’t like having to constantly have to think about object models depending on what my code targets.  I also like to keep my code as reusable as possible, and changing frameworks certainly wouldn’t help on that front.

So what I decided to do was to build my own framework based, mostly, on the object model of the SCSF.  The goal was to implement only the bare minimum of what I needed and to build it specifically considering that it would be used on CE devices. What I ended up with is a simple, lightweight dependency injection framework that I called OpenNETCF.IoC. 


Up Next: The OpenNETCF.IoC Framework: Items and Services

3/9/2009 2:48:36 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [7]  | 
 Monday, January 12, 2009
No idea why the CF omitted the GetCultures method.  The info it returns is clearly supported in the OS, and it's not like it's a lot of work (plus if you're doing globalization, it really is helpful.

Here's a quick implementation I put together this morning that we'll likely add to the SDF:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;

namespace OpenNETCF.Globalization
{
  public class CultureInfoHelper
  {
    private delegate int EnumLocalesHandler(string lpLocaleString);
    private static EnumLocalesHandler m_localesDelegate;
    private static List<CultureInfo> m_cultures;

    private static int EnumLocalesProc(string locale)
    {
      try
      {
        m_cultures.Add(CultureInfo.GetCultureInfo(
        int.Parse(locale, NumberStyles.HexNumber)));
      }
      catch
      {
        // failed for this locale - ignore and continue
      }

      return 1;
    }

    public static CultureInfo[] GetCultures()
    {
      if (m_localesDelegate == null)
      {
        m_cultures = new List<CultureInfo>();
        m_localesDelegate = new EnumLocalesHandler(EnumLocalesProc);
        IntPtr fnPtr = Marshal.GetFunctionPointerForDelegate(
              m_localesDelegate);
        int success = EnumSystemLocales(fnPtr, LCID_INSTALLED);
      }

      return m_cultures.ToArray();
    }

    private const int LCID_INSTALLED = 0x01;
    private const int LCID_SUPPORTED = 0x02;

    [DllImport("coredll", SetLastError = true)]
    private static extern int EnumSystemLocales(
    IntPtr lpLocaleEnumProc, uint dwFlags);
  }
}


1/12/2009 1:22:58 PM (Eastern Standard Time, UTC-05:00)  #    Comments [4]  | 
 Wednesday, December 03, 2008
Calling Control.Invoke tends to be a problem, especially for developers who are new to the .NET world.  I think the primary struggle is how to call Invoke without writing a custom delegate, creating a member variable and/or some helper methods.  Here are a couple patterns that I use pretty regularly:

Using an anonymous delegate

if (this.InvokeRequired)
{
   this.Invoke(new EventHandler( delegate (object o, EventArgs a)
   {
     // do your work here
   }));
}
else
{
  
// do your work here
}

Reusing the existing EventHandler

void MyEventHandler(object sender, EventArgs e)
{
   if (this.InvokeRequired)
   {
     this.Invoke(
       new EventHandler(MyEventHandler), new object[] { sender, e }
     );
     return;
   }

   // do your work here
}


12/3/2008 12:12:37 PM (Eastern Standard Time, UTC-05:00)  #    Comments [2]  | 
 Monday, October 20, 2008
As with most developers, I have a large pool of code snippets from work, tests and investigations I've done in the past.  Sometimes these grow into products, other times they just sit on a hard drive waiting for a time for me to actually use them.

Over the coming weeks I plan to blow the dust off of some of these and see what looks worthwhile.  Simple stuff might get rolled into the SDF (I rolled in a keyboard hook a couple weeks ago) and some stuff will get pushed out as open source libraries because we simply don't need any more products generating any more support load on us at the moment.

Hopefully we'll come up with a coherent place to put all of these in the near future, but for now I'll just post them here on my blog.

The first is the series is called POOMHelper.  I put this together back when WinMo 5.0 first came out while doing work that required that I detect when a POOM item was modified or deleted.  It's a fairly straightforward piece of code that hooks into the eventing mechanism of POOM, plus it also allows you to set some properties of POOM items (mostly Contacts IIRC) that didn't exist in the POOM object model at the time (they may have since been added).

Here's what the public object model looks like:

POOMHelper.PNG

The code is released under our MIT X11 license, so do with it what you wish.  If you need support or help, we offer consulting services.

Download the POOMHelper source here
Download the Interop.PocketOutlook.dll assemly(64 KB) here.
10/20/2008 10:44:21 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Wednesday, August 13, 2008
Today I saw two separate posts on pretty much the same question.  How can you determine if the foreground window changes in a WinMo application?  Moreover, how can you determine if the new foreground window is your own, or in some other process?  My initial thoughts were to do some work in the Form's Deactivate event, but that would lead to having to plumb it into every Form, and then you'd still need special case handlers for MessageBoxes and Dialogs and it would be an unmaintainable pain in the ass. I decided to put some time aside this afternoon and see if I could come up with a better solution, and what I came up with is outlined in a new article entitled 'Determining Form and Process Changes in Windows CE'.

8/13/2008 6:14:58 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Friday, August 01, 2008
It seems that every time I work on a project I get near the end and have to deal with actual deployment of the application and things go south.  Let's face it, Microsoft's wceload application sucks - and that's being generous. It's limited, it's got no object model, and it's behavior has changed over time without any of those changes being documented.

In a recent project I was trying to silently install an application to a directory that would change depending on the target hardware becasue different devices have their storage media named differently.  I wanted to do this without changing or having multiple CAB files, since the application was no different. Achieving this with wceload, I am convinced, is utterly impossible so I put on my reverse-engineering hat, downloaded the CAB spec (cabfmt.doc), and went to work.  Now, a few month later, and with the help of Alex Feinman, we've created a new product called the Windows CE CAB Installer SDK.  In addition to a new product, we went with a new pricing model as well.

The SDK comes with full source,  unit and integration tests designed for running under mstest, samples for generating compressed and uncompressed CAB (the SDK supports both), a template for creating custom installer DLLs and both VB and C# examples of using the SDK.

The main workhorse of the SDK is the WinCEInstallerFIle class, which looks like this:



An example of a custom installer looks like this (just to give you a flavor of how it works):

using System;

using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using OpenNETCF.Compression.CAB;

namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute
{
}
}

namespace ONCFInstall
{
public delegate void FileProgressHandler(int progressPercent);

public static class Extensions
{
public static string Find(this List list, string findString)
{
foreach (string file in list)
{
if (string.Compare(file, findString, true) == 0)
{
return file;
}
}
return null;
}
}

public class CustomCABInstaller : WinCEInstallerFile
{
private int m_fileCount = 0;
private CommandLineArgs m_args;

public event FileProgressHandler FileProgress;

public CustomCABInstaller(string cabFileName, CommandLineArgs args)
: base(cabFileName)
{
m_args = args;
SkipFileNames = m_args.SkipFiles ?? new List();
PathStringReplacements = m_args.PathStringReplacements ?? new Dictionary();
SkipOSVersionCheck = m_args.SkipOSVersionCheck;
}

/// /// List of file names to skip during installation /// public List SkipFileNames { get; set; }

/// /// List of path replacement strings /// public Dictionary PathStringReplacements { get; set; }

/// /// If true, the installer will not check to ensure the target meets the installer's version requirements
///
public bool SkipOSVersionCheck { get; set; } public override void OnInstallBegin() { m_fileCount = 0; } public override void OnTargetOSVersionCheck() { // check to see if we should skip the OS version check if (!SkipOSVersionCheck) { base.OnTargetOSVersionCheck(); } } public override void OnInstallFile(ref FileInstallInfo fileInfo, out bool skipped) { // check to see if it's a name we should skip if (SkipFileNames.Find(fileInfo.FileName) != null) { Utility.Output(string.Format("Skipping file '{0}'", fileInfo.FileName)); skipped = true; return; } // do any path replacements foreach (KeyValuePair val in PathStringReplacements)
{
fileInfo.DestinationFolder = fileInfo.DestinationFolder.Replace(val.Key, val.Value);
}

Utility.Output(string.Format("Installing '{0}' to '{1}'", fileInfo.FileName, fileInfo.DestinationFolder));

base.OnInstallFile(ref fileInfo, out skipped);

if (FileProgress != null)
{
FileProgress((++m_fileCount * 100) / FileCount);
}
}
}
}

8/1/2008 3:42:52 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [3]  | 
 Monday, May 19, 2008
We've published a new article on the OpenNETCF Community Site titled "Native vs. Managed Code: GDI Performance"
 
 
In it, I look at the performance differences between native and managed code making GDI calls.
 
In case you missed them, our other recently published articles include:
 
- Performance Implications of Crossing the P/Invoke Boundary
- An Introduction to WCF for Device Developers
- Getting a Millisecond-Resolution DateTime under Windows CE
- Using GDI+ on Windows Mobile
- Sharing Windows Mobile Ink with the Desktop
- OpenNETCF Mobile Ink Library for Windows Mobile 6
- Improving Data Access Performance with Data Caching
- Developing Connected Smart Device Applications with sqlClient
- Debugging Without ActiveSync
- Image Manipulation in Windows Mobile 5.0
- Don't Fear the Garbage Collector
 
All of our articles are available online at:
http://community.OpenNETCF.com/articles
 
5/19/2008 12:27:16 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Friday, April 18, 2008

Ever since learning how to use function pointers in C, I've always been a fan of using them to help make code a bit more usable, especially when you've got a state machine.  Today, as I'm working on a Wizard UI for a desktop application I came across a typical scenario for using a function pointer.  Depending on the stage of the Wizard you're in, a button will have to do separate things.

That got me to thinking that most managed developers simply don't understand the power and utility of delegates, but instead simply consider them a necessity when using Control.Invoke or creating custom events. Sure, in my case I could have a switch statement in the click handler and do logic there, or I could unhook the click handler from one method and hook it to another, but those all seem ugly and a pain in the ass to me.  A simple function pointer change is all you need.  So I decided I'd throw together a really simple example of how you would use a delegate to change the behavior of a Button click.

Let's assume that we have a button that we want to click, and when it's clicked it will do one of 4 things, depending on the state of our application.  We'll just use a messagebox here to give you the idea - what it does is up to you- it's a function after all.

public void FunctionA()
{
  MessageBox.Show("FunctionA");
}

public void FunctionB()
{
  MessageBox.Show("FunctionB");
}

public void FunctionC()
{
  MessageBox.Show("FunctionC");
}

public void FunctionD()
{
  MessageBox.Show("FunctionD");
}

To simulate the different "states" I simply added a ListBox (called functionList) to the Form and manually added the function names to it in the Form's constructor.  Sure, I could have used Reflection to be clever and populate the list, but I'm tryiong to keep it simple and show delegates.

functionList.Items.Add("FunctionA");
functionList.Items.Add("FunctionB");
functionList.Items.Add("FunctionC");
functionList.Items.Add("FunctionD");

Alright, so now we know that depending on which item is selected, we want to call one of our four functions.  Since they all have the same interface (and they have to to use a delegate) we simply define a delegate that matches them.  This delegate can be privately scoped inside your class.

delegate void FunctionDelegate();

And then we create an instance variable to hold the current function pointer we want to use:

private FunctionDelegate m_functionPointer = null;

We add an event handler for the SelectedIndexChanged event of the ListBox (in the Form constructor)

functionList.SelectedIndexChanged += new EventHandler(functionList_SelectedIndexChanged);

And implement the event handler.  It simply looks at the newly selected index in the list and changes the value stored in m_functionPointer appropriately.

void functionList_SelectedIndexChanged(object sender, EventArgs e)
{
  // determine which function pointer to store based on selection
  switch (functionList.SelectedIndex)
  {
    case 0:
      m_functionPointer = FunctionA;
      break;
    case 1:
      m_functionPointer = FunctionB;
      break;
    case 2:
      m_functionPointer = FunctionC;
      break;
    case 3:
      m_functionPointer = FunctionD;
      break;
    default:
      m_functionPointer = null;
      break;
  }
}

Next we wire up an event handler for our button (again the the Form constructor):

callButton.Click += new EventHandler(callButton_Click);

And finally the magic and simplicity of the state-dependent call

void callButton_Click(object sender, EventArgs e)
{
  // call our function (as long as it's not null)
  if (m_functionPointer != null)
  {
    m_functionPointer();
  }
}

That's all there is to it.  Run the application, select a function and click the button.

Get the full source here.

4/18/2008 6:07:46 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [3]  | 
 Thursday, December 06, 2007

So I picked up a cheap PTZ (pan/tilt/zoom) camera off eBay a couple weeks ago for doing some R&D on a project I'm working on.  My hope was I'd be able to hook it up and talk to it from a device and get streaming video into an app.  Well it turns out that it's not so simple.  All cameras appear to have some form of proprietary interface that obviously varies from OEM to OEM.

I hooked up WireShark in hopes that I could reverse engineer the network commands fromthe packets, but it looks like it would take me weeks to get it figured out, and I don't have that kind of time (or desire) so I shot off an email to the OEM.  While I wait for them to reply (if they ever do) I went about reverse-engineering a kludge.

The device has a built in web server that allows you to control the camera, view video, etc.  So I opened up a page and looked at the source.  It contained a frameset, so I started navigating through frame pages and deconstructing the html to see what commands did what.  Unfortunately the video streaming piece appears to be in a compiled Java applet so getting at that turned out to be a dead-end, however it wasn't a total loss.  I did figure out how to send it commands to pan, tilt and capture single frames (well I figured out a lot more, but I limited my implementation to those functions for now).

So armed with what I knew, I slapped together the following class, basically simulating myself as a browser:

using System;
using System.Net;
using System.Net.Sockets;
using System.Drawing;
using System.IO;
using System.Threading;
using OpenNETCF.Peripherals.Camera;

namespace OpenNETCF.Peripherals
{
  public class MegaTecCamera : ICamera
  {
    private const int CMD_UP = 1;
    private const int CMD_DOWN = 2;
    private const int CMD_LEFT = 3;
    private const int CMD_RIGHT = 4;

    private string m_ip;
    private string m_username;
    private string m_password;

    public MegaTecCamera(IPAddress address, string username, string password)
    {
        m_ip = address.ToString();
        m_username = username;
        m_password = password;
    }

    public Image GetImage()
    {
        Image img = null;

        string command = string.Format(http://{0}/pda.cgi?user={1}&password={2}&page=image&cam=1
            m_ip, m_username, m_password);

        byte[] buffer = new byte[10000];
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(command);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (Stream stream = response.GetResponseStream())
        {
            try
            {
                img = new Bitmap(stream);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Capture failed: " + ex.Message);
            }

            response.Close();
        }
        return img;
    }

    public void Pan(PanDirection direction)
    {
        if (direction == PanDirection.Left)
            SendHttpCommand(GetDirectionCommand(CMD_LEFT));
        else
            SendHttpCommand(GetDirectionCommand(CMD_RIGHT));
    }

    public void Tilt(TiltDirection direction)
    {
        if (direction == TiltDirection.Up)
            SendHttpCommand(GetDirectionCommand(CMD_UP));
        else
            SendHttpCommand(GetDirectionCommand(CMD_DOWN));
    }

    private string GetDirectionCommand(int direction)
    {
        return string.Format(http://{0}/pda.cgi?user={1}&password={2}&page=execute&cam=1&command={3},
            m_ip, m_username, m_password, direction);
    }

    private void SendHttpCommand(string command)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(command);
            try
            {
                request.GetResponse().Close();
            }
            catch { }
        }));
    }
  }
}

The next obvious question is "What the hell do I do with this class that is of any use?"

Well that's the fun part!  I integrated it into a sample page on our demo Padarn server, so we now have images captured from an IP camera streamed back to a 200MHz Windows CE device that in turn serves up those images (and control of the camera) using an ASP.NET server.

The next step I'll add is the ability to turn on and off the light in the room via a web page.

 

12/6/2007 6:15:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  | 
 Thursday, November 29, 2007
In case you missed it, I published a new article on our community site last week on how to get a DateTime.Now equivalent with the milliseconds field filled in.  Read it here.

11/29/2007 11:20:53 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Friday, September 28, 2007
Mark has just published a couple articles with just about everything you could want to know about inking:

Using the OpenNETCF Mobile Ink Library for Windows Mobile 6
Sharing Windows Mobile Ink with the Desktop

9/28/2007 4:37:14 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Thursday, September 06, 2007

So we've already gotten a submission for this month's coding competiton called FlowFx, and I must say it's pretty damned nice.  I'd say this one sets the bar for the quality of what needs to be submitted.

Take a look at the video of the UI in action.

Enter your Windows Mobile or Embedded code for a change to win some cool prizes this month and every month at http://community.opennetcf.com

9/6/2007 6:29:24 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Friday, June 08, 2007

A friend of mine is working on a project that he's been having some major stability problems with.  All of these issues seem to be related with interop to a Sybase database.

After working on and off with him for the past few months, it seems that the root of the problems lie in the fact that a previous developer had written some functions in a "shim" native DLL that calls intoo Sybase, so instead of P/Invoking the Sybase stuff, the developer created a wrapper DLL that he P/Invoked.

After looking at some of the wrapper two things were obvious.  First, the Sybase functions were undecorated C functions, so the shim was unnecessary in the first place, and second, the developer's skill with C are terrible and the shim he created was likely the cause of the problems. So I recommended throwing out the shim, as it was garbage and it was completely unnecessary.

That lead to yet more questions - most notably "how do I marshal X or Y" type things along with "how the hell does one figure this stuff out" and "is this stuff documented anywhere?"  Well other than experience I know of little for figuring it out, and once you get beyond the capabilities of the CF's marshaler I also know of know real documentation.  So I decided I'd put together a fairly simple example of complex marshaling (yes, simple complex).

So first let's look at a typical scenario.  The Sybase stuff often takes in pointers to big, ugly structures.  These structures contain pointers.  Sometimes they are pointers to ASCII strings.  Well instead of wrapping one of these big nasty things, let's create a small representative example that you as a reader can expand upon.

The Native Side

Let's create a native DLL that exports one funtion that takes a fairly easy-to-grasp structure.  The function will simply present a MessageBox with the info.  So here's a structure:

typedef struct MESSAGE_INFO
{
    char *message;
    WORD length;
    DWORD number;
} MESSAGE_INFO;

Note that 'message' is a char *, indicating ASCII.  I'd never write a CE function like this, but this is an example of how to call an existing function, not a best-practices lesson.  Note also that 'length' is only a WORD (2-bytes) making 'number' not DWORD aligned, so there is actually an unused 2 bytes in this thing as well.  Again, I'm trying to show some ugliness that you will see in the wild, not cover how it should be done.

So let's look at the native function just as a reference.  I'll not explain the whole thing as it's simple and the comments should answer most questions:

__declspec(dllexport)
void ShowMessage(MESSAGE_INFO *info)
{
  TCHAR message[512];

  // create a buffer for the Unicode string
  wchar_t *wideString = (wchar_t *)LocalAlloc(LPTR, (info->length + 1) * sizeof(wchar_t));

  // convert the ASCII message to Unicode
  mbstowcs(wideString, info->message, info->length);

  // show a message box with the data
  _stprintf(message, _T("Message: %s\r\nNumber: %i"), wideString, info->number);

  MessageBox(NULL, message, NULL, 0);

  // free the Unicode buffer
  LocalFree(wideString);
}

The Managed Side

Ok, so the native side is pretty straightforward.  It's not ideal from a managed developer's perspective, but let's face it - native developers rarely think of making managed developer's lives easy when they write code.

We need to figure out how to create a MESSAGE_INFO "struct" and pass it in in a format that the API can use it.  First, we can safely rule out letting the CF marshaler handle this.  It would have no clue what to do with this.  We can also rule out creating this as a managed struct.  The interned char * is not blittable, so we'll have to hand-marshal this.  The pointer itself also means we'll have to manage some memory manually too, and that also means "Danger Will Robinson!" as we have the potential for a memory leak.  Don't fear that fact - just be aware of it.

So first, we need to understand what the native DLL is expecting.  It wants a pointer to a struct - so simply put a 4-byte address. At that address will be 12 bytes of data representing a MESSAGE_INFO struct.  The first 4 bytes of that is yet another address.  At that address is ASCII character data.  That's it.  Now lets convert that English to C#.

First we'll create a MESSAGE_INFO class (we choose a class instead of a struct becasue we'll be doing some work internally on it).  In the class we'll define a byte array that holds the 12 bytes that represent a native MESSAGE_INFO as well as some constants for member offsets and lengths for readability:

private const int MESSAGE_PTR_OFFSET = 0;
private const int MESSAGE_PTR_LENGTH = 4;
private const int LENGTH_OFFSET = MESSAGE_PTR_OFFSET + MESSAGE_PTR_LENGTH;
private const int LENGTH_LENGTH = 2;
// DWORD compiler alignment forces an unused 2-byte block here
private const int RESERVED_OFFSET = LENGTH_OFFSET + LENGTH_LENGTH;
private const int RESERVED_LENGTH = 2;
private const int NUMBER_OFFSET = RESERVED_OFFSET + RESERVED_LENGTH;
private const int NUMBER_LENGTH = 4;

public static int StructLength = NUMBER_OFFSET + NUMBER_LENGTH;

// in-memory representation of a native MESSAGE_INFO struct
private byte[] m_data = new byte[StructLength];

So when we call the API, we'll just pass it a byte array (a byte array is already a reference type and will get passes as a pointer) instead of a MESSAGE_INFO struct.  Remember, the native side just wants a 4-byte number.  All of the decorations we use of sturct names and all of that is simply for developer convenience.  As long as we know that our m_data byte array is arranged to match a native MESSAGE_INFO, it will all work.

So our P/Invoke declaration looks like this:

[DllImport("NativeLibrary.dll", SetLastError = true)]
internal static extern void ShowMessage(byte[] messageInfo);

Simple, right?  To call the native API, we simply call ShowMessage with our m_data bytes.  Of course that's a bit ugly and non-managed, so we'll provide an operator to get the m_data without having to expose it explicitly:

// provide an operator to turn a MESSAGE_INFO into a byte array for marshaling
public static implicit operator byte[](MESSAGE_INFO mi)
{
  return mi.m_data;
}

Now we can just call ShowMessage with a managed MESSAGE_INFO instance and we're done.  So far it's all been pretty simple.  The difficult part is actually populating the m_data bytes with the right info. 

First, let's start with an easy one - the numeric data.  The 'number' member is a publicly exported value, while 'length' is meant to be used internally as the length of the string data.  So let's expose a Number property for the managed MESSAGE_INFO class, with set and get accessors.  Instead of using a private member variable to hold the value, we'll hold it in the m_data array:

public int Number
{
  set
  {
    // copy the "value" bytes to our in-memory representation
    Buffer.BlockCopy(BitConverter.GetBytes(value), 0, m_data, NUMBER_OFFSET, NUMBER_LENGTH);
  }
  get
  {
    // get the number from our in-memory representation
    return BitConverter.ToInt32(m_data, NUMBER_OFFSET);
  }
}

Ok, so now the fun one.  The string.  Since we're passing just a pointer, we need to allocate memory for that pointer to "point to" plus we need to make sure that the GC isn't allowed to move that memory around in the event of a compaction.  There are a few ways to do this, but the "recommended" mechanism is a GCHandle. A fixed unsafe pointer would also work, but it assumes you'll only use C# and that you know a bit more about pointers than you might.

So we'll add a GCHandle private member to the class, plus a byte array for our actual message (the memory that the GCHandle will point to):

// GCHandle for our message string
private GCHandle m_messageHandle;

// byte array for the actual message data
private byte[] m_messageData;

Now we need to expose a Message string property.  In the set accessor we want to take the incoming string and put it's ASCII representation into the m_messageData member, get a GCHandle that points to it as m_messageHandle and then stuff that into our m_data.  We also want to make sure that we don't leak if someone sets the message twice.  The get accessor is a lot simpler - it just converts the m_messageData bytes back to a string. So the Message property looks like this:

public string Message
{
  set
  {
    // see if we already have allocated data
    if (m_messageHandle.IsAllocated)
    {
      m_messageHandle.Free();
    }

    // null check for safety
    if (value == null)
    {
      m_messageData = null;
      return;
    }

    // get the ASCII representation of the passed-in value (plus a null terminator)
    m_messageData = Encoding.ASCII.GetBytes(value + '\0');

    // pin it
    m_messageHandle = GCHandle.Alloc(m_messageData, GCHandleType.Pinned);

    // store the address of the pinned object into our 'struct'
    IntPtr dataPointer = m_messageHandle.AddrOfPinnedObject();
    byte[] pointerBytes = BitConverter.GetBytes(dataPointer.ToInt32());
    Buffer.BlockCopy(pointerBytes, 0, m_data, MESSAGE_PTR_OFFSET, MESSAGE_PTR_LENGTH);

    // store the length
    short length = (short)m_messageData.Length;
    Buffer.BlockCopy(BitConverter.GetBytes(length), 0, m_data, LENGTH_OFFSET, LENGTH_LENGTH);
  }
  get
  {
    // only return a string is something is allocated
    if (m_messageHandle.IsAllocated)
    {
        // create a string, stripping the null terminator
        return Encoding.ASCII.GetString(m_messageData, 0, m_messageData.Length).TrimEnd(new char[] {'\0'});
    }
    else
    {
        return null;
    }
  }
}

Lastly we need to make sure our class itself doesn't leak when it's destroyed.  My solution is simple - a Finalizer:

~MESSAGE_INFO()
{
  // free the GCHandle if necessary
  if (m_messageHandle.IsAllocated)
  {
    m_messageHandle.Free();
  }
  m_messageData = null;
}

Yes, implementing Dispose might be a better way to go, but this is less code, and again we're looking at marshaling, not implementing best practices (and I see nothing wrong with a Finalizer for this anyway).

That's it.  You're done.  When run, you'll get something like this:

Download the full solution source here (note I included several SDKs and built and tested with one you probably don't have, so you might need to hack up the project file if it complains).

6/8/2007 2:18:23 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Wednesday, May 16, 2007

Problem
I have some fairly complex data I want to put into a list.  I'd like to use different fonts, icons and maybe even some custom lines and polygons.  Unfortunately the ListBox control in the CF pretty much sucks for this type of thing.  What can the SDF do for me?

Solution
Yes, the default ListBox control is a bit challenged, but all hope is not lost.  The OpenNETCF.Windows.Forms.ListBox2 follows the desktop model and provides owner-drawn capabilities.  Here are some screen shots of a sample application we have for the ListBox2 as well as some of the OpenNETCF.Net networking classes.

   

As you can see, we're drawing items with different font sizes, colors and weights on both screens, plus we're adding some icons in each item in the second and I have that nice and ugly custom "selected" color.

Download the full sample (NetUI) here.

5/16/2007 7:14:46 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [4]  | 
 Thursday, May 03, 2007

Problem
I've got a text file on the device that's stored in [ASCII/Unicode]. Sure, I can create a System.IO.Stream derivative, read the data and close it, but I'd like something simpler. What can the SDF do for me?

Solution
The OpenNETCF.IO.FileHelper class provides some useful methods to explore.  Take a look at these snippets:

string fileContents;
fileContents = OpenNETCF.IO.FileHelper.ReadAllText("MyASCIIFile.txt", Encoding.ASCII);
fileContents = OpenNETCF.IO.FileHelper.ReadAllText("MyUnicodeFile.txt", Encoding.Unicode);

string[] linesOfTextFile;
linesOfTextFile = OpenNETCF.IO.FileHelper.ReadAllLines("MyASCIIFile.txt", Encoding.ASCII);
linesOfTextFile = OpenNETCF.IO.FileHelper.ReadAllLines("MyUnicodeFile.txt", Encoding.Unicode);

5/3/2007 1:45:49 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Friday, April 20, 2007

Problem A
I have an application that transfers data to another app via (serial/CAN/Ethernet/can-and-string/cheese stream ion a macaroni pipe/whatever).  I have set up a send and acknowlege paradigm so I know when the receiver has all of the data, but I need to know that what the other end received is correct.  What does the SDF do for me?

Problem B
I have an application that receives a file from a native application.  The application send me a 'checksum' along with the data and the native guys tell me that I must use that checksum value to make sure that the data I received has not been corrupted.  I vaguely understand what a checksum is, but I have no clue how to calculate one from the file.  What does the SDF do for me?

Solution
[Tested on a custom PXA270-based Windows CE 5.0 device *and* the desktop (full framework 2.0)]

Nicely enough, the SDF solves both of these with the use of the OpenNETCF.CRC class. The CRC (short for Cyclic Redundancy Check) class supports generating a CRC for a byte array or a FileStream.

Here's what usage for a file looks like.  This creates a 32-bit checksum (we support 8-64 bit) using a standard ploynomial (we support any custom polynomial too):

FileStream fs = File.OpenRead(sourceFileName);
uint checksum = (uint)OpenNETCF.CRC.GenerateChecksum(fs, 32, (ulong)OpenNETCF.CRCPolynomial.CRC_CCITT32);
fs.Close();

 

4/20/2007 2:40:28 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Wednesday, January 10, 2007

Bugs are frustrating, but when you write code for a living you expect them and live with them as a fact of life.  They are a lot harder to swallow when they are introduced by other libraries, especially when those libraries work counter to what you would expect.  It's even more frustrating when it's in a library like the Compact Framework itself.

Recently we got a bug report for our ConnectionManager in some code that I know we tested - basically the Description returned by the DestinationInfo class was returning odd data and concatenating to it did bad things.  Experience told me that it sounded like the data coming back from the native API was not getting properly truncated at a NULL.  Not an unusual mistake, so I went to find it.

Description = Marshal2.PtrToStringUni(baseAddr, 16, 256);
int nullPos = Description.IndexOf('\0'
);
if (nullPos > -1) Description = Description.Substring(0, nullPos);

The bad news was the code looked right - we were looking for NULL and trimming at it.  The only way a problem could arise is if the buffer was non-zero at the start.  So off to look at that code.  Here's where the allocation is made:

hDestInfo = Marshal.AllocHGlobal(DestinationInfo.NativeSize);

Again, it looked right.  However, talking with Alex Feinman he said that the Marshal Alloc functions do no zero memory.  In the earlier versions of this code we used our internal MarshalEx, which P/Invoked LocalAlloc with the LPTR parameter, which zeros everything at allocation.  Why the hell the CF doesn't do that one can only guess, but it makes no sense in my book.  Who would want to allocate memory and not zero it?  Worse still is that MSDN doesn't say that the memory is not zeroed.

So then, changing from our MarshalEx function to the CF's Marshal function introduced an error.  So how do we fix it?  There's no CF equivalent to a memset (again, this is a WTF in my book, but there are a few language limitations like this that irritate me - try taking an IntPtr and turning the data at that location into a managed struct without having to copy it).

So anyway, I looked at coredll.def from Platform Builder 5.0 to see if coredll.dll helps, and sure enough I see this:

malloc @1041
calloc @1346
_memccpy @1042
memcmp @1043
memcpy @1044
_memicmp @1045
memmove @1046
memset @1047

P/Invoke to the rescue.  I added the following to the SDF (so it will be in the next release).  Note that wile I was there I handles the annoyances of not having a way to copy from an IntPtr to an IntPtr (memcpy) or a way to validate IntPtrs (IsBad[Read/Write]Ptr) while I was at it.

public static void SetMemory(IntPtr destination, byte value, int length)
public static void SetMemory(IntPtr destination, byte value, int length, bool boundsCheck)
public static void Copy(IntPtr source, IntPtr destination, int length)
public static void Copy(IntPtr source, IntPtr destination, int length, bool boundsCheck)
public static bool IsSafeToWrite(IntPtr destination, int length)
public static bool IsSafeToRead(IntPtr source, int length)

Then a simple fix back in the ConnectionManager:

hDestInfo = Marshal.AllocHGlobal(DestinationInfo.NativeSize);
Marshal2.SetMemory(hDestInfo, 0, DestinationInfo.NativeSize, false);

 

1/10/2007 9:51:46 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Monday, January 08, 2007

There's a thread in the newsgroups where someone is trying to show a Notification before his app does some long-running process. Here's an example of how it's done.

  1. Create a WM 5.0 Windows app, then add a reference to 'Microsoft.WindowsCE.Forms'.
  2. Add a single Button to the Form and name it 'workButton'
  3. Add this to the top of the code page:

    using System.Threading;
    using Microsoft.WindowsCE.Forms;

  4. Replace the entire non-designer Form class code with this:

    public partial class Form1 : Form
    {
      public Form1()
      {
        InitializeComponent();
        workButton.Click += new System.EventHandler(workButton_Click);
      }

      delegate void EventDelegate();

      Notification m_workNotify = new Notification();
      Control m_invoker = new Control();
      EventDelegate m_workCompleteDelegate;

      private void workButton_Click(object sender, EventArgs e)
      {
        // disable the button so it can't be clicked again until work is done
        workButton.Enabled = false;
        m_workCompleteDelegate = new EventDelegate(OnWorkComplete);

        Thread workThread = new Thread(new ThreadStart(WorkProc));
        m_workNotify.Text = "I'm doing important stuff";
        m_workNotify.Caption = "Please wait...";
        m_workNotify.InitialDuration = 5;

        m_workNotify.Visible = true;

        workThread.Start();
      }

      void OnWorkComplete()
      {
        // re-enable the button
        workButton.Enabled = true;
      }

      void WorkProc()
      {
        // simulate working
        Thread.Sleep(20000);
        m_invoker.Invoke(m_workCompleteDelegate);
      }
    }

1/8/2007 2:51:27 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Wednesday, December 06, 2006

We got a request today from someone wondering if the SDF would help send a Wake-on-LAN or Magic Packet.  Well I've never had to do it before, so I looked it up on Wikipedia. The short answer is no, but that's because all of the required pieces are already there in the CF.

Here's my guess on it - keep in mind that I don't have a WOL-capable PC lying around to test this with (if you test it and can confirm if it does or does not work, by all means let me know).

UPDATE (Dec 7, 06): Alex Feinman took the time to test the original code and the broadcast didn't work.  The code has been updated with working, tested code.

/// <summary>
/// Wakes a remote PC
/// </summary>
/// <param name="targetMAC">MAC address of target. Must be 6 bytes and MUST be in network order (reversed)</param>
/// <param name="password">Optional password. Must be null or 4 or 6 bytes.</param>
public static void WOL(byte[] targetMAC, byte[] password)
{
  // target mac must be 6-bytes!
  if (targetMAC.Length != 6)
  {
    throw new ArgumentException();
  }

  // check password
  if((password != null) && 
      (password.Length != 4) && 
      (password.Length != 6))
  {
    throw new ArgumentException();
  }

  int packetLength = 6 + (20 * 6);
  if (password != null)
  {
    packetLength += password.Length;
  }

 
byte
[] magicPacket = new byte[packetLength];

  // has a 6-byte header of 0xFF
  byte[] header = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
  Buffer.BlockCopy(header, 0, magicPacket, 0, header.Length);

  // repeat the destination MAC 16 times

  // your MAC *is* in network (reverse) order, right??
 
int
offset = 6;
  for(int i = 0 ; i < 16 ; i++)
  {
    Buffer.BlockCopy(targetMAC, 0, magicPacket, offset, targetMAC.Length);
    offset += 6;
  }

  if (password != null)
  {
    Buffer.BlockCopy(password, 0, magicPacket, offset, password.Length);
  }

  IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, 9);
  UdpClient c = new UdpClient();
 
c.Send(magicPacket, magicPacket.Length, ep);
}

12/6/2006 5:29:35 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Friday, August 25, 2006

If you read much of what I write, you know that performance is something I like to always keep in mind, and I'm also a big fan of quantitative analysis.  It all started ages ago with a look at the real time capabilities of Windows CE, but most recently I've been looking at managed code.  This entry is the second in a series of looks at performance of managed code, specifically the .NET Compact Framework.  For the first entry, see this blog entry (which became this MSDN article).

Act II - Method calls are Expensive (or Stay in the Shallow End of the Stack!)

As with many of my diatribes into technical problems, this all started with a newsgroup post.  SOmeone posted that the had done a Towers of Hanoi implementation in VB.NET, C# and C++ and that the C# implementation was faster than VB, but got slower in CF 2.0.  They also said that native code was much faster than both (I think he may have said an order of magnitude, but don't quote me on that).

Well he didn't post any code so we could reproduce his results, and I never take anyone on their word on something like this, so I decided to put it to the test.  Before going any further, you may need some background information on what the Towers of Hanoi problem is.  You're probably familiar with it - you just didn't know what it was called.  Go read this Wikipedia entry and come back.

I decide to do a recursive solution, so the meat of the problem is that we have an exponential number of method calls, making the call stack very, very deep.  Just from a memory point of view this is a bad idea (see my MEDC presentation on memory management if you want to know more on the whys of that).  But you'll also see that the expense of method calls in the CF (see Act I) really bites you here as it bites hard.

First, let's look at the code.  In C#, it looks like this:

public class Hanoi
{
  private int[] pegs = new int[3];

  public Hanoi(int totalDisks)
  {
    // start with all disks on peg 0
    pegs[0] = totalDisks;
    pegs[1] = 0;
    pegs[2] = 0;
  }

  public int Solve()
  {
    int et = Environment.TickCount;
    Move(0, 2, 1, pegs[0]);
    return Environment.TickCount - et;
  }

  private void Move(int fromPeg, int toPeg, int intermediatePeg, int disks)
  {
    if(disks == 0) return;

    // move all but one disk to the intermediate peg
    Move(fromPeg, intermediatePeg, toPeg, disks - 1);

    // move the last remaining disk to the destination - no need for the intermediate
    pegs[fromPeg] -= 1;
    pegs[toPeg] += 1;

    // now move all but one off the intermediate peg to the destination peg
    Move(intermediatePeg, toPeg, fromPeg, disks - 1);
  }
}

You can see that Move calls itself twice.  Now try tracing the code in your head if I call Solve when totalDisks is 30.  Ugly.

Now lets look at the C++ implementation.

class Hanoi
{
    private:
        int pegs[3];
        void Move(int fromPeg, int toPeg, int intermediatePeg, int disks);

    public:
        Hanoi(int totalDisks);
        int Solve();
};

Hanoi::Hanoi(int totalDisks)
{
    // start with all disks on peg 0
    pegs[0] = totalDisks;
    pegs[1] = 0;
    pegs[2] = 0;
}

void Hanoi::Move(int fromPeg, int toPeg, int intermediatePeg, int disks)
{
    if(disks == 0) return;

    // move all but one disk to the intermediate peg
    Move(fromPeg, intermediatePeg, toPeg, disks - 1);

    // move the last remaining disk to the destination - no need for the intermediate
    pegs[fromPeg] -= 1;
    pegs[toPeg] += 1;

    // now move all but one off the intermediate peg to the destination peg
    Move(intermediatePeg, toPeg, fromPeg, disks - 1);
}

int Hanoi::Solve()
{
    int et = GetTickCount();
    Move(0, 2, 1, pegs[0]);
    return GetTickCount() - et;
}

You can see that it's really not much different - in fact it's really, really close.  So what do we see for results when we run these? Look at the table below (my device was an Axim X30 with a PXA270 processor)

disks C# - CF 2.0 C++ Diff % improvement
20 744 461 283 38%
21 1518 1148 370 24%
22 2997 2068 929 31%
23 5964 4006 1958 33%
24 11892 7646 4246 36%
25 23942 14875 9067 38%
26 47945 29423 18522 39%
27 95674 58496 37178 39%
28 190917 116837 74080 39%

The C++ version performed nearly 40% better.  Of course the C# JIT compiler is running on a mobile device, with presumably much less power than a desktop machine, so the JITter is built to optimize for compile speed, not execution speed.  To try to level the playing field, I compiled the C++ version in Debug mode to turn off all compiler optimizations.  I can't actually see what the CF JITter creates for assembly, so we can't be sure if the resulting code is the same, but that's the nearest I can come.

So we know that the implementation code is near identical.  We also know from Act I that identical code in a single method has no performance difference between native and managed code.  We also know from Act I that method calls are quite expensive.  A reasonable conclusion then is that the performance degradation we're seeing here is nearly all in the cost of method calls.  Does this mean that managed code performance is terrible?  The answer is "it can be if you don't fully understand what the CLR is doing." The lesson learned here then is to either refactor the algorithm to keep your call stack short (there are non-recursive solutions to this problem - maybe another day I'll test that), or put heavily recursive stuff into a native library and P/Invoke to it.

If you want to try these out on your own device, you can download the source code here (post your results in the comments if you'd like).  The source actually points out another lesson, this time in UI development speed. The C# version has a nice UI that I put together in about 10 minutes.  Writing a nice UI would have taken quite a bit longer in C++ so I didn't even bother. With the C++ version you have to get the results from by running in eVC or Studio and setting a breakpoint in the calling loop and writing down the number after each iteration.

8/25/2006 12:09:58 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Wednesday, August 23, 2006

We've had an idea for a new project for some time, and we've finally decided to put out a code seed for it to see if the community wants to get involved.

The idea is this - Create a native coredll.dll library for the desktop that exactly matches the one exposed by Windows CE (same funtions at the same ordinals).  In theory, this would allow you to run Compact Framework applications against the full framework including code that P/Invokes.  The long-term goal is to implement every funtion (there are about 1800 of them, we've seeded the project with 50), but the milestone I'm shooting for is to get this library to a point that the SDF will run on the desktop.

Why would you want this library you ask?  The answer is fairly simple - to help in debugging and unit testing.  I don't envision you shipping a product that runs on CE and XP, but I do see great value in being able to run your CF assemblies through NUnit or Team Suite unit tests, which today cannot be done on a device.  This project is an enabler for that.

THe project is located at CodePlex as the OpenNETCF Advanced Debugging Toolkit.  Look for more pieces to the toolkit as time progresses.

8/23/2006 2:00:11 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Tuesday, August 22, 2006

The Bitmap class in the Compact Framework is a confusing thing, largely because it has abstracted what the OS is doing underneath a little too far.  For example, look at the following code:

Bitmap bmp1 = new Bitmap(fileStream);
Bitmap bmp2 = new Bitmap(200, 200);

Let's assume that fileStream is a valid stream to a resource bitmap file that is 100x100 in size.  So is there any difference between bmp1 and bmp2, other than the fact bmp1 presumably has some color data in it?  The answer is yes - there's a very big difference, and that difference can have a huge impact on application performace as well as cause exceptions.

So let's look at this a little deeper with some examples.  Here's the first:

int iterations = 0;

while (true)
{
  try
  {
    iterations++;
    Bitmap b = new Bitmap(GetImageStream());
    if (iterations % 100 == 0)
    {
      Debug.WriteLine(string.Format("{0} objects", iterations));
    }
  }
  catch
  {
    Debug.WriteLine(string.Format("Failed after {0} objects", iterations));
    Debugger.Break();
  }
}

If I run this code (GetImageStream() just pulls an image from an embedded resource), the app will run forever, occasionally spitting out the debug port how many hundreds of objects it's created.  If you run RPM on it you'll see memory getting allocated, the GC firing occasionally and resources being freed up.  All is well in the world of managed code and everything is working as expected.  Hooray.

Now let's change that ever so slightly to this:

int iterations = 0;

while (true)
{
  try
  {
    iterations++;
    Bitmap b = new Bitmap(200, 200); // <--- CHANGED HERE
    if (iterations % 100 == 0)
    {
      Debug.WriteLine(string.Format("{0} objects", iterations));
    }
  }
  catch
  {
    Debug.WriteLine(string.Format("Failed after {0} objects", iterations));
    Debugger.Break();
  }
}

Note the single change where the bitmap is created.  Try running this and after a few iterations - the exact number depends on available device memory - it will OOM (throw an out of memory exception).  On the device in front of me it was about 40.

So the first thing to do is theorize why this would happen.  Seems like the Bitmap's resources aren't getting freed after it goes out of scope at the end of the while block.  An explicit call to Dispose() may solve it if that's the case, so let's try another test.

int iterations = 0;

Bitmap b = null;
while (true)
{
  if (b != null)  // explicit disposal
    b.Dispose();

  try
  {
    iterations++;
    b = new Bitmap(200, 200);
    if (iterations % 100 == 0)
    {
      Debug.WriteLine(string.Format("{0} objects", iterations));
    }
  }
  catch
  {
    Debug.WriteLine(string.Format("Failed after {0} objects", iterations));
    Debugger.Break();
  }
}

Sure enough, when we run this, it behaves like the first.  Strange that the Bitmap behaves differently depending on which constructor we use - this is contrary to common sense, right? 

So let's think a little more.  A Bitmap has a large area of unmanaged resources and some managed resources.  It seems that when we create a bitmap using the size ctor, the finalizer doesn't get run when an OOM happens.  Let's test again and see if that really is what's going on. We'll remove the explicit Dispose call and wait for the finalizers and try again when we OOM.

int iterations = 0;

while (true)
{
  try
  {
    iterations++;
    Bitmap b = new Bitmap(200, 200);
    if (iterations % 100 == 0)
    {
      Debug.WriteLine(string.Format("{0} objects", iterations));
    }
  }
  catch (OutOfMemoryException)
  {
    Debug.WriteLine("Waiting for finalizers to run..."));
    GC.WaitForPendingFinalizers();
    Bitmap b = new Bitmap(GetImageStream());
  }
}

When we run this one, again all is well in managed code land, though we see it waiting for finalizers to run a lot, and that catch is an expensive one for perf (as all exceptions are). At this point I think "well that surely has to be a bug" but I often like a second opinion, so I went right to the source and asked the CF team about the behavior.  The response from them is actually quite informative.  Their response in in italics below.

I think you are probably seeing is several interactions that can be quite confusing.

  1. Creating a bitmap using the stream constructor will construct a DIB (Device Independent Bitmap).
  2. Creating a bitmap using the width/height constructor will construct a DDB (Device Dependent Bitmap).
  3. DIB's are allocated out of the virtual address space of the application.
  4. DDB's are allocated by the driver. This typically means that they are allocated in the virtual address space of gwes.exe. Alternatively, the driver could allocate these in dedicated video ram.
  5. Creating a bitmap with the stream constructor will generate a fair amount of garbage as it copies data from one buffer to the other.

When we perform a GC because of an OOM in the stream constructor case, we will almost certainly have some amount of garbage that we can free back to the OS immediately. This will also trigger the finalizer to run on another thread as soon as possible. That should help the next call to bitmap creation.

When we perform a GC because of an OOM in the width/height constructor case, it is fairly likely that the OOM is caused because of virtual memory exhaustion in gwes.exe. Thus freeing memory in our process will not help the memory condition in gwes.exe. We need the bitmap finalizer to run before this would actually free memory in a way that would help this scenario. While the finalizer thread would certainly have been triggered to start, it most likely will not get a chance to free bitmaps before we OOM while trying to allocate a bitmap immediately after triggering a GC on the initial thread.

In short, we have 2 different types of Bitmap in our runtime with varying performance and allocation characteristics. DDBs are generally faster to manipulate and draw to the screen than DIBs, but they are constructed in an external memory space that can cause allocation confusion and cause the performance of calls to LockBits or Save to be slow. If a DIB is desired and you wish to construct it based on width and height, we provide a function that constructs a Bitmap with a width, height, and pixelformat specified. This function will construct a DIB instead of a DDB.

I personally still consider this a bug in the implementation - the CF should catch these occasions and handle it for us rather than OOMing all the way back to the app to wait for the Finalizers and retry - that's an implementation that should be done below us. 

Still the answer sheds light on the fact that how we create a Bitmap should be highly dependent on how we intend to use that Bitmap.

8/22/2006 2:24:50 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [4]  | 
 Thursday, June 29, 2006

Since most people like to try before they buy, we've released Evaluation Versions of our Calendar Controls.  Download the evaluation binaries and a sample project using them here.

6/29/2006 12:37:14 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Tuesday, June 27, 2006

First let me go on record as saying that I think using a 'z' to terminate words is utterly moronic, like using the number 2 instead of the word 'to'.

Anyway, on 2 my skillz....

Last week I posted a fantastic kludge for turning on the Bluetooth radio on an Axim X30.  Well, like any kludge, as soon as it shipped it broke.  Turns out the notification icon isn't always in the rightmost position - it can move.  That screwed with my intricate algorithm of moving in and up 10 pixels from the lower left corner of the screen.

So what's a developer to do?  First, let's take a quick detour into how those icons work. 

They "tray" icons are actually called Notification icons and they are displayed by calling the Shell_NotifyIcon API.  When the icon is created you provide a window handle for it to notify when it's clicked.  The icon itself doesn't have any other abilities.  This is a critical piece of info for this hack.

Since I know it's posting messages to another Window when it's clicked, I simply needed to figure out exactly what it's doing.  Time to break out Remote Spy++ in eVC (are you in the group that never really knew what the hell that tool was used for? This is a classic case).

Loaded up Spy++ and I see a Window conspicuously named "Bluetooth Console" - that's promising.  I put a watch on it and sure enough, when I tap the icon, messages get posted to that window (off is in the blue box, on in the red).  Now all I need to do is post the same messages.

So first, I need the handle for that Window.  Time for the FindWindow P/Invoke:

IntPtr btWindow = FindWindow("WCE_BTTRAY", "Bluetooth Console");

Next, replicate the messages the tap generates:


SendMessage(btWindow, WM_USER + 1, 0x1267, 0x201);
SendMessage(btWindow, WM_USER + 1, 0x1267, 0x202);
SendMessage(btWindow, WM_USER + 1, 0x1267, 0x200);

That causes the Bluetooth Console to create and show the popup menu. Now it needs a message to tell it to wait for a menu tap:

SendMessage(btWindow, WM_ENTERMENULOOP, 0x01, 0x00);

Now "generate" the tap:

SendMessage(btWindow, WM_COMMAND, BluetoothRadioState ? CMD_BT_OFF : CMD_BT_ON, 0x00);

And tell it to quit listening for menu taps:

SendMessage(btWindow, WM_EXITMENULOOP, 0x01, 0x00);

It does something else that I can't tell what the effect is, but since it's doing it, I will too:

// not sure what this does, but physically clicking does it, so replicate it here
SendMessage(btWindow, WM_USER + ((BluetoothRadioState) ? (uint)0xC00D : 0xC00C), 0x01, 0x00);

And finally get the Menu window and hide it:

IntPtr btmenu = FindWindow("MNU", "");

SendMessage(btmenu, WM_DESTROY, 0x00, 0x00);
SendMessage(btmenu, WM_CANCELMODE, 0x00, 0x00);

While it's still ugly, it's a bit cleaner than the original, and much smaller.  This is our new class in its entirety:

using System;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace OpenNETCF.Devices
{
  public static class AximX30
  {
    public static bool BluetoothRadioState
    {
      get
      {
        RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WIDCOMM\BtConfig\General");
        bool currentState = (((int)key.GetValue("StackMode")) == 1);
        key.Close();
        return currentState;
      }
      set
      {
        // see if any action is needed
        if (BluetoothRadioState == value)
        {
          return;
        }

        IntPtr btWindow = FindWindow("WCE_BTTRAY", "Bluetooth Console");

        // pop up the menu
        SendMessage(btWindow, WM_USER + 1, 0x1267, 0x201);
        SendMessage(btWindow, WM_USER + 1, 0x1267, 0x202);
        SendMessage(btWindow, WM_USER + 1, 0x1267, 0x200);

        // give it time to create the menu
        System.Threading.Thread.Sleep(100);

        // find the menu that popped up
        IntPtr btmenu = FindWindow("MNU", "");

        // start the window listening for menu messages
        SendMessage(btWindow, WM_ENTERMENULOOP, 0x01, 0x00);
        // send it the on or off message
        SendMessage(btWindow, WM_COMMAND, BluetoothRadioState ? CMD_BT_OFF : CMD_BT_ON, 0x00);
        // tell it it's done listening
        SendMessage(btWindow, WM_EXITMENULOOP, 0x01, 0x00);

        // not sure what this does, but physically clicking does it, so replicate it here
        SendMessage(btWindow, WM_USER + ((BluetoothRadioState) ? (uint)0xC00D : 0xC00C), 0x01, 0x00);

        // now hide the menu
        if (btmenu != IntPtr.Zero)
        {
          SendMessage(btmenu, WM_DESTROY, 0x00, 0x00);
          SendMessage(btmenu, WM_CANCELMODE, 0x00, 0x00);
        }

        return;
      }
    }

    [DllImport("coredll.dll")]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("coredll.dll")]
    private static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

    private const uint WM_DESTROY = 0x02;
    private const uint WM_CANCELMODE = 0x1F;
    private const uint WM_USER = 0x400;
    private const uint WM_ENTERMENULOOP = 0x0211;
    private const uint WM_EXITMENULOOP = 0x0212;
    private const uint WM_COMMAND = 0x0111;

    private const int CMD_BT_OFF = 0x1001;
    private const int CMD_BT_ON = 0x1002;

  }
}

6/27/2006 3:58:19 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Friday, June 23, 2006

I recently worked on a project that required me to connect to a printer from a Pocket PC with the Widcomm bluetooth stack on it.  Frustrating as it was, one positive thing came from it - I generated a nice start to a set of classes for using High-Point Software's BTConnect.

Of course it means that you'll need to buy BTConnect to use this library without the "evaluation mode" popup, but it abstracts the ugliness of sommand-line parameters away from the developer so you can focus on creating your app.

I've parked the library here:

www.opennetcf.org/shared

6/23/2006 4:31:35 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Monday, June 05, 2006

I may be a little biased because they're ours, but our new Calendar Controls really are the best looking ones I've seen.  You can now add a calendar to your managed app that looks just like the Outlook calendar.

6/5/2006 1:30:35 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 

Seems like it took forever, but we've finally released the SDF 2.0 Extensions for Visual Studio 2005.

For more info on what exatly comes with the new SDF Extensions, click here.

6/5/2006 1:26:58 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Tuesday, May 30, 2006

Just as a mental exercise, today I decided to try to write a single method that would allow me to return information about the currently running assembly as a string.  One method needed to return the copyright info, the company info, etc.

The end result is this simple function:

public string GetAssemblyAttribute<T>(T attributeType) where T:Type
{
    object attribute = Assembly.GetExecutingAssembly().GetCustomAttributes((T)attributeType, false)[0];
    return (string)attribute.GetType().GetProperties()[0].GetValue(attribute, null);
}

And calling it is this easy:

string s = "";

s = GetAttribute(typeof(AssemblyCopyrightAttribute));
s = GetAttribute(typeof(AssemblyCompanyAttribute));
s = GetAttribute(typeof(AssemblyDescriptionAttribute));
s = GetAttribute(typeof(AssemblyProductAttribute));
s = GetAttribute(typeof(AssemblyTitleAttribute));
s = GetAttribute(typeof(AssemblyTrademarkAttribute));

Now why it has to be this ugly I'm not sure, but isn't reflection a hoot!? 

5/30/2006 10:12:52 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Thursday, May 11, 2006

For those who attended any of my sessions at MEDC, below are links to the downloads.

SumoRobot Lab Manual
SumoRobot Sample Code
HeapTest RPM Test App
CF RPM provisioning file for WM 5.0

5/11/2006 6:38:12 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Tuesday, May 09, 2006

In one of the hands-on labs here at MEDC a developer asked how to pass a managed funtion to a native DLL as a callback function.  I promised him a sample, so here's a simple one that shows how to call EnumWindows:

 

public delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);

public partial class Form1 : Form
{
    EnumWindowsProc callbackDelegate;
    IntPtr callbackDelegatePointer;

    [DllImport("coredll.dll", SetLastError = true)]
    public static extern bool EnumWindows(IntPtr lpEnumFunc, uint lParam);

    public Form1()
    {
        InitializeComponent();

        callbackDelegate = new EnumWindowsProc(EnumWindowsCallbackProc);
        callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);

        EnumWindows(callbackDelegatePointer, 0);
    }

    public int EnumWindowsCallbackProc(IntPtr hwnd, IntPtr lParam)
    {
        System.Diagnostics.Debug.WriteLine("Window: " + hwnd.ToString());

        return 1;
    }
}

5/9/2006 8:44:10 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Thursday, February 23, 2006

If you're building a CE image and want to include CF 1.0 or CF 2.0, then it's pretty simple - just drag the component from the catalog into your workspace.  But what if you don't want to include the CF at all, but still have the plumbing there so your end-user can install the CF themselves and have it work?  One could look through the cesysgen.bat files and decipher what needs to be set or, if you're lazy like me, you could ask the CF team.

Here's the answer, courtesy of Jim Suplizio:

The appropriate support sysgen will have to be added to the image depending on what version of CF is going to be installed.

  • SYSGEN_DOTNET_SUPPORT is the CF 1.0 support sysgen.
  • SYSGEN_DOTNETV2_SUPPORT is the CF 2.0 support sysgen. SYSGEN_DOTNETV2_SUPPORT is a super-set of the CF 1.0 support.

Effectively if SYSGEN_DOTNETV2_SUPPORT is added to the image then the end user can deploy either 1.0 or 2.0 and all of the required underlying CE OS pieces will be there.

Keep in mind that required means "base functionality". CF 2.0 has optional functionality that requires other SYSGENS and they are as follows:

  • Message Queuing - SYSGEN_MSMQ
  • Soap Reliable Messaging Protocol - SYSGEN_MSMQ_SRMP
  • SQLMobile (2005) requires CoCreateGuid functionality - SYSGEN_OLE_GUIDS
  • IPv6 - SYSGEN_TCPIP6
  • IE, PIE, HTMLView (htmlview.dll) or nothing - SYSGEN_IE, SYSGEN_PIE, SYSGEN_HELP or simply nothing.
  • The following only apply to the MainstoneII, other devices will only have null driver sets:
    • D3D Mobile - BSP_D3DM_XSCALE
    • D3D Mobile - SYSGEN_D3DMXSCALE

 

2/23/2006 4:47:21 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Wednesday, February 22, 2006

It's been a while since we visited the OpenNETCF.Deskop.Communication library, but there have been lingering issues that ActiveSync 4.x have exposed (a stack imbalance exception).  So today I revisited the library and did some fixes to it as well as to the sample app (bad, bad me for not marshaling calls to the UI from a thread.  It's now a Studio 2005 project.

The latest code is in Vault and the downloads on the site are updated to this new version (2.9) as well.

2/22/2006 2:09:33 PM (Eastern Standard Time, UTC-05:00)  #    Comments [2]  | 
 Sunday, February 19, 2006

SDF 2.0 continues to have functionality for working with the time and time zones for devices.  The differences from SDF 1.x are a namespace change, a classname change (don't believe the beta docs or the beta, these have changed since that drop), and under the hood a lot more internal checks are going on to head off errors and to provide correct device support.  Basically this one has been pretty heavily tested across a broad range of devices.

Some quick highlights:

Getting and Displaying a List of Time Zones

using OpenNETCF.WindowsCE;
...
// get and display all available zones
TimeZoneCollection tzc = new TimeZoneCollection();
tzc.Initialize();

foreach (TimeZoneInformation tzi in tzc)
{
    lstZones.Items.Add(tzi);
}

Displaying the Currently Set Time Zone

using OpenNETCF.WindowsCE;
...
// get and display the currrent zone

TimeZoneInformation currentTz = new TimeZoneInformation();
DateTimeHelper.GetTimeZoneInformation(ref currentTz);
lblCurrentZone.Text = currentTz.StandardName;

Setting the Current Time Zone (from the Listing above)

using OpenNETCF.WindowsCE;
...
if
(lstZones.SelectedItem != null)
{
    TimeZoneInformation tzi = (TimeZoneInformation)lstZones.SelectedItem;
    DateTimeHelper.SetTimeZoneInformation(tzi);

    // this verifies that the time zone did indeed get changed
    TimeZoneInformation tz = new TimeZoneInformation(
        (byte[])Registry.LocalMachine.OpenSubKey("Time").GetValue(
            "TimeZoneInformation"));
    MessageBox.Show("Current Timezone in Registry is:\r\n" 
        + tz.StandardName, "Verified");
}

Displaying the Current Time (without DateTime.Now)

using OpenNETCF.WindowsCE;
...
DateTime dt = DateTimeHelper.SystemTime;

txtHour.Text = dt.Hour.ToString();
txtMinute.Text = string.Format("{0:00}", dt.Minute);
txtSecond.Text = string.Format("{0:00}", dt.Second);

Setting The Current System Time (Local Time is Analogous)

using OpenNETCF.WindowsCE;
...
// get the current time so we can copy the date part

DateTime dt = DateTimeHelper.SystemTime;

DateTimeHelper.SystemTime = new DateTime(dt.Year, dt.Month, dt.Day,
    int.Parse(txtHour.Text), int.Parse(txtMinute.Text), int.Parse(txtSecond.Text));

 

2/19/2006 6:17:03 PM (Eastern Standard Time, UTC-05:00)  #    Comments [4]  | 
 Sunday, February 12, 2006

CE supports a Multimedia timer, though it's not in CF 1.0 or 2.0.  We've rectified that in SDF 2.0 (though your platform must support the Multimedia timer to use it - meaning WM and PPC are out).

So what do high-performance timers buy you?  Well if you look at how a regular timer works, they run at a really low priority and are horrible if you want anything that resembles deterministic behavior.  If you set the interval to say 1000ms, it's guaranteed to not fire in less than 1000ms, but there's actually no upper bound at all.  Jitter of 50ms (5%) would not be exceptional and in fact I've seen substantially worse on systems with a high load.

Our Timer2 class (name is still not finalized, so don't finalize on it) is based on the desktop's Timer class and provides things like a one-shot capability (timer fires once and never again without you having to disable it) and if you derive from it you can have it run a callback instead of raising an event.

Here's a quick example of usage:

void StartMyOneshotTimer
{
  // create a timer
  Timer2 oneShot = new Timer2();

  // make it a one-shot timer
  oneShot.AutoReset = false;

  // fire 3 seconds from enabling
  oneShot.Interval = 3000;

  // allow 10ms latitude for when it fires
  // so it will fire between now + 2995 and now + 3005
  oneShot.Resolution = 10;

  oneShot.Elapsed += new ElapsedEventHandler(oneShot_Elapsed);

  oneShot.Start();
}

void oneShot_Elapsed(object sender, ElapsedEventArgs e)
{
  // do something here
}

2/12/2006 2:39:02 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Saturday, February 04, 2006

You might have noticed that SDF 2.0 no longer has serial or GPS classes.  This is intentional.  CF 2.0 now has serial classes and the Windows Mobile AKU includes GPS support.  We realize that there are some of you out there that are using GPSes on non-WM 5.0 devices and that you'd like to be able to use our stuff under Studio 2005.  For those people, we've spun the Serial and GPS classes into a stand-alone assembly: OpenNETCF.IO.Serial.  There are no plans for an installer for this assembly, and unless we get strong feedback it probably won't make it into the SDF either.

2/4/2006 2:41:38 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Thursday, February 02, 2006

If you're a Windows CE device developer and you've got a device with a persistent registry, you're probably already aware that the CF Registry class doesn't help much for saving the registry, restoring branches from a file or creating volatile keys.  Once again the SDF is here to help with CreateVolatileSubkey, RestoreHiveBasedKey, RestoreRamBasedRegistry, SaveHiveBasedKey and SaveRamBasedRegistry.

One note - the doc says they're in the Registry2 class - that's already been changed to RegistryHelper.

 

2/2/2006 11:31:28 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Sunday, January 29, 2006

Making apps power aware, especially through the device Power Manager works, but the code is kind of ugly and a pain to implement.  Once again SDF 2.0 simplifies things:

using System;
using System.Windows.Forms;
using OpenNETCF.WindowsCE;

namespace WindowsCETest
{
  public partial class MyPowerAwareClass
  {
    public MyPowerAwareClass()
    {
      DeviceManagement.DeviceWake +=
       new DeviceNotification(
DeviceManagement_DeviceWake);

      PowerManagement.PowerUp += new DeviceNotification(PowerManagement_PowerUp);
    }

    void PowerManagement_PowerUp()
    {
      MessageBox.Show("The Power Manager says I'm awake!");
    }

    void DeviceManagement_DeviceWake()
    {
      MessageBox.Show("Device notifications say I'm awake!");
    }
  }
}

1/29/2006 9:56:53 AM (Eastern Standard Time, UTC-05:00)  #    Comments [4]  | 
 Saturday, January 28, 2006

The Windows CE operating system supports several notifications for common device events liek changes in AC power, network status changes and time changes.  They are exposed by using the CeRunAppAtEvent or CeSetUserNotification APIs.  While the Windows Mobile Notification Broker provides an interface for some of these, it doesn't provide access to all of them, nor is it available for general Windows CE developers.

SDF 1.4 provided a set of Notification classes that could be used to get these (and those classes are still there in SDF 2.0) but we felt that a simple object model around these would really be a nice thing to have.  So we created the OpenNETCF.WindowsCE.DeviceManagement class.  Now subscribing to the notifications is as simple as this example of detecting when the device time has been modified:

using System;
using System.Windows.Forms;
using OpenNETCF.WindowsCE;

namespace WindowsCETest
{

public class MyClass
{

public MyClass()
{

    DeviceManagement.TimeChanged +=
       
new DeviceNotification(DeviceManagement_TimeChanged);
}

void
DeviceManagement_TimeChanged()
{
    MessageBox.Show(
"The time was just changed.");
}

}

}

1/28/2006 6:26:51 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  | 
 Saturday, January 21, 2006

We're extremely close to a beta release of SDF 2.0.  To give you a taste of what's in it, we've posted the online documentation.  Any feedback is appreciated.  Enjoy.

1/21/2006 11:49:17 PM (Eastern Standard Time, UTC-05:00)  #    Comments [3]  | 
 Tuesday, December 20, 2005

So if you're working with Microsoft's new Microsoft.WindowsMobile.PocketOutlook namespace and trying to use the OutlookCollection.Restrict method to filter by a Contact's (or any PimItem's) ItemId field, you will likely run into a problem.

First, let me say the ItemID Class sucks.  It exposes basically nothing useful but a ToString() method, even though it holds numeric data.  And the first item added to POOM gets the ItemId of 0x80000001, which you might note is an *unsigned* number (again, the CLS is a pain for not allowing unsigned numbers).  So if you have an ItemId class and you want to use it, you have to do something like this:

unchecked
{
    int myId = int
.Parse(m_outlookSession.Contacts.Items[0].ItemId.ToString())
}

Really, that's how you have to do it.

So, let's say we have a Contact's ItemId and we want to see if the current session has said Contact.  One might try this:

m_outlookSession.Contacts.Items.Restrict("[ItemId]=" + itemId.ToString());

A nice try, but that gives you the not-so-helpful exception:

The query string is incorrectly formatted.
Parameter name: [ItemId]=-2147483647

Alright, so ItemId only exposes itself as a string, and Restrict has little in the way of useful documentation or samples, so maybe we can try it as a string like so:

m_outlookSession.Contacts.Items.Restrict("[ItemId]='" + itemId.ToString() + “'“);

Well that gives a similar exception, just adding the single quotes:

The query string is incorrectly formatted.
Parameter name: [ItemId]=-'2147483647'

Because I've used POOM from C++, I know that ItemId seems new to me, so just as a lark I figure I'll try 'Oid' as a field name instead, and keep it as a numeric:

m_outlookSession.Contacts.Items.Restrict("[Oid]=" + itemId.ToString());

Lo and behold, success!

Now technically this might not be a true bug, but it's sure not documented anywhere, nor would it be at all intuitive to guess if you'd not used C++ to access an IContact (which exports an Oid field, *not* an ItemId) before.  Bad Windows Mobile Team.  BAD!

Things needed:

  • The ItemID needs to have an explicit operator for conversion to an int at the very least.  A ToInt32 or ToIntPtr or something of the sort would be useful.
  • Either name the field Oid like it's stored in the database, or provide some sort of substitution so when I filter by ItemId the underlying class converts that to Oid.
  • The least they could have done was give exception text like “The field cannot be found in the collection“
  • Documenting how to remove a Restrict once set would be useful (I used Restrict(“[Oid]<>0“) for lack of any better idea)
12/20/2005 10:15:43 PM (Eastern Standard Time, UTC-05:00)  #    Comments [4]  | 
 Friday, December 09, 2005
 Wednesday, November 23, 2005

I was playing around with PlaySound today (no pun intended) and was kind of surprised to find that I could play an embedded resource wave file with one line of code (well one line past the P/Invoke declaration):

using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

....

// P/Invoke declarations....
[DllImport("CoreDll.DLL", EntryPoint="PlaySound", SetLastError=true)]
private extern static int PlaySound(byte
[] szSound, IntPtr hMod, SoundFlags flags);

[Flags]
enum SoundFlags
{
  Alias = 0x00010000,
  Filename = 0x00020000,
  Synchronous = 0x00000000,
  Asynchronous = 0x00000001,
  Memory = 0x00000004,
  Loop = 0x00000008,
  NoStop = 0x00000010
}

...

PlaySound(((MemoryStream)Assembly.GetExecutingAssembly(
  ).GetManifestResourceStream(
  "AudioTest.tada.wav")).GetBuffer(),
  IntPtr.Zero,
  SoundFlags.Synchronous | SoundFlags.Memory);

11/23/2005 12:41:54 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Tuesday, November 22, 2005

A couple new articles from OpenNETCF have finally gone public:

Device Debugging and Emulation in Visual Studio 2005 from Alex Feinman
Using Visual Studio 2005 to Design User Interfaces and Data for Device Applications from Maarten Struys

11/22/2005 1:02:12 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Monday, August 22, 2005

Here's yet another article I'm working on for MSDN and again, comments are welcome.  A printer friendly version is here.  The source is available here.

8/22/2005 12:16:38 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [4]  | 
 Monday, August 15, 2005

Here's another article I'm working on for MSDN.  Again, comments are welcome.  A printer friendly version is here.  The source is available here.

8/15/2005 9:25:29 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [3]  | 
 Sunday, August 14, 2005

Here's a draft of an article I'm putting together for MSDN.  Comments are welcome.  A printer friendly version is here.

8/14/2005 12:20:26 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Friday, August 05, 2005

Finally!  We've released SDF 1.4.  What's new you ask?  Well here's a quick list (which I extracted from check-in comments from the source Vault - you can do the same to see exactly what the changes are):

  • Bluetooth support added
  • Serial.GPS mods to standardize naming
  • Diagnostics.DebugMessage and RetailMessage
  • Bug fixes in TimeZoneCollection and DateTimeEx
  • Bug Fix in XmlSerializer for GUIDs
  • EventWaitHandle.WaitOne bug fix
  • Additions and fixes for AccessPoint and Adapter classes
  • Bug fix in StreamInterfaceDriver.DeviceIoControl
  • ThreadEx.RealTimePrioority added
  • Updated BatteryLife designer
  • Updated DateTimePicker Designer
  • Fixes and Updates to Win32Window
  • ApplicationEx fix for modal Forms and thread safety added
  • FTP bug fixes
  • ControlEx added support for WM_COMMAND
  • DeviceMonitor adds RequestDeviceNotifications
  • SelectedIndexChanged fix in ComboBoxEx
  • WS and WS_EX updated to remove unsupported styles
8/5/2005 10:57:21 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 

I often start on a project with the best of intentions to finish, but then something else comes up and I get side tracked.  I was going through code this morning and came across one such example from when I was doing the Travelling Salesman Problem on a device.  Someone on a newsgroup said a device wasn't powerful enough to do it - I thought that was BS, so I sat down and started coding.  Of course then other things came up and this ended up unfinished (though it's probably only a day of work away).  I did get far enough to do Help documentation for it.

Knowing myself and the list of things I need to do, I'm probably not going to get back to it any time soon, so if someone else wants the mental exercise, feel free to finish what I've done.

8/5/2005 10:39:44 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]  | 
 Thursday, August 04, 2005

Someone asked me today “How do I get my CF window to not show up in the taskbar?”  Since Form.ShowInTaskbar isn't supported in the CF, I decided to play around and see how it's done.

It led me to play around with the SDF's Win32Window and EnumEx classes.  Basically, populate a couple ListViews with all the available style and extended style bits, then let the user check whatever s/he wants and reapply them.

187 lines of code later and I've got a very busy window (check out the caption bar) but it's still in the Taskbar.  Turns out to be not-so-easy after all - so I'll keep trying, but here's a quick sample on using the Win32Window.

Here's the meat of it:

private void ParentWindow_Load(object sender, System.EventArgs e)

{

      m_child.Show();              

      m_childWindow = Win32Window.FindWindow(null, "ChildWindow");

     

      WS childStyle = m_childWindow.Style;

 

      foreach(WS style in EnumEx.GetValues(typeof(WS)))

      {

            ListViewItem lvi = new ListViewItem(style.ToString());

            lvi.Checked = ((childStyle & style) != 0);

           

            lvwWS.Items.Add(lvi);

           

      }

 

      WS_EX childExStyle = m_childWindow.ExtendedStyle;

 

      foreach(WS_EX exstyle in EnumEx.GetValues(typeof(WS_EX)))

      {

            ListViewItem lvi = new ListViewItem(exstyle.ToString());

            lvi.Checked = ((childExStyle & exstyle) != 0);

           

            lvwWSEX.Items.Add(lvi);

      }

 

}

 

private void btnSetStyle_Click(object sender, System.EventArgs e)

{

      WS style = 0;

      foreach(ListViewItem lvi in lvwWS.Items)

      {

            if(lvi.Checked)

                  style |= (WS)EnumEx.Parse(typeof(WS), lvi.Text);

      }

      m_childWindow.Style = style;

 

      WS_EX exstyle = 0;

      foreach(ListViewItem lvi in lvwWSEX.Items)

      {

            if(lvi.Checked)

                  exstyle |= (WS_EX)EnumEx.Parse(typeof(WS_EX), lvi.Text);

      }

      m_childWindow.ExtendedStyle = exstyle;

      m_child.Refresh();

}

PostScript:

It turns out this is right.  If you modify the style of the Form during it's contructor, then it will not show up in the Taskbar (thanks Sergey).

public ChildWindow()

{

      InitializeComponent();

 

      Capture = true;

      Win32Window hwnd = Win32Window.GetCapture();

      Capture = false;

 

      hwnd.ExtendedStyle |= WS_EX.NOANIMATION;

}

 

PostPostScript:

This uses SDF 1.4, so if you're trying it, make sure you get the latest code (or wait a day until 1.4 is released)

 

8/4/2005 4:27:09 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
 Tuesday, April 26, 2005

It seems that mobile and embedded computing is finally being recognized as an actual career path.  Purdue University has a class and a Mobile Computing Lab.  Check out the projects students have done so far.  Very promising indeed.

4/26/2005 9:54:33 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [3]  | 
 Friday, March 25, 2005

For those of you who may ever need to interface to a DS1307 I2C real time clock (it would wourk for the 1306 SPI RTC as well) here's a useful class.

private class RTCTime
{
 private byte[] m_bytes = new byte[7];
 
 public RTCTime()
 {
 }
 public RTCTime(byte[] data)
 {
  m_bytes = data;
 }
 public RTCTime(DateTime dateTime)
 {
  this.Second = dateTime.Second;
  this.Minute = dateTime.Minute;
  this.Hour = dateTime.Hour;
  this.Day = dateTime.Day;
  this.Month = dateTime.Month;
  this.Year = dateTime.Year;
 }
 public static implicit operator byte[](RTCTime rtc)
 {
  return rtc.m_bytes;
 }
 public static implicit operator RTCTime(byte[] bytes)
 {
  return new RTCTime(bytes);
 }
 public static explicit operator DateTime(RTCTime rtc)
 {
  return new DateTime(rtc.Year, rtc.Month, rtc.Day, rtc.Hour, rtc.Minute, rtc.Second, 0);
 }
 public int Second
 {
  get { return BCD_TO_WORD(m_bytes[0]); }
  set { m_bytes[0] = WORD_TO_BCD(value); }
 }
 public int Minute
 {
  get { return BCD_TO_WORD(m_bytes[1]); }
  set { m_bytes[1] = WORD_TO_BCD(value); }
 }
 public int Hour
 {
  get { return BCD_TO_WORD(m_bytes[2]); }
  set { m_bytes[2] = WORD_TO_BCD(value); }
 }
 public int DayOfWeek
 {
  get { return BCD_TO_WORD(m_bytes[3]); }
  set { m_bytes[3] = WORD_TO_BCD(value); }
 }
 public int Day
 {
  get { return BCD_TO_WORD(m_bytes[4]); }
  set { m_bytes[4] = WORD_TO_BCD(value); }
 }
 public int Month
 {
  get { return BCD_TO_WORD(m_bytes[5]); }
  set { m_bytes[5] = WORD_TO_BCD(value); }
 }
 public int Year
 {
  get { return BCD_TO_WORD(m_bytes[6]); }
  set { m_bytes[6] = WORD_TO_BCD(value); }
 }
 public int Length
 {
  get { return m_bytes.Length; }
 }
 private int BCD_TO_WORD(byte x)
 {
  return (x & 0x0f) + ((x >> 4) * 10);
 }
 private byte WORD_TO_BCD(int x)
 {
  return (byte)((x % 10) + ((x / 10) * 0x10));
 }
}
3/25/2005 12:36:30 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [3]  | 
 Saturday, March 12, 2005

Pocket PC magazine has published an article by Mick Badran of Breeze Training that uses the SDF (though they called it the Smart Device Extensions - remember back when the CF was called that?).  An online version is available here.

3/12/2005 4:53:55 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |