Archive for the '.NET' Category

Feb 08 2008

Character Counter

Published by under .NET,Software

Whilst reading an article I was curious about the number of commas and full-stops that the author used – when you become an editor of a newsletter you start to think about things like this.  After hunting around the various utilities on my system I discovered that I didn’t have anything that could easily do this.  So, I did what any self-respecting programmer would do and threw together a quick app to do it for me.

I have made both the source code and pre-compiled binary available for download under a BSD license (share, remix, no endorsement).  It is written in C# and requires the .Net 2.0 framework, if you want to compile the source you will probably require MS Visual Studio (Express should be ok), although it may work with SharpDevelop or Mono.

It is a console application (sorry, no pretty GUI this time) that reads the contents of input.txt (in the same directory as the app), it then counts the occurrences of each character and outputs the results to the console. Simple!

If you make any improvements to the code please leave a comment and/or email the changes to me: gringod [at] gmail [dot] com.

No responses yet

Nov 20 2007

Test Driven Porting

Published by under .NET,Bell Ringing,Programming

Recently I’ve had reason to take an code library written in C++ and port it to C#.  Whilst I dabbled in C++ on a compilers course at university, I hated it then and I still hate it now.  I personally think it’s an abomination and should be consigned to the great garbage collector in the sky.   Whilst I can just about read the C++ syntax there is a lot that I don’t understand about it.

The library I was porting had semi reasonable documentation outlining what classes exist and their methods and a brief description of the overall usage.  This gave me a good starting point, however the documentation didn’t include example usages and expected results, for this I was forced to delve into the code.

One development paradigm I have been interested in but have been unable to find a decent project to test it on is Test-Driven-Development and this seemed like the perfect project to try it on.  So I set to work on the first iteration getting the test set up.   Without knowing exactly what results I should be expecting I was finding it hard going, so once again I dived back into the old code.

Thankfully, the developers of the C++ library had create a fairly comprehensive set of unit tests and with my limited C++ knowledge and a text editor with RegEx Find & Replace I was quickly able to convert their unit tests into NUnit based unit tests.

For example, what started out life as:

 1: void test_row_multiply_change(void)
 2: {
 3:  row r;
 4:  RINGING_TEST( ( r *= change( 6, "X" ) ) == "214365" );
 5:  RINGING_TEST( ( r *= change( 6, "1" ) ) == "241635" );
 6:  RINGING_TEST( ( r *= change( 8, "X" ) ) == "42615387" );
 7:  RINGING_TEST( ( r *= change( 5, "3" ) ) == "24651387" );
 9:  RINGING_TEST( row( "214365" ) * change( 7, "5" ) == row( "1234675" ) );
 10: }

Quickly became:

 1: [Test]
 2: public void TestMultiplicationByChange()
 3: {
 4:  Row r = new Row();
 5:  Assert.AreEqual((Row)"214365", r *= new Change(6, "X") );
 6:  Assert.AreEqual((Row)"241635", r *= new Change(6, "1"));
 7:  Assert.AreEqual((Row)"42615387", r *= new Change(8, "X" ));
 8:  Assert.AreEqual((Row)"24651387", r *= new Change(5, "3"));
 10:  Assert.AreEqual((Row)"1234675", new Row("214365") * new Change(7, "5"));
 11: }

Now, with a full set of unit tests at my disposal I was quickly able to bash away at the library and very quickly got working code without the need to trawl through ghastly C++ code.

Hooray for Test-Driven-Development and three cheers for Test-Driven-Porting.

ps. The library I’m porting is an open source library for Bell Ringing – yes I know I’m a geek but anyone that has followed everything else in this post must also be a geek ;-).  Once I’m finished I will be releasing my code under an open source license as well, I just need to pick the right one.

pps. I may have exaggerated my hate of C++ a little.  I believe all languages have their place, even the esoteric languages like LOLCode.

kick it on

No responses yet

Oct 12 2007


Published by under .NET,Programming

Many, many times in my programming life I have seen people causing themselves all sorts of problems as the try and concatenate paths for file and directories.  They’re always trying to work if the path already ends with a directory separator or not.  And then there are the cross platform systems that try  to workout what the directory separator should be.

With the release of the .Net platform,  Microsoft gave developers that need to handle file system operations a wonderful, but underused, utility class: System.IO.Path.  One of the methods on this class is Combine().  It take two arguments: path1 (string) and path2 (string), and intelligently combines them.

That’s it!  No more messing around with string concatenation or endless if statements or figuring out if it should be a forward or backslash… just Path.Combine().

kick it on

5 responses so far

Sep 30 2007

Really Simple Dependency Injection

Published by under .NET,Programming

Having just started a new job I find it interesting to see the way that the other developers I’m working with do things. One of the things I found in the code was for doing dependency injection. I’m not going to analyse that code as but what I will say is that I managed to replace 10 lines of code with just 3.

Without further ado here is the C# code:

