Blog Image

Software Development

About the blog

The blog was created in an attempt to keep those valued points which are discovered in daily development and give something back to the community.

FileSystemWatcher

C# Posted on 2011-06-21 22:01

A FileSystemWatcher is very handy for
monitoring a file and e.g. reading it when it’s changed.

However, in some scenarios, more than
one Changed event with the same contents is raised for the same text
file. E.g. NotePad raises the event twice when saving a file, TextPad
3 times etc. etc.

This is annoying, because we don’t
really know how many times the event will be raised, and we can’t
safely react until the last time it’s raised – it may throw e.g. an
Access Denied because the editor isn’t done.

One solution is to use a timer which is
reset every time the event is raised for a specific file. When the
timer runs out, then the file can be accessed. For small files on a
fast machine or connection, it should be fairly safe to set the timer
to 1 sec, but it’ll depend on the size of the file, the load on the
machine, the bandwidth of the connection etc.

Small XML configuration files on a fast
machine with local harddrive storage could probably go as low as
100ms, but a 1 sec timer is safer and the rest of the application
won’t know when the file was available anyway. It just looks to the
app like the user pushed Save 1 sec later. (This could be a problem
when monitoring files in time-critical apps, but then this solution
really shouldn’t be used in such scenarios.)

The ”one timer per file” makes the
solution a lot less attractive the more files are monitored.



Readonly vs const

C# Posted on 2011-06-14 14:00

In short: const is set at compile time, readonly is set at runtime.

There’s a very important difference
between referencing consts and readonlys declared in a
different assembly: the const value is copied at compile time, while readonly is referenced at runtime.

Usually this difference won’t mean a
lot, but if you’re recompiling a referenced
assembly which has an updated const, then all referencing
assemblies will continue using ”the old const value” unless you
recompile them too. This could be the difference between being able
to drop-in a new assembly to fix a bug without re-deploying a full
system and not being able to …

A readonly will reference the value from the referenced assembly and therefore dropping-in only that assembly will be effective.

There are, however, drawbacks to using readonly, e.g. TestCase attributes (NUnit tests) can’t use them – only const is allowed. Attributes are set at compile time and not evaluated.



Program Compatibility Assistant

Development Posted on 2011-06-02 17:58

On Windows 7 Microsoft has come up with yet another “assistant”.

The Program Compatibility Assistant may be a great invention for non-developers, but for Developers using Visual Studio 2008 on Windows 7 (x64) it fails to inspire any enthusiasm, because it may change unhandled exceptions into silent failures.

If a vshosted app throws an unhandled exception, then the PCA will detect it, report that VSHost.exe did something bad and prevent any further unhandled exceptions from appearing in VS for the particular vshost execution path. Most annoyingly, PCA reports that it has made the compatibility changes with no option to say “No thank you”.

From then on no Unhandled Exception may make it’s way through to the GUI (neither VS nor the app under development).

This is bad because it gives a false sense of security – the app runs with no problems reported … !

What happens seems to be exactly the same as if the OS automatically pushed the “Continue” button on the Unhandled Exception messagebox.

An example: Create a Windows Forms application, add a statement which may occasionally throw a DivideByZero exception in the Form Load handler and some UI update after the statement, and then run it a few times – sometimes the UI update will happen, sometimes it won’t – but the problem is not reported.

This is really bad – the app which looks like it works well … doesn’t !

As with most other problems this can be prevented with unit-testing, but if the unit-testing isn’t test-driven, but instead the tests are written after the app-code, then it may not be obvious that there is a problem. Which means that it’s now entirely up to the developer to think of every possible thing that could go wrong – instead of just starting the app from VS, and hopefully seeing some of them.

Unfortunately vshost doesn’t handle “unhandled exceptions” very well, which means that even when PCA is disabled, then VSHost will provoke the crash dialog – not a position in the code with the debugger handy.

The problem can’t be worked-around by not using VSHost (Project setting) – that will just provoke similar actions on the app-executable if run with PCA, and the app-crash isn’t caught if running without PCA.

For some unknown reason the unhandled exception won’t necessarily have the same repercussions when the app is run outside VS.

PCA persists the path of the “offensive” VSHost (…MyProject/bin/Debug/MyProject.vshost.exe) in

[HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]

along with

[HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant\Persisted]

VSHost will be marked with a “DISABLEUSERCALLBACKEXCEPTION” value.

PCA is a Service which can be disabled, but don’t forget to check and cleanup the registry associated with it, because the OS will keep using the PCA registry settings when running VSHost and other apps.

[The symptoms described were seen on Windows 7 (x64) running Visual Studio 2008 Professional Edition]



AssemblyCompany – default value

C# Posted on 2011-05-29 13:51

The default value for AssemblyCompany in AssemblyInfo.cs for a new project can be changed in the registry in the value “RegisteredOrganisation” in one of the following keys depending on OS:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion

HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion

The default value is “Microsoft” when the operating system is pre-installed.



Directory.Delete on Windows 7 is not blocking

C# Posted on 2011-05-28 19:10

