Much as I’ll admit to some spittle-flecked indignation when it comes to Visual Studio 20-anything, it has largely been the development tool that has paid my mortgage and allowed me to eat biscuits and cake. But this one takes the biscuit, cake, mug of tea and plate.

I’m happily working away, writing code when suddenly find in files stops working with the wonderful message “No Files Were Found To Look In. Find Was Stopped In Progress” Ah it’s simple. I’ve obviously fiddled with the search options and not selected the file types to search in or something similar. Nope –  everything looks just fine.

Ah I know. Close devenv and start again. Nope – exactly the same.

So, off for a coffee and moan and someone says: “Press Ctrl+Scroll Lock a few times and it’ll be fine”. This sounds a bit Mornington Crecsent to me, but it worked.

Sometimes I wonder if I should just go back to using notepad.exe

Today seems to be the day for posting useful stuff on the blog. Actually, it’s just so I can quickly useful find bits of code I might need again.

So I’ve a got a web page that displays some text a user has entered that may contain URLs and I’d like them to be displayed as actual hyperlinks.

 

public string ConvertUrlsToLinks(string msg)
{
string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}

 

OO purists have long argued that switching on the type of an object by using some conjured up member enum is wrong. And I agree. Fundamentally, it’s nasty and you can satisfyingly waggle your finger at poor OO design.

However, sometimes things aren’t so easy and straightforward. I’m currently working with a complex financial trade class hierarchy that simply can’t be changed – it just wouldn’t be practical. I needed some new functionality that switched on an instance of the base class of the hierarchy. Ok, so it breaks all the rules, but at least it’s switching on a common base type and not completely unrelated types. Peter Hallam’s article describes the problems with a generalised type switch built into the language and why it’s not practical.

So what follows is stream of software design consciousness that touches on the relative casting performance of C# as vs. is, lambda functions, generics and fluent interfaces (method chaining) that achieves a solution.

Lets assume we have some simple class hierarchy. These classes do nothing, but demonstrate the principles involved. We’ll use these throughout the examples.


// Our base class
public class Trade
{
    public void TradeMethod()
    {
    }
}

public class GenericTrade : Trade
{
    public void GenericTradeMethod()
    {
    }
}

public class SwapTrade : Trade
{
    public void SwapTradeMethod()
    {
    }
}

public class SpotTrade : Trade
{
    public void SpotTradeMethod()
    {
    }
}

A first stab at switching on type might be like this:


public void doSomething(Trade trade)
{
    if (trade is GenericTrade)
    {
        GenericTrade genericTrade = trade as GenericTrade;
        genericTrade.GenericTradeMethod();
        // ....
        // ....
    }
    else
        if (trade is SwapTrade)
        {
            SwapTrade swapTrade = trade as SwapTrade;
            swapTrade.SwapTradeMethod();
            // ....
            // ....
        }
        else
            if (trade is SpotTrade)
            {
                SpotTrade spotTrade = trade as SpotTrade;
                spotTrade.SpotTradeMethod();
                // ....
                // ....
            }
            else
            {
                // Default actions
                // ....
                // ....
            }
}

Well it works, but it has a couple of problems.

  • C# offers the syntactically concise way to upcast and downcast using as and is. Unfortunately as Emilio Guijarro shows, the relative performance of ‘as’ vs ‘is’ when typecasting means ‘is‘ is pretty slow.
  • Somehow, the if…else.. If …else structure seams very clunky when there’s more than a few types.

To get around using the slow ‘is‘ is easy.


public void doSomethingElse(Trade trade)
{
    GenericTrade genericTrade = new GenericTrade();
    SwapTrade swapTrade = new SwapTrade();
    SpotTrade spotTrade = new SpotTrade();

    if (genericTrade as GenericTrade != null)
    {
        genericTrade.GenericTradeMethod();
        // ....
        // ....
    }
    else
        if (swapTrade as SwapTrade != null)
        {
            swapTrade.SwapTradeMethod();
            // ....
            // ....
        }
        else
            if (genericTrade as GenericTrade != null)
            {
                genericTrade.GenericTradeMethod();
                // ....
                // ....
            }
            else
            {
                // Default actions
                // ....
                // ....
            }
}

This requires an instance of each type, but the structure is even more horrible than before. So abandon that way of doing it. What we really need is something that is readable. Something like this would be ideal:


public void doSomething(Trade trade)
{
    switch (trade)
   {
      case GenericTrade:
            // ...
            // ...
            break;
      case SwapTrade:
            // ...
            // ...
            break;
       case SpotTrade:
            // ...
            // ...
            break;
        default:
            // ...
            // ...
            break;
      }
}

Bart De Swet’s article that describes a solution that yields a similar code structure. This is implemented using method extensions which is unnecessarily complicated, so I devised a similar solution using instance methods.

So here’s my take on a switch class – I’ve called it SwitchOnType for clarity:


