Finding Code Issues

October 1, 2010 – 22:02

As programmers we are well known for writing bug free perfectly formed code first time round, as such I don’t really understand why DevExpress implemented the code issues feature… no wait… that should be the other way round.

CodeRush has several ways to access the Code Issues user interface, first off there is the thin file overview down the right hand side of the viewport. In the code itself there are handy contextual hints too.

Code Rush Issue In Context

In this example, “this.” is redundant and has been greyed out, if you hover over it it will tell you more about the issue and how to resolve it. Different issues have different notation so code that is to be transformed will have a coloured underline.

In the process of going though a file created by someone else the code style was a bit off – I was able to quickly bring it in line with the project preferences by using the shortcut keys Alt + PageDown to skip between the issues then Ctrl + ‘ to fix the issues quickly.

Great feature for spotting mistakes as you code, and also for learning new language features as they are introduced into the specification.

Spot The Mistake 1

August 21, 2010 – 18:30

This one had me puzzled for about an hour, I shall endeavour to post the answer in the comments in short order.

foreach (var id in CharacterIdentities)
    (x) => OnSkillInTrainingUpdated(x, id));

Using EVEMon Data with LINQPad

July 31, 2010 – 22:52

LINQPad is an awesome aide to .NET Developers. Written by Joseph Albahari of LinqBridge and the C# In a Nutshell series fame. LINQPad allows the developer to write, compile and run C# or VB.NET Expressions, Statements of Programs outside of Visual Studio.

Everything I am going to show you in this post can be done with Visual Studio simply by wrapping the text in a new console application, and adding references to the DLLs. However I strongly encourage you to download LINQPad and give it a go.

In the event you are using 64-bit windows and are still using LINQPad 2 you will need to download the x86 version of LINQPad 2, as all of the EVEMon assemblies are compiled for x86. If you have LINQPad 4 you don’t need to worry about.

Assuming you have EVEMon installed, the first step is to load the EVEMon.Common.dll assembly into LINQPad:

  1. Go ahead and fire up LINQPad ensure you have a new query window open
  2. Press F4 (Query -> Query Properties).
  3. Click the “Browse…” button at the bottom of the properties window.
  4. Navigate to the EVEMon install directory.
  5. Select “EVEMon.Common.dll”

While you have “Query Properties” open go to the “Additional Namespace Import” tab and add the following two lines:


EVEMon.Common was designed to work as part of a long running process, namely the EVEMon application sitting in your system tray from when you turn your computer on until you turn it off, as such we need load the static data from the data files.


Now we get to do some LINQ,

var allItems = from item in StaticItems.AllItems
	       where item.Family == ItemFamily.Ship
	       select new
	           CPU = item.Properties[DBConstants.CPUOutputPropertyID].Value.Value,
	           PG = item.Properties[DBConstants.PGOutputPropertyID].Value.Value,

I could start to explain the above line by line, but there are lots of really good LINQ articles on the Internet, including one by Joseph Albahari. We will just say that the above pulls all of the ships out of EVEMon’s Items data file and selects the Name, Race, CPU, PowerGrid and Description property for each one.

Now we see my favorite aspect of LINQPad, the .Dump() extension method, simply running the following command:


Will output the data we have just queried as a nice HTML Table:

That is all I have for you for now, I am working on a project that uses this data outside of EVEMon, keep an eye on Twitter where I will hopefully be providing a link for testing in the not too far distant future.

Tracing A Method Signature

July 16, 2010 – 22:03

Over the past three weeks I have discovered that many performance problems with Windows Forms applications are down to certain events being fired very rapidly, usually these are down to layout operations being triggered by updates to controls.

Without the use of RedGate Software’s excellent performance profiler I have been forced back into the habit of temporarily peppering the code I suspect of being a problem with trace messages.

For a while I was quite disorganised using trace messages such as “Entered SoAndSoMethod”, “OnSomeEvent Triggered”, etc. Over time I have settled into using the declaring class and method name to identify which method was being called.

Thinking about it today I decided this was still too much work (yeah, I am that lazy), I wondered if System.Reflection could help me:

