Category: .NET Framework

CSV Parser

For some of my work, I work on data importers and other different tasks which require dealing with CSV and tab delimited files which can often be very challenging to parse. I was sick of rolling my own csv/tab delimted parser, so I went ahead and found one that worked very well on CodeProject simply called CsvReader.

CsvReader works very similar to the StreamReader which is a firehose cursor (only going forward) and is capable of parsing very quickly (30+ MB/s). CsvReader can also be databound if there’s a need by using IDataReader. Using CsvReader is fairly simple and doesn’t really require much more than adding a few references to your project and simple array handling.

Hope this helps, it sure made things simpler for me.

try..catch Usage – Unused Variable Warning

Elminating the unused variable warning for a declaration in the catch block is very easy because you don’t need to assign to a variable.

See the below code for an example.

try {
}catch (Exception) {

Note: you should always log an exception if it isn’t expected. For example, for any IO Related exceptions you should probably log these.

Hope this helps.

Stopping a System.Threading.Timer

Stopping a System.Threading.Timer isn’t very well covered in the MSDN documentation.

We need to use the Change Method which accepts two integers. Please note that it is possible that a few callbacks can be potentially queued and called after you have stopped the timer. This is because the callback of the System.Threading.Timer uses worker threads.

To stop the timer we use the following code in C#.NET

mytimer.Change(Timeout.Infinite, Timeout.Infinite);

Hope this helps.

Run a Single Instance of An Application (.NET)

Occasionally, as a software developer you want to restrict a user to only allow them to run one instance of an application on their machine. The reasons why vary dramatically, but often it is because it could make large system changes, maybe their is some business reason, or perhaps it just doesn’t make sense.

Restricting an application to only run one instance is actually really simple in .NET although it does require a little bit of thinking and explanation. Most software developers with a university education would have read “Operating System Concepts” and spent significant time hearing about mutexes and other different solutions provided by the operating system or virtual environment.

The simplest and best method of only allowing one application to be used is to use a mutex in program.cs in the Main method. We will not search the process table as this really only works if the user doesn’t make a copy of the application and change the name.

What is a mutex? Mutex is short for mutual exclusion. A mutex is a protected variable that provides a method of controlling access also known simply as a lock. If you have done any serious multi-threading you have probably used the lock object, or a mutex to control access to critical sections of code. The MSDN includes a great description of the mutex class and should be referenced.

The real elegance of using a mutex is that the operating system will keep track of it, and ensure that another process can’t be started as long as the mutex runs. Of course, using a mutex also is the cleanest and simplest code. 🙂

We begin adding the code by opening program.cs and then by creating the mutex in static class Program. We need to ensure we pass in something relatively unique as the string in Threading.Mutex, often I use the name of the application or the GUID what you use is really up to you.

static class Program
static System.Threading.Mutex mutex = new System.Threading.Mutex(true, "9245fe4a-d402-451c-b9ed-9c1a04247482");
static void Main()

The real advantage of having the named mutex is that we’re able to use it literally anywhere on the machine to check and see if the process is running. We will be using one of the overloaded constructors to ensure we don’t wait for the mutex. We do this because we’re not synchronizing threads, and in most cases it wouldn’t really make sense to wait for one application to close so we can start another. We pass in true because we don’t want to try and acquire the lock if it already exists.

Our program.cs looks like the following so far.

static class Program
static System.Threading.Mutex mutex = new System.Threading.Mutex(true, "9245fe4a-d402-451c-b9ed-9c1a04247482");
static void Main()
if (mutex.WaitOne(TimeSpan.Zero, true))

We now need to add the contents to our if block and then eventually decide on what to do if an instance is already running. I typically just notify the user through a messagebox or console window depending on what the application is for.

static class Program
static System.Threading.Mutex mutex = new System.Threading.Mutex(true, "9245fe4a-d402-451c-b9ed-9c1a04247482");
static void Main()
if (mutex.WaitOne(TimeSpan.Zero, true))
Application.Run(new frmMain());
//Ensure we release mutex
// In .NET 2.0 AbandonedMutexException is thrown in next thread that acquires mutex
//Maybe log this to file
MessageBox.Show(Application.ProductName + " is only allowed one instance.");

It could also be possible to use the Windows API and focus the other application. Generally, if you’re working on a normal windows application just notifying the user is acceptable. I generally try my best to avoid the Windows API in .NET.

We need to ensure we release the mutex. “If a thread terminates without releasing a Mutex, the mutex is said to be abandoned. This is a serious programming error because the resource the mutex is protecting might be left in an inconsistent state.” MSDN

Keep in mind that in at least .NET 3.5, if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.

How to Minimize Application to Tray

I’m not sure how many times I have been someone ask for help on the MSDN forums, email me, or come over and ask me in the case of coworkers. The steps to have an application minimized to tray are very simple.

      Create .NET Windows Application.
      Create .NET application.
      Add Tray Notifcation Icon to Windows form.
      Create Icon (using .NET, or other software). The icon should be 16×16
      Using either code or the visual editor you need to add the icon.
      As you may have noticed there’s no minimize event on the form. We need to use the form’s Resize Event and make sure that we check to see if the WindowState is Minimized. If the WindowState is minimized we need to make our form invisible and make the tray icon visible.
      Depending on your application, and how you have designed things you should use either the click or doubleclick events on the notifyicon to set the visibility of the form again and hide the trayicon again.

//No Minimize Event, so we need to use Resize event & check WindowState
private void frmMain_Resize(object sender, EventArgs e)
if (this.WindowState == FormWindowState.Minimized)
this.Visible = false;
notifyIcon1.Visible = true;

//Make form visible and notify icon invisible.
private void notifyIcon1_Click(object sender, EventArgs e)
this.Visible = true;
notifyIcon1.Visible = false;

Subversion On Windows?!

It’s no secret that I have been contact almost daily by Technical Recruiters , often the job advertisements that the technical recruiters have been sending me include a requirement for Microsoft SourceSafe experience. I often wonder a company would choose SourceSafe to manage their code as it doesn’t really do a good job: the only go thing I guess is the integration with Visual Studio TFS.

The company I currently work for didn’t have any sort of source code management when I started. Literally, I had a budget of zero to string together something that was flexible enough and could integrate with Visual Studio 6 and Visual Studio 2005. I was able to find something that perfectly fit my needs, cost nothing other than a few hours to implement and about 1/2 an hour of research.

For the Windows server, I needed something that was mostly graphical because the other programmer basically has a fear of the change so I know he won’t be using any of the SVN commands. I also really wanted something that would use Active Directory for authentication if possiblex, because I absolutely hate having to remember yet another password that should be changed in three months. (If it uses Active Directory, I can do a Single Sign on which I believe is absolutely fantastic!) I chose to use VisualSVN Server Standard Edition because of the fairly simple graphical user interface, and Active Directory support. The only thing I’m a little disappointed about is that I have to Remote Desktop into the machine to do some remote tasks.

For the developer machines, I wanted to also have at least one graphical version for subversion. I chose to use TortoiseSVN which is absolutely fantastic and supports all of the SVN protocols that I know and also integrates very well with Windows Explorer even showing what files you have changed since you last commited!

For Visual Studio 6, I was able to use SVNVB6 which works okay but isn’t really ideal. It doesn’t really comply with any of the Microsoft Best Practices for plugins, some things aren’t really fully integrated and the project has really strange scheduled downtime each week.

For Visual Studio 2005, I wanted to be able to right click on any of the files or the project and of course be able to commit my changes. For Visual Studio 2003 + there are quite a few options, I ended up using VsTortoise but Anksvn is also a very good solution.

What Source Code Management system and plugins do you use?

Determine if Skype is Installed

The easiest method of checking whether Skype is installed is actually to check for a Registry Key. We, of course, can’t check C:Program Files for a Skype Directory because the user could have installed elsewhere (or maybe if 64 bit the operating system did?)

Skype’s API Document provides us with the following information:

To check if Skype is installed, in regedit check if the following key exists: HKCUSoftwareSkypePhone, SkypePath . This key points to the location of the skype.exe file. If this key does not exist, check if the HKLMSoftwareSkypePhone, SkypePath key exists. If the HKCU key does not exist but the HKLM key is present, Skype has been installed from an administrator account but not been used from the current account.

Generally, I only care if the Current User has configured Skype, so I will ignore the HKEY_LOCAL_Machine information and instead rely entirely on the HKEY_CURRENT_USER information.

You must make sure you reference: Microsoft.Win32 for the registry functions or modify the snippet slightly.

        using Microsoft.Win32;

        //Function uses Microsoft.Win32 to check registry value of 
        //HKEY_CURRENT_USERSoftwareSkypePhoneSkypePath and returns false if
        //the key is null
        private bool isSkypeUser()
            RegistryKey skype = Registry.CurrentUser.OpenSubKey(@"SoftwareSkypePhone");

            if (skype != null && skype.GetValue("SkypePath") != null)
                return true;
                return false;

Books I’ve Read

Sometimes, when I have applied for full time employment in the past I have seen job ads or received responses from companies asking what books I’ve read. Nearly every time, I have heard this question I was so shocked because I didn’t ever keep track of what I had read or where I had gleamed those little bits of valuable information.

This list will be updated at least monthly, although when I have an abundance of extra time I might be able to read an additonal book or two. Please note that this list only contains books I am interested in professionally and in no specific order.

Books Finished:

  • ASP.NET 2.0 Unleashed
  • Beginning Ubuntu Linux
  • C# How to Program
  • Code Craft: The Practice of Writing Excellent Code
  • Don’t Make Me Think: A Common Sense Approach to Web Usability
  • jQuery In Action
  • Network+ Guide to Networks
  • Learn to Program With C++
  • Practical Web 2.0 Applications with PHP
  • Systems Analysis and Design in a Changing World
  • Teach Yourself HTML 4 in 24 Hours
  • Visual Basic 6 Complete
  • Web Style Guide: Basic Design Principles for Creating Web Sites

Currently Reading:

  • Operating System Concepts

Although the list is getting pretty extensive, please understand that these are books I can verify as of September 7th 2009. The title suggests this is only books, so please remember that I definitely have visited many websites along the way.