Having recently upgraded/outdated a development laptop from old faithful Windows XP (32-bit) to Windows 7 (64-bit), we came across a problem which seemed odd at first.

Some unit-tests in a customer project failed intermittently at very unexpected points – it seemed like something went quite wrong with creating and deleting directories, but it wasn’t consistent or even predictable.

Additional symptoms were UnauthorizedAccessException and IOException – The directory is not empty. Both encountered when deleting a newly created empty directory (i.e. created by the same thread which was deleting it).

Digging deeper it looked like sometimes the System.IO.Directory.Delete actually failed silently and Directory.Create succedeed but the directory wasn’t there. It seemed unlikely for this to be caused by either .NET or even the OS acting up – it would seem much more likely that there would be some problem with the unit-tests which was hidden earlier either because the old laptop with XP was slower or the like.

However, after having debugged for a while, the problem could be reproduced quite consistently by running this simple snippet (from an NUnit test):

string dir = @”C:\PROJ\OBJECT.NET\UnitTest\Server\LOGS\Week21″;

for (int i = 0; i < 5000; i++)

{

Directory.CreateDirectory(dir);

Assert.IsTrue(Directory.Exists(dir));

Directory.Delete(dir, true);

Assert.IsFalse(Directory.Exists(dir));

}

[The snippet was run in DevStudio 2008 (9.0.21022.8 RTM), with NUnit (2.5.3.9345) and TestDriven.NET Professional (2.22.2468 / 3.0.2749) using .NET 3.5 SP1 and compile-target Any CPU on Windows 7 (x64)]

Directory.Delete(dir, true) will return before the directory is actually deleted 20-30 times out of 5000 – not a lot, but more than enough to annoy. The delay from the Delete returns and until the Directory actually disappears (Exists = false) can be up to 35-40ms – again, not a lot.

This could be a problem in a lot of both development and production scenarios – not just in a unit-testing environment, where a directory is created before and deleted again after each unit-test is run.

The actual behaviour may be related to Restore Points and versioning or something else, because if the drive in the snippet is changed to a different non-system drive (without Versioning and Restore Points ?) (like a D-drive), then it succeeds – every time.

The point here being that apparently it’s unsafe to assume that Directory.Delete is blocking when running under Windows 7.


The fix in many scenarios is to just hang around after Directory.Delete and wait for Directory.Exists to return false.

However, this isn’t quite enough if a directory tree more than 1 level deep is being deleted. More about this later.



Generic List – Stack Extension methods

C# Posted on 2010-06-03 12:32

Recently while developing a RecentFiles list for a customer application, it became apparent that neither generic List, Stack or Queue offered the desired functionality.

The desired functionality was a hybrid of List and Stack allowing Push onto the RecentFiles (latest at the top of the list) combined with the ability to remove entries anywhere in the RecentFiles (entries which already exist in the RecentFiles should be moved to the top).

Extension methods came up as a possible solution for adding the Stack method Push to List while keeping the List functionality.

The code:


internal static class StackList
{


public static void Push<T>(this List<T> list, T value)
{
list.Insert(0, value);
}

public static T Pop<T>(this List<T> list)
{
T result list[0];

list.RemoveAt(0);

return result;
}

public static T Top<T>(this List<T> list)
{
T result = list[0];

return result;
}

}

The code includes additional Pop and Top methods which seemed nice to have. As List<T> includes an integer indexer, Top isn’t really that necessary – and actually requires more text to use than it’s implementation list[0].

Unittesting the code is straight forward as the functionality is clearly defined. There are no functional dependencies, which would need to be decoupled and mocked etc.



Rhino Mocks

Unittesting with Rhino Mocks Posted on 2010-05-25 20:08

Rhino Mocks is a very useful and very advanced tool for decoupling and Inversion of Control (IOC).

Rhino Mocks allows the developer to decouple (almost ?) any object from the surrounding object-“world” if the dependencies are accessed through an interface, and provided that alternative mocked dependencies can the injected instead.

It allows quite easily to setup stub functionality, i.e. methods/properties which return a specific result. The main functionality, though, is the mocking of objects. It allows setting up expectations as to which methods are called with specific param-values and how many times, as well as quite elaborate ways of manipulating/checking the passed in params to return a specific result. With the latest versions it’s even possible with very little and quite easily readable code to check event subscription, raise events on the mocked objects and check that the UUT (unit-under-test) raises specific events.

To a large extent Rhino Mocks allows use of the AAA-approach (Arrange, Act, Assert), meaning division into 3 stages, the first being arranging the environment – setting up dependencies and the UUT. The second being actually acting on the UUT, e.g. invoking specific methods etc., and the third being asserting that the results are as expected, e.g. testing variable values, testing that specific events were raised / not raised etc.

Rhino Mocks works well with NUnit 2.5 – we use the combination to test units written for .NET Framework 2.0+ (primarily 3.5). Rhino Mocks 3.6 support .NET 2.0 and 3.5.



Software tools

Favourites Posted on 2010-05-02 23:01

TestDriven.NET

Rhino Mocks

NUnit

TextPad

Sun VirtualBox



Next »