Which process is using the serial port in Windows?

Which Windows process is has the COM port open, and is blocking other processes from using the serial port?

Yes you read that right.. COM ports and serial line communications. Serial line communication, whether it is the RS-282 og RS-485 standards, is still in use at thousands, if not more, industrial plants and ships all around the world.

A frequent problem when accessing Windows COM ports by software is that the port is already open and in use by another application. Quite a similar problem as when another process has a IP port open!

Cut to the chase: Sysinternals Process Explorer comes to the rescue yet again! This amazing piece of software can easily find processes which have particular COM ports open. You could probably find this information by manually entering WMI-queries (a SQL-like language for querying Windows about all sorts of system information), but it is so much easier with Process Explorer.

It’s easy as pie:

Ctrl+F in Process Explorer (Find -> “Find by handle or DLL”).

In the search box type “\Device\Serial”. All processes with open Serial lines will appear in the search results!

Searching for a single COM port is of course equally simple, COM1 = \Device\Serial0, and so on.

Note one caveat: if you have this search box open while you are launching a process, then Process Explorer will show “<Non-existent Process>” instead of the proper process name. Simply close the search box and open it again, and Process Explorer will refresh it’s internal state and show the correct process name. As long as the process is alive of course.

Happy process hunting!

When breakpoints cannot be hit in C++ code

Occasionally the debugger will not be able to hit a breakpoint in C++ code. For instance in Visual Studio the breakpoint will be grayed out or something similar. Now, considering that you double checked that the breakpoint is in fact active, here are a couple of reasons why you might have this problem.

1. The debugging symbol files are outdated.  

In Visual Studio these are *.pdb files, while in Rad Studio these have the extension *.tds. A simple way of fixing this is to delete the debugging symbol files and rebuild the solution. Rebuilding should delete and recreate the files if necessary, but to be 120% sure you can delete them yourself.

See also this SO answer Stackoverflow post

 2. The code is not compiled into the executable.

While you are working in the IDE the breakpoint will look fine and dandy, but then it becomes inactive or “un-hittable” the moment you run the executable. The problem may be that the code not included in the executable due to conditional compilation. For instance, consider what happens in the following pseudocode if CALL_INNER is not defined:

class ExampleClass
{
    void Outer()
    {
#ifdef CALL_INNER
        Inner();
#endif
    }

    void Inner()
    {
        // Do stuff
    }
}

Assuming there are no other calls to Inner(), other than the one in Outer(), then any compiler today will optimize away Inner() when CALL_INNER is not defined. So breakpoints in Inner() cannot ever be hit.

Powershell reminders

Another useful tool on Windows is Powershell, but it seems that every time I use it I have to Google the right way of doing things. Probably because I don’t use it every day (or week). Anyhow, it’s a very useful piece of software for those odd tasks that show up sometimes.

What’s great about powershell is that it combines all the usual shell goodness (pipes, redirects, and more) with more or less the whole .NET Framework! Many people have used it for years to automate all sorts of tasks.

Dead easy powershell  commands for working with text data:

Replacing strings (example replaces semicolon with win newlines):

 "one;two;three" -replace ";", "`r`n"
 one
two
three

And if you want to keep the semicolons as well:

 "one;two;three" -replace ";", "$&`r`n"
 one;
two;
three

Sorting files, which is also dead easy:

 type .\messy_file.txt | sort > sorted_file.txt

But there is a catch! sorted_file.txt will end up with unicode encoding, which is not always what you want. Luckily it turns out that the redirect operator > is just syntactic sugar anyway, and the whole thing can be written as

 type .\messy_file.txt | sort | out-file -encoding unicode -filepath sorted_file.txt

The list of supported output encodings are in the docs, but I do believe it supports these at least:

unicode  — (16-bit)
utf8
ascii

Recursively deleting certain files with powershell

 ls -recurse -filter *.obj | rm
 

Find X latest modified files

 ls -recurse | sort -property LastWriteTime -descending | select -first 20

Count lines in a file matching pattern