public class SwitchOnType<T1>
{
    bool _break = false;
    private T1 _object;

    public SwitchOnType(T1 obj)
    {
        _object = obj;
    }

    public SwitchOnType<T1> Case<T2>(Action<T2> action) where T2 : class
    {
        if (_break == false)
        {
            T2 t = _object as T2;
            if (t != null)
            {
                action(t);
                _break = true;
            }
        }
        return this as SwitchOnType<T1>;
    }
    public void Default<T2>(Action<T2> action) where T2 : class
    {
        if (_break == false)
        {
            T2 t = _object as T2;
            if (t != null)
                action(t);
        }
    }
}

And here’s how it’s used with our class hierarchy example:


public void doSomething(Trade trade)
{
    new SwitchOnType<Trade>(trade)
        .Case<GenericTrade>(genericTrade =>
        {
            // It's a GenericTrade
            genericTrade.GenericTradeMethod();
            // ...
            // ...
        })
        .Case<SwapTrade>(swapTrade =>
        {
            // It's a SwapTrade
            swapTrade.SwapTradeMethod();
            // ...
            // ...
        })
        .Case<SpotTrade>(spotTrade =>
        {
            // It's a SpotTrade
            spotTrade.SpotTradeMethod();
            // ...
            // ...
        })
        .Default<Trade>(t =>
        {
            // Default actions
            t.TradeMethod();
        });
}

Although there’s a few extra {‘s and )’s, the structure is close to the ideal. This is mainly possible using method chaining (also known as fluent interfaces), by returning this (well a genericized this) in the case method and passing the code to be executed if the case test succeeds as a lambda function. Note if none of the Case methods succeeds, the Default method will get called. If you want to know more about fluent interfaces read Martin Fowler’s article.

So just accept that sometimes you have no choice and have to accept that it’s right to do what’s wrong – is that software or life. Or both.

Intrigue is curious thing, much as curiosity is intriguing. What drives it? Mostly just needing to know something for no other reason than wanting to know itself – curious indeed. 

So why would I really be bothered to know what WindowsFormsSyncronizationContext does under the hood? Well dear bleader (if someone who write blogs is a blogger, maybe someone who reads blogs is a bleader) I had my suspicions, but I just needed to find out.

SynchronizationContext and it’s derivatives was introduced in .NET 2.0 as simple .NET language construct to allow a non-GUI thread to call methods on a GUI control. Previously, code had to be written to perform the InvokeRequired, BeginInvoke, Invoke dance and as has been discovered, this has problems and  can have you chasing nasty bugs.

In https://davebrooks.wordpress.com/2007/02/12/begininvoke-the-land-of-confusion/ I discussed BeginInvoke for delegates and controls, some issues and how they worked under the hood.

As I said before, I was suspicious that WindowsFormsSynchronizationContext worked pretty much the same way. And Lo, with a bit of windows message spying on a simple test app, my suspicions were confirmed. WindowsFormsSynchronizationContext.Post() and .Send() end up using PostMessage with registered windows messages, presumably using BeginInvoke and Invoke respectively to push the control method call onto the main GUI thread.  However, it does make the code earlier to write and as we all know, less code means less bugs.

Now to find out what happens in the Freemasons. I’m just curious you understand.

I’ve been meaning to get around to sorting out the plethora of App.config in a large, multi project C# solution, but it wasn’t anywhere near the top of the pile of problems that needed solving. I just keep hacking values into the *.exe.config file after the build to make things work.

In a spare (and rare) 20 minutes, while drinking a coffee, I thought I’d have a quick look and discovered a really simple solution. For some reason this technique had completely passed me by. Imagine you’ve got a C# solution made up of 3 projects which build into 3 separate executables, each requiring a common config file. If you have simply added a config file to each project and try to keep them in sync you quickly end up in config hell. So rather that add a new config file to each project, simply create one in one of the projects and then link it in the others.

Here’s how, in our imaginary 3 project solution

Solution
     Project1
     Project2
     Project3

  • Right click on Project1 and select Add->New Item->Application Configuration File and it will create a the file App.config in Project1.
  • Right click on Project2 and select Add->Existing Item and browse to Project1’s App.config file, but don’t hit the Add button. Select the Add button drop down and select Add as link.
  • Repeat for Project3

So now when you open any of the projects App.config files you will be using the same file. More importantly, when you build the solution, each projects bin/Debug (Release) directory will have it’s own, but identical copy of the config file (Project*.exe.config) leaving you the freedom to deploy the executables with their own or a common config file. Essentially, building the solution duplicates the config files from a single master version.

Itch successfully scratched.

Tangosol (aka Oracle) has a .NET version of Coherence that’s been available for a few months now. Previously, it was possible to use Coherence in a .NET or unmanaged C++ project, but required the use of a thirdparty or home grown JNI proxy mechanism – maybe Codemesh. However, Coherence.NET provides a native .NET serialization mechanism which makes it’s use in a C# GUI pretty straightforward.