public static void Trace()
    var stackTrace = new StackTrace();
    var frame = stackTrace.GetFrame(1);
    var method = frame.GetMethod();
    var parameters = FormatParameters(method.GetParameters());
    var declaringType = method.DeclaringType.ToString().Replace("EVEMon.", String.Empty);
    Trace("{0}.{1}({2})", declaringType, method.Name, parameters);
private static string FormatParameters(ParameterInfo[] parameters)
    var paramDetail = new StringBuilder();
    foreach (var param in parameters)
        if (paramDetail.Length != 0)
            paramDetail.Append(", ");
        paramDetail.AppendFormat("{0} {1}", param.GetType().Name, param.Name);
    return paramDetail.ToString();

This means that with liberal application of:


Will output the following to the trace:

0d 0h 00m 03s > CharacterMonitor.OnLoad(ParameterInfo e)
0d 0h 00m 03s > CharacterMonitor.multiPanel_SelectionChange(ParameterInfo sender, ParameterInfo e)
0d 0h 00m 03s > CharacterMonitor.multiPanel_SelectionChange(ParameterInfo sender, ParameterInfo e)

Hopefully that will save a few seconds here and there. It is a shame that reflection can’t get the actual values of the parameters from the frame, as that would be even more useful. 3.5 GridView RowCommand event fired twice

April 1, 2010 – 16:25

I am writing this up to hopefully save someone else time in the future, this particular problem took up six hours of my day yesterday causing quite a bit of frustration for me, as the developer, and the users of the application.

If you are searching for the solution scroll down to the bottom of the page where I will outline the solution I used to resolve the problem. It is also worth pointing out that this does appear to be fixed in .NET 4. Certainly I was able to consistently reproduce the problem with VS2008/.NET 3.5 on multiple different computers. However after converting the project to VS2010/.NET 5 I haven’t seen the issue.

Explanation of the problem

I wrote and maintain an application that publishes a list of courses and allows users to book onto these courses, what I have listed below is a simplified version of this application.

The administration console contains two lists:

  • Published Courses – courses visible to all employees.
  • Unpublished Courses – courses waiting to be published, only visible from the administration console.

Courses can be freely published (i.e. moved from Unpublished to Published) by clicking green tick. Courses that have not had any bookings made can be unpublished by clicking the red cross.

The cross and the tick are implemented as GridView ButtonFields:

<asp:ButtonField ButtonType="Image" CommandName="UnpublishCourse" 
    ImageUrl="~/images/unpublish.png" InsertVisible="False" Text="Unpublish" />

This application has been running for six months, the issue had not been observed up until yesterday. The user explained to me that when they were publishing courses they were always published in pairs, equally when unpublishing courses it was being done in pairs, concealingly unpublishing a course with bookings.

Investigating the problem

Initially I tried to reproduce this on my local machine, backed up and subsequently restored the database locally made sure I was running the same revision as the server and fired it up. Couldn’t reproduce the problem, no matter how fast I clicked it wouldn’t happen. Tried various permutations of code and database but could only reproduce on the server.

Refreshed the binaries on the server with the HEAD from subversion, problem was still happening most of the time. I confirmed that it wasn’t an issue with the stored procedures by running them manually through LinqPad.

I started putting debug statements at the entry points to the critical parts of the code, this yielded an interesting output on my development machine, each time the cross or the tick was clicked UnpublishedGridView_RowCommand was fired twice. This gave me something to search for, seems I am not the only one to have this problem, Microsoft tried to reproduce it in 2006 but couldn’t.

Solving the problem

As it turns out there are several ways of fixing the problem, several people have used timers to “debounce” the RowCommand event, assuming that the event is always going to be fired twice a session variable can be used to filter out the second event.

Because the event is only fired twice when ButtonType=”Image” not when ButtonType=”Link” you can set the text property to the HTML to render your image. This resulted in the code above becomming:

<asp:ButtonField ButtonType="Link" CommandName="UnpublishCourse" 
    InsertVisible="False" Text="<img src=images/unpublish.png />" />

This proved to be the simplest possible solution, Visual Studio 2008 throws a warning about validation, but I can live with that as long as the application works. In addition to the simplicity of the solution it also continues to work in 4 (which doesn’t exhibit the double event behaviour).