Here i Count all the .cpp files in a Visual Studio 2012 project file:

 Get-Content MyProject.vcxproj
 | Where-Object {$_ -match "<ClCompile.*.cpp`""}
 | Measure-Object
 

Powershell has the Measure-Object cmdlet, which is much like “wc” in Unix.
The grave accent character ( ` ) is the Powershell escape character.

Find files or directories having a certain name

The Where-Object cmdlet also be used to for matching file or directorynames.

This is an example of finding all the GIT repositories in a directory tree:

ls -recurse -force | where {$_.Name -eq ".git"}

It is important to include the “-force” switch to powershell “ls”, because .git directories are hidden and will not be found unless that switch is included.

Powershell grep : list files containing pattern

 ls -recurse | select-string -pattern "something" -list | select Filename

This simple command will list each file once which contain a specific pattern. The final select is not necessary, but avoids outputting context around each match which is often very useful when searching binary or autogenerated files.

SQLite3 reminders

Time to dust off this old blog again.. I’ve been using the brilliantly light-weight SQLite 3 database on several different projects lately, but there is always some tricks I easily forget. To avoid wasting time with the documentation I’ll write them down here.

So far there is only one:

Unix time to human readable time:


SELECT datetime(1361865600, 'unixepoch');

2013-02-26 08:00:00

Unix time utility site: http://www.epochconverter.com/

Resetting autoincrement columns / fields

SQLite maintains the current largest counter value in the special SQLITE_SEQUENCE table. So really all you have to do is set the “seq” column to zero on the row for your table in SQLITE_SEQUENCE.

E.g. deleting all rows and resetting the counter value:


DELETE FROM MyTable;

UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE name = 'MyTable';

Programs which bind to port 80 on Windows

Here is a list of programs on Windows that may be using port 80.

A reoccuring problem when running web servers like Apache locally, or doing other kinds of work requiring port 80, is that something is already using the port!

For future encounters with this problem I’ve created a cheat sheet:

Programs which may be using port 80 on Windows

Application Type Display name or image name
IIS Service World Wide Web Publishing Service
MsDepSvc Service Web Deployment Agent Service
Skype Application Skype.exe
SSRS Service SQL Server Reporting Services

It is possible to discover which program has bound to port 80 using a combination of Netstat and Task Manager, or even better by using the Sysinternals tools TCPView and Process Explorer. I will add more programs to the list as I encounter them.

Today’s palindromic date

Today is very special day – in a way.. You see, today’s date is the same when read forwards or backwards – it’s a palindrome!

Well, at least if you live in a parts of the world with a date format such as day-month-year or year-month-day and you are using the Gregorian calendar. But that does cover a huge chunk of the world’s population, according to Wikipedia.

Allow me to demonstrate:

21. february 2012 = 21.02.2012 = 21022012

It turns out that today will be the last palindromic date in a while. The next one does not occur until 02.february 2020. It’s probably a sign, for sure.. 🙂

I created the little hack listed below for finding palindrome dates. It looks for palindromes both using the typical western date format, the North American format, and the ISO format for dates. The palindromic dates for the last 3 years and next 10 years are:

2010-01-02: 20100102
2010-02-01: 01022010
2011-02-11: 11022011
2011-11-02: 20111102
2012-02-21: 21022012
2020-02-02: 02022020
2020-02-02: 02022020
2021-02-12: 12022021
2021-12-02: 20211202

Here is the source:

/* 
 * Palindromic date finder hack 
 * By Lars Warholm, Norway
 * Copyright 2012 larslab.com
 * Released under GNU GPL v3.0
 */
using System;
using System.Collections.Generic;
using System.Linq;

namespace PalindromicDates
{
    public class PalindromDate
    {
        public DateTime Date { get; set; }

        public string PalindromicForm { get; set; }
    }


    public static class StringExts
    {
        public static string ReverseString(this string str)
        {
            char[] reverse = str.Reverse().ToArray();
            return new string(reverse);
        }
    }


    class PalindromicDateFinder
    {
        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }


        /// <summary>
        /// Look for palindromic dates in range StartDate .. EndDate
        /// </summary>
        public PalindromDate[] FindPalindromes()
        {
            List<PalindromDate> palindromes = new List<PalindromDate>();

            palindromes.AddRange(FindPalindromes("ddMMyyyy"));
            palindromes.AddRange(FindPalindromes("MMddyyyy"));
            palindromes.AddRange(FindPalindromes("yyyyMMdd"));

            palindromes.Sort((x, y) => { return x.Date.CompareTo(y.Date); });

            // remove duplicates
            for (int i = 0; i < palindromes.Count-1; i++)
            {
                if (palindromes[i].Date.CompareTo(palindromes[i + 1].Date) == 0)
                {
                    palindromes.RemoveAt(i + 1);
                }
            }

            return palindromes.ToArray();
        }


        /// <summary>
        /// Look for palindromic dates in range StartDate .. EndDate, using the specified date-to-string format
        /// </summary>
        private PalindromDate[] FindPalindromes(string dateFormat)
        {
            List<PalindromDate> result = new List<PalindromDate>();

            DateTime day = StartDate.Date;
            DateTime endDay = EndDate.Date;

            while (day.CompareTo(endDay) < 1)
            {
                string dayStr = day.ToString(dateFormat);

                if (dayStr == dayStr.ReverseString())
                {
                    result.Add(new PalindromDate() { Date = day, PalindromicForm = dayStr });
                }

                day = day.AddDays(1);
            }

            return result.ToArray();
        }



        static void Main(string[] args)
        {
            var p = new PalindromicDateFinder() { StartDate = DateTime.Now.Subtract(new TimeSpan(1100,0,0,0)), EndDate = DateTime.Now.AddDays(3650) };
            var palindromeDates = p.FindPalindromes();

            Console.WriteLine();

            foreach (var pDate in palindromeDates)
            {
                Console.WriteLine("{0:yyyy-MM-dd}: {1}", pDate.Date, pDate.PalindromicForm);
            }

            Console.WriteLine("Press Enter to quit");
            Console.ReadLine();
        }
    }
}

Using byte arrays as dictionary keys in NBEncode

I very rarely use dictionary keys other than built-in types such as strings or ints – there are not that many cases where a user defined class is necessary in the types of systems I work on (administrative and financial systems mostly). So I came upon a few fun challenges while implementing the NBEncode’s BDictionaries, which represent bencode’s dictionaries.

These dictionaries, or hash tables if you prefer, must use a BByteString object as key. BByteString objects are the library’s internal representation of bencode byte strings. They are really just arrays of bytes. A BByteString object may represent a text string, but this is entirely context dependent, and they should always be considered binary data when used as dictionary keys.

For more information on bencode, bencode dictionaries and byte string, check out the link to the
bencode specification at the end of this post.

Since the standard string implementation of GetHashCode goes out the window it is necessary to create a custom one for BByteStrings. I chose to go for a well-known hashing scheme based on a polynomial like this:

hash = c[b0] + c^2[b1] + c^3[b2] + ... + c^N[bN]

b0,b1 etc are the bytes at index zero, one and so on from the byte string used as dictionary key. The constant c is often chosen to be 37 or 31, because this gives a reasonably good spread of hash values.

The implementation of GetHashCode() for BByteString objects thus looks like this:

public class BByteString : BObject<byte[]>
{
	private const long maxBytesToUseInHash = 12;
	private const long hashCoeff = 37;
	// other code not shown in this example

	public override int GetHashCode()
	{
		long hashValue = 0;
		long maxTableSize = (long) UInt32.MaxValue;
		long bytesToHash = Value.LongLength < 12 ? Value.LongLength : maxBytesToUseInHash;

		for (long i = 0; i < bytesToHash; i++)
		{
			hashValue = (hashCoeff * hashValue + (long)Value[i]) % maxTableSize;
		}

		int returnValue = (int)(hashValue - (long)Int32.MaxValue) - 1;
		return returnValue;
	}
}

The loop that calculates the hash value uses Horner’s rule for calculating those kinds of polynomials. It is also known as Horner’s scheme. The number of bytes to hash (“bytesToHash”) is capped to prevent an unecessarily long calculation. Horner’s rule is often taught in undergraduate Algorithms and Data Structure courses.

Close, but no cigar..

The hashing scheme for BByteStrings worked well when inserting key-value pairs in the BDictionary objects. However finding and fetching objects from the BDictionaries would fail. Debugging the hashing algorithm did not reveal anything, as different instances of the same byte strings always produced the same hash value. So it seemed that I forgot something else.

After a little headscratching ILSpy was brought in to have a look at the .NET Dictionary<K,V> implementation. (ILSpy is available at http://wiki.sharpdevelop.net/ILSpy.ashx).
Beginning with the Dictionary’s ContainsKey-method, I ended up at the FindEntry-method shown below:

// System.Collections.Generic.Dictionary<TKey, TValue>
private int FindEntry(TKey key)
{
	if (key == null)
	{
		ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
	}
	if (this.buckets != null)
	{
		int num = this.comparer.GetHashCode(key) & 2147483647;
		for (int i = this.buckets[num % this.buckets.Length]; i >= 0; i = this.entries[i].next)
		{
			if (this.entries[i].hashCode == num && this.comparer.Equals(this.entries[i].key, key))
			{
				return i;
			}
		}
	}
	return -1;
}

In the inner if-test it does a check of the keys’s hash code, but it also checks for object equality between the existing key and the passed in key. Since the default implementation of object.Equals just checks for referential equality this would not work. No keys other than the original key object would ever be found equal!

As often is the case the solution was simple enough. The BByteString Equals method ended up looking like this:


public class BByteString : BObject<byte[]>
{
	// other code omitted

	public override bool Equals(object obj)
	{
		bool equals = false;
		if (obj is BByteString)
		{
			var byteString = obj as BByteString;
			equals = Value.IsEqualWith(byteString.Value);
		}
		return equals;
	}
}

Since BByteStrings are really byte arrays, it is necessary to compare the both object’s byte arrays to each other to determine if they are equals. The method uses a byte array extension method called IsEqualWith, which is also included in the NBEncode library. It simply loops over both arrays, checking for differences. A possible future optimization on this could be to calculate and store a hash values of the byte arrays, and compare that instead – since those values could be stored and reused.

All in all solving little mysteries like this make it interesting and satisfying to code, and you learn something in the process. I think this does it for NBEncode for now, and I am looking forward to doing other hobby projects.

Resources

A concise overview of the “bencode” encoding can be found here:
The BEncode specification (and more)

NBEncode is available from this link:
NBencode, a bencode library for .NET

A BEncode library in C# .NET 4.0

NBEncode is a .NET implementation of Bittorrent’s bencode protocol, written in C# 4.0. It encodes and decodes bencode streams, and has an easy to use object model.

Since bencoded .torrent files are going away in favour of magnet links, I decided to create this library as a small tribute to the format. Torrent-files have been an effective and innovative way of distributing bits, such as free or open sourced software.

Overview of NBEncode

NBEncode is a simple little library, thanks to the elegant simplicity of the bencode protocol. However, the library can easily be used for real world applications, for instance data storage, data transfer across networks, or certain classes of RESTful web services. The bencode protocol can be an attractive alternative to JSON or XML when you do not require built-in support for floating point numbers, GUIDs and the like, or when you are handling quite a lot of binary data.

NBEncode is..

    • Fully object oriented
    • Stream oriented
    • Builds a typesafe object graph when decoding, like the DOM way of reading XML.
    • Encodes from an object graph to a stream
    • Contains a full set of MSTest unit tests
    • Comes with a sample console application for parsing bencoded files, such as .torrent-files.
    • Released under the GNU GPL 3.0 license

The NBEncode sources are hosted on GitHub.com: https://github.com/lars1/NBEncode.git

Old code drop:
NBEncode source of august 5. 2012

Azure WebRole will not start after upgrade to November 2011 release / Azure 1.6

I have been working on a fairly feature rich Azure project for a year now. Having gone through Azure 1.1 to 1.6 has been both fun and interesting, but also trying at times because of various bugs.

After recently upgrading to the Azure November 2011 release 1.6 libraries and corresponding SDK the Azure project refused to run locally.

DevFabric startup would stop, with Visual Studio displaying the message “Role Instances are taking longer than expected to start. Do you wish to continue waiting?”

Azure WebRole will not start after upgrade to Azure November 2011 release (Azure 1.6)

The dreaded “Role Instances are taking longer than expected to start” message

Azure Compute emulator would stop at: [Diagnostics]: Starting configuration channel polling – before an error occured, a shutdown event was signalled, and the whole process would start over again.

Searching for the cause

A systematic search for the reason was the first and best option. A little googling revealed some possible causes:

  • Trace listeners could be causing the problem. Disabled all tracing, both sources and listeners, but no change
  • Service configuration change event handlers could be causing the problem. Disabled all of them but no change
  • The sites tag in ServiceDefinition.csdef could be causing the problem. Commented it out but no change

Finally I came upon the idea of disabling startup tasks. This had worked for a previous problem, and the application had a couple. This did in fact work – in isolation – so the startup tasks were causing the problem.

It is a pity because startup tasks used to work on the 1.4 and 1.5 releases of Azure DevFabric. At least the application will run locally again.

The startup tasks in ServiceDefinition.csconfig which had to be commented out:

    <Startup>
      <Task commandLine="StartupTasks\InstallRootCert.cmd" executionContext="elevated" taskType="simple" />
      <Task commandLine="StartupTasks\FixDiagFolderAccess.cmd" executionContext="elevated" taskType="simple" />
    </Startup>

Unobserved exceptions from Tasks causing IIS to crash

Parallell extensions in .NET 4.0 introduced Tasks as a very useful abstraction for threads. However uncaught exceptions in Tasks can take down your web server.

Adding a global event handler for uncaught exceptions in Tasks, so called unobserved exceptions, solves the problem.

Code to solve the problem

There was quite a bit of backstory, but to cut a long story short a WCF service created .NET 4.0 Tasks, one of which then threw an exception later. This caused IIS to crash, but is in fact a designed feature of IIS.

At the top of my mind I can think of two common patterns for multithreaded applications. For fun I call these two patterns “Fire and Wait” and “Fire and Forget”. The solution to the problem was very straightforward: just add a special event handler to the hosting application. This is shown in the “Fire and Forget” code below.

Fire and wait

The gist of fire and wait is to simply create all the Task objects and start them, and ensure they are stored in a collection. Then the thread that created the Tasks just blocks on one of the static “Wait” methods, until all the Tasks are have completed or faulted.

Failed tasks will trigger an AggregatedException, which encapsulates all the Exceptions that occured in the Tasks. These can then be handled one by one.

The example code here uses simple Tasks which don’t return values:

public class FireAndWaitExample
{
    public void RunTasks()
    {
        try
        {
             List tasks = new List();
             var taskFactory = new TaskFactory();

             tasks.Add(taskFactory.StartNew(() =>
             {
                 throw new Exception("Thread failed!");
             }));
             tasks.Add(taskFactory.StartNew(() =>
             {
                 throw new Exception("Yet another thread failed!");
             }));

             // Throws aggregate exception:
             Task.WaitAll(tasks.ToArray());
        }
        catch (AggregateException aggregateEx)                    // The most important part
        {
             aggregateEx.Handle(HandleExceptionsInAggregateException);
        }
    }

    public bool HandleExceptionsInAggregateException(Exception ex)
    {
        errorTrace.TraceData(TraceEventType.Error, 0, ex);        // Do tracing and so on here
        return true;
    }
}

After handling the AggregatedException it is possible to read return values from Tasks which were set up for that. Return values of faulted Tasks are simply null.

Fire and Forget

In the Fire and Forget pattern your code cannot stick around waiting for the Tasks to complete. So catching an AggregateException as in the previous pattern will not work.

However, there is still a simple solution to the problem of Tasks throwing unobserved or unhandled exceptions. Registering a global event handler for the TaskScheduler.UnobservedTaskException event is all you need to do. For ASP.NET applications (4.0, MVC 3 or any other for that matter) the best place to do this in Global.asax.cs:

protected void Application_Start()
{
    // Catch unobserved exceptions from threads before they cause IIS to crash:
    TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs excArgs) =>
    {
        TraceSource trace = new TraceSource("UnhandledExceptionTrace");       // Example of tracing the exception
        trace.TraceData(TraceEventType.Error, 1, excArgs.Exception);
        excArgs.SetObserved();
    };
}

You can then fault threads as you please without any danger of taking down IIS. And if exceptions should occur while in production then they will will be logged for certain, which makes diagnostics so much easier.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        Task t1 = new Task(() =>
        {
            throw new Exception("Fire-and-forget thread faulted!");
        });
        t1.Start();

        return View();
    }
}

Taken together, the Fire and Wait and Fire and Forget patterns make it quite easy to write safer threaded applications even if the threads throw exceptions.

The Backstory: Random crashes

Recently I came across a problem with a WCF service hosted on Azure. The IIS process w3wp.exe would crash, and the service instance would then be unavailable for a short while. Usually errors like these would be reported in the application’s exception log, but the log revealed nothing. Some information could be gleaned from the Windows Application and System log though.

Most of the service’s operations were straightforward CRUD operations, but a few operations were different. For business reasons they would start threads which continued doing work after the service operation returned. A clue pointing to these threads as the likely reasons for the crashes was the fact that IIS crashed several minutes after the last service operation had returned. We used a controlled test deployment, so we knew this for certain. So the only code that could be running at the time of the crashes would be the threads.

Error from the Windows Application log

One of the three errors seen in the Windows Application log relating to IIS crashing

The source of the crashes

Taking a closer look at the Tasks mentioned earlier it became clear that not all of them were wrapped in a try-catch block. In fact some quick testing revealed that one was throwing uncaught exceptions due to it not being able to reach a remote host.

Some more searching was necessary. It turned out that IIS was set up so that unobserved exceptions rethrown on the finalizer thread would cause the w3wp.exe process to terminate! In other words uncaught exceptions from faulted threads cause IIS to crash during .NET garbage collection. This was due to a security policy specific to IIS, and is a default setting for at least Windows 7 and Server 2008, if not all Windows versions.