Which ever objects you want to work with the cache simply need to ne derived from IPortableObject , add some getters and setters and implement the ReadExternal and WriteExternal methods. This example is lifted straight out of Tangosol sample code.


public class ContactInfo : IPortableObject
{
private string name;
private string street;
private string city;
private string state;
private string zip;
public ContactInfo()
{ }

public ContactInfo(string name, string street, string city, string state, string zip)
{
Name = name;
Street = street;
City = city;
State = state;
Zip = zip;
}

public override int GetHashCode()
{
return name == null ? 0 : name.GetHashCode();
}

public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}

ContactInfo contactInfo = obj as ContactInfo;
return contactInfo != null &&
Equals(Name, contactInfo.Name) &&
Equals(Street, contactInfo.Street) &&
Equals(City, contactInfo.City) &&
Equals(State, contactInfo.State) &&
Equals(Zip, contactInfo.Zip);
}

public override string ToString()
{
return "ContactInfo("
+ "Name=" + Name
+ ", Street=" + Street
+ ", City=" + City
+ ", State=" + State
+ ", Zip=" + Zip
+ ')';
}

public void ReadExternal(IPofReader reader)
{
Name = reader.ReadString(0);
Street = reader.ReadString(1);
City = reader.ReadString(2);
State = reader.ReadString(3);
Zip = reader.ReadString(4);
}

public void WriteExternal(IPofWriter writer)
{
writer.WriteString(0, Name);
writer.WriteString(1, Street);
writer.WriteString(2, City);
writer.WriteString(3, State);
writer.WriteString(4, Zip);
}
}

Thoughtfully, they have also provided a couple of apparently useful classes to make the GUI developers life easy. WindowsFormsCacheListener and CacheEventHandler classes are there so the GUI develeoper doesn't have to worry about which thread the cache events are raised on and the associated GUI thread update problem.

public partial class ContactInfoForm : Form
{
  ...
  listener = new WindowsFormsCacheListener(this);
  listener.EntryInserted += new CacheEventHandler(AddRow);
  listener.EntryInserted += new CacheEventHandler(AddAnotherRow);
  listener.EntryUpdated += new CacheEventHandler(UpdateRow);
  listener.EntryDeleted += new CacheEventHandler(DeleteRow);
  ...
  cache.AddCacheListener(listener);
  ...
}
private void AddRow(object sender, CacheEventArgs args)
{
 throw new Exception();
}
private void AddAnotherRow(object sender, CacheEventArgs args)
{
...
}
private void UpdateRow(object sender, CacheEventArgs args)
{
...
}
private void DeleteRow(object sender, CacheEventArgs args)
{
...
}

I’m always wary of this style of coding in C#. Is it truely thread safe and what happens when exceptions are thrown – all the classic multicast delegate and event issues. A simple change to the above code to add another EntryInserted delegate gives us the answer (I added the AddAnotherRow and the hard thrown exception). As expected, the exception means the subsequent delegates aren’t called and it fails silently. For any GUI design in a fast moving financial environment, this is a real problem.

It also leads me to wonder if another thread comes along and and removes the delegate from the CacheEventHandler mid call what happens. I’ve blogged about this before (who hasn’t?). This a very easy trap to fall into when using delegates and events in a multithreaded C# GUI application.
 
 

Sometimes you just have no choice. You have resort to some hack in order to make your code work. I recently had to write a GUI client to provide some specialist admin tasks on DataSynapse GridServer v2.6. For various reasons this had to be a C# .NET GUI and DataSynapse thoughtfully provide a .NET API which made the coding tasks pretty straightforward. Everything worked beautifully except when the GUI closes and the App Domain doesn’t unload. Consequently the .exe and vshost.exe just hang around like ghostly processes.

Some investigation revealed that whenever any of the DataSynapse admin .NET API methods are called there’s a sleep, wait or join that never exits.

[In a sleep, wait, or join]
mscorlib.dll!System.Threading.Monitor.Wait(object obj, int millisecondsTimeout, bool exitContext) + 0x14 bytes

It turns out this is a known bug that I’m sure will be fixed at some stage. However, that didn’t really help me. Despite some failed attempts to terminate the thread, I resorted to some rug pulling. The code now uses my old Suppuku class to make sure everything terminates.

static void Main()
{
      Application.SetCompatibleTextRenderingDefault(false);
      new ShellApplication().Run();
      Suppuku.Sword.Commit(0);
}

And here’s the brutal implementation.

namespace Suppuku
{
      public class Sword
      {
            [DllImport("Kernel32.dll")]
            private static extern bool TerminateProcess(int handle, int exitCode);
            public static void Commit(int exitCode)
            {
                  TerminateProcess(-1, exitCode);
            }
      }
}

Sometimes needs must and Win32 comes to the rescue.  Any other solutions gratefully excepted.