public static T Get<T>() where T : class
string implName = Program.Settings[typeof(T).Name].ToString();
object concrete = Activator.CreateInstance(Type.GetType(implName));
return (T)concrete;

So what can you do with this code? Well, the way it is written means that you can create an object, the class of which is defined in a configuration file. This allows you to program to an interface but decide the concrete class in the configuration file. The method above will find the class defined for the interface being passed in, create an object of that type and return the object cast to the type of the interface.

The code used to call the method:
IPlugin plugin = PluginFactory.Get<IPlugin>();

plugin.OutputMessage("hello, world!");

The definition in the config file:
<setting name="IPlugin" serializeAs="String">

I’m sure I haven’t explained terribly well, so I’ve thrown together a simple example that you can download. I should point out that this code a very simple example of dependency injection, it doesn’t handle passing values to the constructor of the object being instantiated, although it would be simple to add that. Also, the example I have included statically links to the two plugin assemblies, this could be changed such that the plugin assemblies are dynamically loaded using Assembly.Load()

If you want a more fully featured implementation of dependency injection you should check out the Spring.Net framework.
kick it on

Technorati Tags: , , ,

3 responses so far

Aug 09 2006

Environment NewLine Warning

Published by under .NET

I just found a site (via that is advocating the use of Environment.NewLine.

I would agree that it is good to go with the use of Environment.NewLine as it adds an extra layer of platform independance, i.e. you don’t need to worry about whether to use \r\n or just \n, and you don’t need to worry so much about what happens when you port the code from one .Net language to another. It isn’t however the answer to all problems.

Environment.NewLine only answers the problem of new line on the machine that it is running on. Where you may still run into problem is when you create a file using Environment.NewLine and then move the file to another platform. This is an age old problem and I don’t have a solution for it, just that you should be under no illusion that Environment.NewLine will solve this problem.

No responses yet

Feb 01 2006

Double Imprecision In .Net

Published by under .NET

I’ve spouted on about this previously on my blog but I thought it was about time I posted some code that demonstrates some of the problems we’re up against. The problem seems to be that under certain circumstances the .Net Double data type loose its precision and gives you a number that you weren’t expecting. The chances are that the error will be out by 0.00000000000001, but that might be enough to cause an error.

The simplest way to prove this error is with a simple loop:

Dim x As Double = 0.00
While (x < 7.00)
    x += 0.01
End While

What you would normally expect is a linear progression from 0.00 to 7.00:


However, when the code is run you will find that somewhere in the output is some results like this:


This, as I am sure you will agree, is an unexpected result and could result in errors. If you try this exercise again but using Decimal instead of Double you will find that you get the results you expect. I’m sure there are people out there that will say that all you need to is simple rounding to get rid of the error. Sorry, but it doesn’t quite work like that and the following code will prove it:

Dim x As Double = 0.00
Dim y As Decimal = 0.00
While (x < 7.00)
    If (Math.Round(x) = Math.Round(y)) Then
        Console.Writeline("Error found")
    End If
    x += 0.01
    y += 0.01
End While

If you run this could you should get at least one error message, and probably more.

Is there a solution to this problem? Of a sort, yes. I have found that using the Decimal data type does not give the same rounding problems. Decimal also solves problems that I have had in the past with the Math.Floor() function. However, several people have told me that using the Decimal data types does incur a slight memory cost over using the Double data type. The question you need to ask yourself is “What is more important: memory or precision?“. Personally I now always use the Decimal data type. Maybe one day I’ll get around to doing some benchmarks to find out if there is a performance hit when using Decimal rather than Double… But that’s a job for another day.

3 responses so far

Jan 10 2006

Playing a wav resource in VB.NET 2.0

Published by under .NET

This is a follow-up to my previous post “Playing a wav from a resource in VB.Net“.  The previous post was how to get it working in VB.Net for the .Net Framework 1.1.  In the .Net Framework 2.0, Microsoft has been kind and provided a System.Media namespace in the core System.dll.

I happened across this file quite by accident but it seems that it will greatly simplify the code that was required for .Net 1.1.  The code for .Net 2.0 looks something like:

Imports System
Imports System.Media
Imports System.Resources
Imports System.Reflection
Imports System.IO

Public Class Sound
    Public Shared Sub PlayWavResource(ByVal wav As String)

        ' get the namespace	
        Dim strNameSpace As String = Assembly.GetExecutingAssembly()_

        ' get the resource into a stream
        Dim resourceStream As Stream = Assembly.GetExecutingAssembly()_
                                     .GetManifestResourceStream(strNameSpace + "." + wav)
        If resourceStream Is Nothing Then Exit Sub

        With New SoundPlayer(resourceStream)
        End With
    End Sub
End Class

As you can see we no longer require the calls to the Win32 API. Whilst this may not mean much to the average Joe Bloggs, it is rather important. It means that we can now play wavs from a resource stream without breaking out of managed .Net code…. I knew you’d be excited by that!!!

Note: I haven’t tested this code yet. This is only code dervied from looking through the Object Browser in Visual Studio 2005.  If you copy and paste this code you will also need to re-type the single and double quotes as WordPress screws them up.

No responses yet

Nov 29 2005

File System Alert

Published by under .NET

For a project that I’m working on we’ve recently switched from using the .Net Framework 1.1 to using the .Net Framework 2.0. Whilst .Net 2.0 does have some nice features (Generics, System.Management, XHTML compilance in ASP.Net, refactoring tools in VS2005) there are also some problems with it.

One of the problems we have had is that, for no apparent reason, our IIS server will create a memory dump. So far there doesn’t seem to be any correlation between user activity and the dump files being created. Due to the fact that the dump files and event messages generated by IIS are less than helpfull – thats putting it mildly – I resorted to Microsofts latest debug tools, DebugDiag, to help me sort out what the problem could be.

The only trouble is that I don’t have all day to sit around waiting for DebugDiag to create its more informative memory diagnostic dumps, I’ve got work to be getting on with. What I needed is a piece of software that would inform me when file in the DebugDiag output folder is created. The .Net framework provides a component that can do just such a task called the FileSystemWatcherunfortunately it doesn’t have an interface. So, as any programmer would to when faced with a task, I went ahead a created a neat little software tool that sits in my system tray and alerts me when files in the DebugDiag folder are created.

However, I didn’t stop there. Why should I create a tool with such a narrow market. Surely if I want to watch one folder for new files, at some point I’ll need to watch other folders, maybe I’ll need to watch for other events such as changed and deleted files. Enter File System Alerts. In this tool users can create any number of watches with varying settings. Users can be notified by a system tray alert, the alert window being brought to the foreground and a log file being created.

THe latest version of the installer can be downloaded from my Downloads page. At time of going to press the latest version is 1.0.2159.28024.

No responses yet

Oct 28 2005

Suspect Rounding In .Net

Published by under .NET

For the past week (might be a slight exageration) I have been working on two rather complex and long winded calculations for a certain project that I am working on. I have been given a set of data to run through the calculations and a list of expected results. Unfortunately I have been receiving some rather unexpected rounding results and as soon as I manage to fix the rounding for some of the dataset it seems to throw out the results for other items in the dataset.

Unfortunately I am unable to step through the code as it is running the calculation and (until late on Friday) I was only able to output one result value. As a result I debugging has been a rather slow and laborious process. On Friday I implemented a debugging system that let me not only output a final result but also log various values throughout the calculation process.

Today I finally I managed to track down the round problem to the .Net Math.Floor() function.

From the MSDN library:

Returns the largest whole number less than or equal to the specified number.

[Visual Basic]
Public Shared Function Floor(ByVal d As Double) As Double

A number.

Return Value
The largest whole number less than or equal to d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, then that value is returne

The code that was causing me problems was the following:

Public Function Truncate(number As Double, places As Integer) As Double
    Dim temp As Integer = Math.Floor(number * Math.Pow(10,places))
    Return temp / Math.Pow(10,places)
End Function

What this code does, is take a floating point number and truncate it to a user specified number of decimal places. For example Truncate(125.12542, 2) should give a result of 125.12. It should also be possible to truncate to 0 decimal places using, for example, Truncate(125.12542, 0) should give a result of 125.

The trouble I was getting, however, was that I was calling Truncate(1001.010, 2) and I was getting a result of 1001.00 when the result should have been 1001.01. As you can imagine, when you are working with financial calculations even a penny out is far from acceptable…. all calculations have to be exact. So this problem had to be resolved.

I’m not about to give you a run down of the whole debugging process that I had to go through as it took several days and a lot of caffine and stress. But in the end I tracked to the problem to being the fact that I had used the Double vairable type. For some reason, which I’m still not entirely aware of, the is some odd rounding when rounding Doubles. These issues seem to disappear if you use variables of type Decimal. So I spent a whole day going through my code replacing all instances of Double with Decimal.

Now that I have completed that all my code is now producing the correct results. If only Microsoft had made these issues more clear in their documentation I might have saved myself several days work and a lot of stress.

2 responses so far

May 25 2005

MojaviBuilder Under Mono?

Published by under .NET,MojaviBuilder

Having subscribed to the MWF blog I noticed today that they have finally posted a new entry.

Whilst this in itself isn’t too interesting, some of the information in the entry is interesting. Firstly, the MWF (Microsoft Windows Forms) project for Mono is now up to 98% complete. Most of the basic controls are now complete.

The second interesting piece of information is that you can now get a Live CD for mono. The CD is freely available as an ISO which can be downloaded directly via HTTP or via BitTorrent (see

The upshot of all this is that hopefully MojaviBuilder will now run under Mono. I have downloaded the ISO via BitTorrent which I’ll burn to CD when I get home and then have a go and running MojaviBuilder. If it does run then I’ll know I can go continue developing MojaviBuilder in .NET 1.1 safe in the knowledge that I can be run under Windows, Linux, and MacOS.

2 responses so far

« Prev - Next »