Lack of AutoEllipsis support in ToolStripSystemRenderer

March 7, 2010 – 22:03

AutoEllipsis is a property introduced to System.Windows.Forms.Label with .NET 3.0, which in the event of the text overflowing the rendering rectangle of the Label will trim the end and add a Ellipsis (“…”), if this does occur the ToolTip for the label will also be set to the full (untrimmed text).

Unfortunately this functionality is not available for ToolStripStatusLabel. To make things worse in the event the text overflows it disappears completely. This bug, oversight, feature or whatever you want to call it cause some confusion after the release of EVEMon Several people assumed the new more verbose status bar was broken, being empty and all.

We put together a kludge fix, which would set the text and if it overflowed try to guess the length with Graphics.MeasureString. This worked fairly well, it cause some flickering when resizing the window and would leave a small gap on the right hand side of the StatusStrip.

I knew there must be a better way, and seeing an article about the StringFormat class reminded me of the need to find it. Searching about a bit found me a post on Joel on Software, I refined the code a little and came up with this (which is basically identical to Tom’s solution):

public class AutoEllipsisToolStripRenderer : ToolStripSystemRenderer
  protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
    ToolStripStatusLabel label = e.Item as ToolStripStatusLabel;
    if (label == null)

You need to wire this code into your StatusStrip:

this.MainStatusStrip.Renderer = new AutoEllipsisToolStripRenderer();

To the ToolStripStatusLabel will also need it’s Spring property set to true, and if you want the text left aligned the TextAlign Property will need to be set to MiddleLeft.

If you want the ToolTip to work correctly the StatusStrip will need to have ShowItemToolTips set to work, and the ToolStripStatusLabel AutoToolTip set to true. It isn’t perfect as the ToolTip is displayed when the text is not truncated, but it is close enough for my purposes.

I am exploring WPF at the moment, I was glad to see the default behaviour of a StatusBar was to just stop rendering the text at the bounds of control, an ellipsis could be added with the TextTrimming and TextWraping properties:

            Some Text Goes Here, this text may be very long as demonstrated here. In the event we run out of space an ellipsis is used.

LINQPad Crash

March 2, 2010 – 22:48

Update: I never did “fix” this problem, installing .NET 4 then using LINQPad 4 seems to work well.

I found myself using LINQPad more often than creating console applications, so much so I dicided to make the small but worth while investment in the optional “Autocompletion” (Intelisense-like) component. The licence is great because I can have it installed on all three of my PCs without having to buy extra licences.

I was figuring out the limits of the Math.Pow function a few days ago on the laptop when the LINQPad upgrade message appeared, not sure what happened next because LINQPad crashed with the following exception.

System Specification:

  • Windows 7 Home Premium x64
  • .NET v2.0.50727 (+3.0 & 3.5)
  • .NET v4.0.20506
  • VisualStudio 2010 Beta1
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
   at LINQPad.Program.ProcessException(Exception ex)
   at LINQPad.Program.Start(String[] args)
   at LINQPad.ProgramStarter.Run(String[] args)
   at LINQPad.Loader.Main(String[] args)

If anyone has any theories as to how this can be fixed I would be very apprecitive if you could post in the comments.

So far I have tried:

  • Reinstalling from the latest (2.10.1) from the LINQPad website.
  • Restarted the computer.
  • Removing LINQPad through Add/Remove Programs.
  • Remove LINQPAD manually.
  • Rename %APPDATA%\LINQPad.
  • Looked for Native Images in C:\Windows\assembly – None there

It seems to me that LINQPad throws some exception, which it’s built in exception handler tries to handle then fails, this probably means that the above stack trace is probably not indicative of what is causing the problem. Not that I think it will make a difference but I am going to try upgrading to Visual Studio 2010 RC tomorrow then at least I wll be able to use LINQPad for .NET 4.

Preventing the PictureBox control from locking files

February 28, 2010 – 21:18

One of our more regular contributors to EVEMon posted on our forums showing that the application was incapable of updating cached files (specifically images), after a bit testing I discovered the following Exception was being thrown when trying to overwrite the file in question:

System.IO.IOException: The process cannot access the file 'path\filename' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
   at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
   at EVEMon.Common.FileHelper.OverwriteOrWarnTheUser(String srcFileName, String destFileName) in EVEMon.Common\FileHelper.cs:line 108
   at EVEMon.Common.FileHelper.OverwriteOrWarnTheUser(String destFileName, Func`2 writeContentFunc) in EVEMon.Common\FileHelper.cs:line 82
   at EVEMon.Common.Controls.CharacterPortrait.SavePortraitToCache(Image newImage) in EVEMon.Common\Controls\CharacterPortrait.cs:line 248

After a bit of searching around I discovered a post on StackOverflow identifying that System.Drawing.Bitmap(string filename) would lock the filename until the Bitmap was disposed of. The post presented a solution but no code, A bit of further searching confirmed my expectation that Image.FromFile(string filename) was subject to the same locking behaviour:

The file remains locked until the Image is disposed.

A bit more searching identified another post on StackOverflow which gave me the basic syntax and structure for the code I was going to need to implement this in EVEMon. The final code looks like this:

MemoryStream stream = new MemoryStream();
byte[] imageBytes = File.ReadAllBytes(cacheFileName);
stream.Write(imageBytes, 0, imageBytes.Length);
stream.Position = 0;
var image = Image.FromStream(stream);
return image;

It appears that GDI+ will lock any image that is loaded into a control in WinForms and WPF, several comments on StackOverflow and suggested that even disposing of the control and the FileStream was not a reliable way of being able to write to the file so the above method is seems to be be the best solution all round.

OneNote vs Evernote

February 27, 2010 – 21:11

Somewhere in the middle of 2007 I was encouraged to use OneNote to clear my desk and move to a “paperless” system, initially this was a little painful as it seemed a gargantuan task to scan in all of the bits of paper on and around my desk that appeared to contain useful information.

As it turned out I realised that if a bit of paper was covered by another (or in fact covered by anything) it wasn’t that important to the execution of my role and could probably be thrown in the bin.

At the time I was not using Microsoft Office at home, opting to use OpenOffice for the limited needs I had for productivity software. I did however want a better way of organising my paperwork at home, OneNote 2007 came in at about £70 which isn’t unreasonable for what you got. Then I discovered Evernote.

Seemed perfect, I don’t generate so much paperwork that I would bust the 40mb/month limit on the free account. In the end I decided to adopt Evernote at home and continue to use OneNote at work, it proved quite a handy separation of work and life.

Recently I have run into two problems that are pushing me towards using Evernote for everything, and ditching OneNote entirely:

  1. Evernote handles PDFs really well, you drag them in and they are displayed using the Foxit rendering engine. It just works. OneNote on the other hand plain old embeds them into the note, great now how is that different from having them in a folder in My Documents.
  2. Evernote 3.5 has vastly improved the synchronization mechanism meaning that I can safely put something on Evernote on my PC and it will be on my laptop shortly after it is turned on next. Microsoft has tried to get this kind of functionality into OneNote and SharePoint however it just doesn’t work that well, it is too slow and there seems to be a 10 minute refresh cycle hard coded into the product.

I am still not sure that I want to ditch OneNote entirely, the 2010 version has some nice labour saving devices built in such as quick screen clippings and image formatting with the fluid user interface. Nothing in OneNote 2010 screams “don’t leave me” though.

Login failed for user ”

January 25, 2010 – 14:51

There is an excellent post on the SQL Protocols blog about diagnosing the “Login failed for user ”. The user is not associated with a trusted SQL Server connection.” message displayed by SQL Management Studio and other applications which use the same API; Notice the blank username ”.

I believe there is one possibility missing from the above post: that is the Group Policy setting “Deny access to this computer from the network”. Which can be found in both Domain Group Policy and Local Security Policy in the following path:

Computer Configuration » Windows Settings » Security Settings » Local Policies » User Rights Assignment.

I have been using this policy more and more to lockdown access to site systems in accordance with our security and access policy. It pays to be cautious when applying User Rights Assignment policies to a machine, as in Windows 2003/XP they are not very granular.