Category: C#.NET

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 {
doSomething();
}catch (Exception) {
logError();
}

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.

Windows Service – Marked For Deletion

Windows Services,especially managed .NET ones , can be extremely difficult to deploy if not done correct initially. Errors, of course, can also be very difficult to diagnose if theres a problem immediately after the server starts.

Occasionally, as a developer you need to uninstall the service whether it be through sc delete, or installutil /u . Sometimes, the service isn’t uninstalled immediately and still exists in the server management console. (services.msc) after the uninstall is done.

To reduce the need to restart the machine, we should do the following:

  1. Stop the service.
  2. Close services.msc
  3. Uninstall service.

Why A Restart Is Required

  • Windows 2000 machines, in my experience, have almost always had to have a restart.
  • If the service creates many worker threads, sometimes these threads will also hang around resulting in a restart being required.
  • This is done if CanStop = false in your service code.Windows knows this service shouldn’t be stopped and it will only mark it for deletion but will not delete it right away.

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");
[STAThread]
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");
[STAThread]
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");
[STAThread]
static void Main()
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
//Ensure we release mutex
// In .NET 2.0 AbandonedMutexException is thrown in next thread that acquires mutex
mutex.ReleaseMutex();
}
else
{
//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;
notifyIcon1.ShowBalloonTip(50);
}
}

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

How to Get Path of Running Application

Getting the path of the running application is really simple, and is pretty important if you allow the user to install the application anywhere (which you really should do!) I’ve just included the way to do it for windows forms, but it isn’t that hard to adopt to other situations.


using System.IO;
using System.Windows.Forms;

//......

string executing = Path.GetDirectoryName(Application.ExecutablePath);

Skype API Basics – Part 1

What is the Skype API?
The Skype API is an easy way to create plugins that can dramatically change the way Skype functions. For example, we could make a program that reads messages out loud as we receive them instead of having to check for new messages.

The Skype API is potentially very different for each of the operating systems Skype is available for. And, of course, there are different wrappers of the API available for some of the different languages.

What Operating Systems Are Supported?

  • Linux
  • MAC
  • Windows

What Languages Are Supported?
The Windows API,Skype4COM, is supported in literally any language that can import an ActiveX DLL or using a bit of hackery and some Skype commands we can also use Windows Messages via the Win32 SendMessage API .

Wrappers are available for additional languages that aren’t necessarily updated as frequently as Skype4COM. Skype4Java is a completely cross platform, language specific, implementation of the Skype API. Unfortunately, Skype4Java is infrequently updated and often lags behind the other implementations. Skype4Py is the other language specific implementation of the Skype API and can be used with Python on Windows and Linux.

What is Skype4COM?
Skype4COM is an ActiveX dll for use on Windows. Basically, it offers us a collection of properties, objects, and interfaces that we can use to manipulate Skype. By default, Skype4COM is installed with the Skype Extras although I always think it is prudent to provide it with our application and reference the included version.

What is Skype4Java?
Skype4Java is an older language specific wrapper for use with Java and is pretty much outdated and dying. I haven’t personally used Skype4Java, but have noticed it hasn’t been updated since 2006.

What is Skype4Py?
Skype4Py as previously mentioned is the language specific wrapper for Python and is fully supported on Linux and Windows. Skype4Py contains two different naming schemes: one follows the norms of Python, and the other set of naming conventions resembles Skype4COM.

Why use the Skype API?
There are a lot of interesting applications that make use of Skype to do telemarketing (predictive dialing even!), make Skype act like a fax machine, and even completely replace the need for a telephone! Unfortunately, my first use of the Skype API was to monitor employees that were deleting their Skype history and copy all of the messages sent and received to a location.

How should I get started?
Usually, I start reading a little bit about the API before, I begin to use it but I don’t ever focus in enough to learn the API completely unless I absolutely need to. Instead of spending your time focusing on learning APIs you should instead focus on learning computer programming fundamentals or some website development fundamentals.

More coming next week!

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;
            }
            else
            {
                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.

Read a Whole Textfile Into a String

At work, I’ve been working on an auto html emailer.   I’ve been receiving files from our Latin American office that are completely in spanish and trying to sift through the HTML and recreate the email taking into account size and the fact that Outlook 2007 still doesn’t accept background images and most CSS.

Anyway, one of the files they sent originally that the old software produced didn’t work. And to prove this, I had to somehow figure out how to loop through this text file they’ve been sending and prove this to my boss. I eventually found a function, that would let me avoid the looping, the steam writer and just do it.

System.IO.File.ReadAllText(String fileName)