Skip to content

May, 2007 articles

NotifyIcon context menus for both buttons in .NET (evolution of a hack)  

Here’s the evolution of what should have been a clean reusable component in .NET and how it becomes a hack thanks to the limitation of the .NET framework.


I’m working on an application where I want two contextual menus on the notify icon. The right one will display a number of options for settings and creating new items and the left to switch between the various items.

Before anyone else harps on about UI conventions this is exactly how the Windows Safely Remove Hardware notify icon works.

A brief glance at the NotifyIcon component in .NET shows that it supports one contextual menu displayed with the right button.

This is a shortcoming but not a problem right? This is a modern object oriented programming environment and extending functionality should be easy. It certainly was in Delphi back in the early 90’s with it’s .NET-like VCL framework.

Attempt 1. Subclassing NotifyIcon (failed)

One of the founding principles of object oriented programming is reuse. The sealed keyword prevents reuse and forces use instead.

Keith Pleas wrote “If they extend it, they will break it. Use internal more. Seal first, ask questions later.” which is absolute rubbish.

In our case the subclassed NotifyIcon would hook into the click mechanism and display a menu. Reflector shows nothing would break.

This is an unfortunate trend in the .NET Framework and with each release the framework grows towards an inflexible monolithic framework of simplistic classes. These classes force you to reinvent the wheel if they are not quite what you like because the developers believe they know exactly how you will use the framework.

Online forums provide substantial evidence to the contrary.

So creating a reusable component that just has two ContextMenuStrip properties – one for each button – is out thanks to short-sighted framework developers.

Attempt 2. Show ContextMenu on left-click (failed)

We’ll have to reproduce this code in each app we write and instead wire up to the NotifyIcon’s OnMouseClick event.

There we will need to test to ensure the left button is clicked and show the alternative ContextMenuStrip:

private void notifyIcon_MouseClick(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left)

Okay, this shows the menu now when the click happens but does not behave like the right-click menu. The positioning and click tracking is off and an odd blank task-bar item appears. A quick glance at the disassembly of NotifyIcon.ShowContextMenu shows code to handle the positioning and the the method we want to handle the tracking/task-bar is ContextMenuStrip.ShowInTaskbar.

And guess what? It’s internal.

Attempt 3. Hack the control (success)

Back at the drawing board we decide the only option left to us is the ugly hack. Replace the ContextMenuItem, call ShowContextMenu and then switch the ContextMenuItem back.

Of course even NotifyIcon.ShowContextMenu is unfathomably marked private so we’ll have to call that via reflection. The result is:

private void notifyIcon_MouseClick(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    notifyIcon.ContextMenuStrip = taskMenuStrip;
    typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(notifyIcon, null);
    notifyIcon.ContextMenuStrip = contextMenuStrip;


The framework developers were worried I might break NotifyIcon if I subclass it and took measures to prevent that possibility through a combination of the sealed, private and internal.

Instead I am forced to develop a solution that is much more likely to break as I now rely on:

  • ContextMenuStrip property setter not clearing or removing existing displayed menu
  • ShowContextMenu private property not changing name or visibility


Red Hat releases Liberation fonts  

Linux vendor Red Hat have released a font family named Liberation under a GPL licence.

The family consists of three typefaces known as Liberation Serif, Liberation Sans and Liberation Mono each in normal, italic, bold and bold italic variants. The fonts are not hinted in this initial release so may not look too great on-screen at some sizes. Red Hat expect to release better-looking hinted versions in the future. Having attempted hinting Envy Code R font myself they have my sympathy.

These new fonts are designed to be metric-compatible (and therefore interchangeable) with the standard Windows fonts of Times New Roman, Arial and Courier New intending to "Liberate" documents from Microsoft’s fonts. Bearing in mind Office 2007 pushes new typefaces as the default I’m not sure how successful this will be long-term.

Microsoft’s typefaces were designed to be metric-compatible with the classic Times Roman (1931), Helvetica (1957) and Courier (1955) typefaces in the first place so perhaps Red Hat would have been better off licensing or mimicking those instead.

Screen shots follow.


The Liberation fonts on Windows using ClearType alongside the Windows fonts they intend to replace. The free Bitstream Vera family equivalent is also shown (only Vera Sans Mono is metric-compatible).


Microsoft’s Windows fonts alongside Apple’s versions of the originals and the Liberation fonts again all rendered with Mac OS X and sub-pixel precision aliasing. Point sizes have been increased by 3pt to compensate for the difference in on-screen DPI.


LINQ to SQL details, issues and patterns  

LINQ to SQL (formely called DLINQ) is a simple object-relational mapper (ORM) scheduled for .NET Framework 3.5/Visual Studio 2007 (Orcas).

On projects with new data I’m keen on keeping the tables and classes as similar as possible and so the limited functionality of LINQ to SQL really appeals to me.

Sure for larger applications or where legacy data does not inspire great classes then a more advanced ORM with better mapping facilities can outweigh the disadvantages and learning curve imposed by another layer of abstraction. Microsoft have that covered with LINQ to Entities which will ship post-Orcas because of the immaturity of the the designer and advanced scenarios.

Whilst prototyping I’ve come up with a few oddities that deserve documenting somewhere. Here they are in not-quite-FAQ format.

What SQL is this query or operation generating?

Set the Log property of your DataContext object to Console.Out.

What objects are generated and how do I extend them?

MyDataContext : DataContext

Represents a users view of the database and is generated by designer/SQLMetal exposing a property for each table being mapped.

Can be extended by writing your own partial class or sub classing.

MyEntity / T

Represents an entity for each row in the associated table and is generated by designer/SQLMetal exposing a property for each field being mapped which is also decorated with attributes that specify the underlying field name and type.

Can be extended by writing your own partial class, sub classing or providing a superclass.
No classes are generated for the tables themselves, instead the generic class Table<T> uses the attribute information from the entity objects (cached via various metadata classes such as MetaTable).

What patterns does LINQ to SQL use?

Thankfully ActiveRecord is ignored and a more flexible approach is used. It basically provides one class for the database and one for each type of entity (because of inheritance, there could be more than one type of entity per table).

I’ve yet to delve deep enough into the classes and patterns to find good matches but a brief look reveals the following possibilities:

Registry – System.Data.Linq.DataContext
Unit of Work – System.Data.Linq.DataContext
Identity Map – System.Data.Linq.IdentityManager
Table Data Gateway – System.Data.Linq.Table<T>
Query Object – System.Data.Linq.DataQuery<T>
Metadata Mapping – System.Data.Linq.Provider.Meta*, System.Data.Linq.*Attribute, System.Data.Linq.Mapping.*

How do I persist changes?

Call the SubmitChanges method on your DataContext object.

What causes the error “Row not found or changed” when submitting changes?

By default LINQ to SQL creates UPDATE statements that include every field as it was when read in the WHERE clause and not just the primary key as you might expect. The upshot is that if the record has changed since it was loaded it will not find it.

However, there are also a couple of scenarios where it won’t find the record even if it hasn’t changed:

  • If the data range/precision of the .NET type can’t exactly hold the value in the SQL table (e.g. DateTime)
  • If the table schema doesn’t exactly match the mapping (e.g. a column’s nullability changing)

If in doubt remove the table from your LINQ schema diagram and drag a fresh copy back in from your database using the Server Explorer pane.

Why does the OnPropertyChanging event use the PropertyChanged event handler delegate?

OnPropertyChanging does indeed seem to be using the PropertyChangedEvent and PropertyChangedEventArgs that OnPropertyChanged use.

Being that PropertyChangingEvent and PropertyChangingEventArgs exist I would assume this is a bug within the designer/SQLMetal in beta 2.

What database vendors are supported?

SQL Server 2000, 2005, 2008 and SQLCE are currently included.

Why do queries against a table return entities that do not match the query?

This occurs when entity objects in memory are out-of-step with data in the database.

The query is exectuted against the SQL server and for each matching record it either creates and entity object or uses the cached one it already has.

Therefore it is possible your result set will:

  • not include matching entities because the database indicates they do not (database changed or do not exist)
  • include entities that do not match because the database indicated they did (database changed or object changed)

Why is memory consumption so high?

LINQ to SQL tends to burn more memory than you might be expecting because of the multiple objects and aggressive caching in place.

Should I share a DataContext between users?

Web applications, web services and middle-tiers often share objects between potential users and requests. It is worth bearing in mind that a DataContext is not well suited to sharing between users because:

  • Entities are cached indefinitely
    • High memory use as every entity is eventually loaded to memory
    • Entities to be out-of-date if the data can be updated elsewhere (triggers, imports, background jobs)
  • DataContext.CommitChanges persists all objects changed via that DataContext
    • Difficult to determine a safe point to commit User A’s completed entities without committing User B’s incomplete entities
  • DataContext’s Table<T> creation is not thread safe
    • Accessing a table for the first time on two threads could cause the DataContext to create one instance of a Table<T> whilst creating another for the same <T> and resulting in the latter being kept but the former being returned to one of the callee’s.

A DataContext is therefore best suited for either a single-user application, per-session or per-request.


Subversion talk at Guernsey Developer User Group  

This presentation is now available on-line.

I will be giving a talk entitled “Change management with Subversion” at the Guernsey Developer User Group later this month.

The talk will start with the reasons for change management and the terminology Subversion uses before delving into a typical work cycle. The AnkhSVN client for Visual Studio and the TortoiseSVN client for Windows Explorer will be demonstrated and various other points covered such as when to branch, when to merge, what server options exist etc.

If you are interested in source control, team collaboration or release management then feel free to come along.

This GDUG meeting takes place on the 24th of May at the Guernsey Training Agency’s office above the Guernsey Post Office in Smith Street. As usual the meeting will start at 6pm and the talk will likely start shortly after that and run to around 30-45 minutes (I’m still finalising the content).

This location is the venue for the tonight annual general meeting of the Guernsey section of British Computer Society. I believe this particular BCS event is only open to BCS members but if you are a member then this is a gentle reminder. At least 4 of us from the GDUG will be in attendance.