IDisposable StopWatch to Benchmark code blocks (via Lambda or Delegate) in C#

Sometimes you need to time code execution for use *inside* your application. the StopWatch class was designed just for this purpose, but you end up with some pretty ugly code that looks like this:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// Do something.
for (int i = 0; i < 1000; i++) { Thread.Sleep(1); }
// Stop timing.
stopwatch.Stop();
// Write result.
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

This gets really messy, especially if the code is already pretty complicated. But with very little effort you can make the .Net StopWatch just as beautiful as the Benchmark class in Ruby.

public class DisposableStopwatch: IDisposable {
  private readonly Stopwatch sw;
  private readonly Action f;

  public DisposableStopwatch(Action f) {
    this.f = f;
    sw = Stopwatch.StartNew();
  }

  public void Dispose() {
    sw.Stop();
    f(sw.Elapsed);
  }

}

To use the new stopwatch:

using (new DisposableStopwatch(t => Console.WriteLine("{0} elapsed", t)) {
  // do stuff that I want to measure
}

This is the best solution I’ve ever seen for this problem! No extension (so that it can be used on many classes) and very clean and very simple!

SerializationException Running Npgsql Commands on .Net Entity Framework

Recently, while working on a project for a client I was writing a .Net application using the Entity Framework backed onto a PostgreSQL database. All of a sudden I got a System.Runtime.Serialization.SerializationException when I was trying to run my app, and the stack trace (weirdly) didn’t help.

It turns out that while I had added the Npgsql dependency to the project, it wasn’t enough. Entity Framework it seems, needs to have access to Npgsql.dll assembly information.  When EntityFramework tries to use the library, it won’t find it (despite being in the project) unless it is in the Global Assembly Cache (GAC).

The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system. Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). Source

The best way to resolve this is to use the Npgsql installer that matches the version in your project from: https://github.com/npgsql/npgsql/releases. Those setups take care of registering Npgsql in GAC and set up the machine.config file to include the Npgsql db provider factory.

After I did this, everything worked as it should, and all was right with the world.

Convert SQL Server Database to a SQLite Database

Recently, I wanted to resurrect an old project of mine I worked on in my spare time originally designed to work on .Net technologies. Naturally, I backed it against a SQL Server 2005 Database which turned out to be a bad idea because it made portability of that data a bit of a nightmare.

So it was with great happiness that I found this tool (mirrored here) by liron.levi who posted an article on CodeProject on how to accomplish this task. You still need a Windows machine and an install of SQL Server (Express Edition with Advanced Tools is alright) but it got the job done just fine for me.

If you want a no-fuss easy way to convert your databases into a format easier to deal with and a lot more portable to-boot.

Download Microsoft .NET Framework 3.5 SP1 Standalone Full Redistributable Setup Installer

Many applications uses Microsoft .NET Framework 3.5 as development platform, and thus requires .NET Framework to be installed beforehand, else the installation will request to download and install .NET Framework from Internet. On offline system without Internet access or online server with slow downloading speed, the requirement to download setup files through web may hit the wall – a no go.

kamagra shipping

Microsoft initially just provides a minimal size dotnetfx35setup.exe download which is a bootstrapper that will still need to download more files via Internet. For users who prefer to perform offline installation or install .NET Framework 3.5 SP1 without waiting for download to complete will have to download and save a copy of full complete standalone or redistributable Microsoft .NET Framework 3.5 SP1 setup installer, which is finally published by Microsoft.

Microsoft .NET Framework 3.5 SP1 (Service Pack 1) is a full cumulative update that contains many new features building incrementally upon .NET Framework 2.0, 3.0, 3.5, and includes cumulative servicing updates to the .NET Framework 2.0 and .NET Framework 3.0 subcomponents. See KB951847 for list of changes and fixed issues in the .NET Framework 3.5 Service Pack 1.

Download full package of Microsoft .NET Framework 3.5 SP1: dotnetfx35.exe (231 MB)

For known issues and release notes, refer to Microsoft .NET Framework 3.5 SP1 Readme.

WebGAC Takes the Pain Out of .Net Dependencies

My good friend Paul Jones, has released a great tool called WebGAC to github.  WebGAC is a great way to manage .net assemblies and adding them to .Net projects from a centralised repository of binaries.  As someone who has used this tool on literally dozens of projects for nearly 2 years now, Its a must have tool for all Visual Studio developers.

Managing binary dependencies in .NET can be a complicated task. For small projects, checking the dependencies into source control tends to work just fine. So does requesting that all developers have various binaries available in their GAC. Grow much bigger, or add more projects, and managing that starts to get very difficult. The Java world has had a solution to this problem for a long time, in the form of Maven and Ivy. Remote servers store the binaries, and the build tool automatically downloads them on demand.

WebGAC adds the core of this functionality to .NET, but without requiring you to switch build tools, or maintain a separate configuration file. Dependencies are specified just the same way as normal, but if you don’t have them when building your project, WebGAC will fetch them for you automatically.

WebGAC is available at http://github.com/paulj/webgac. Browse over there for more information and installation instructions, or continue reading here for more details.

Better way to get the Scheme, Host and Port from Uri Object in .Net

Recently I was working on a project where I needed to strip the scheme, host and port (if it wasn’t 80) from a Uri object. Obviously I could have used string concatenation to get the value I needed, but it just seemed so ghastly and inelegant. In frustration and annoyance that it wasn’t part of the standard Uri object definition, I asked a friend who gave me this little gem:

side effect of clomid

Uri uri = new Uri("http://localhost:6767/h/ello.php");
string url = new Uri(uri.AbsoluteUri).GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

The string, ‘url’, will (in this example) hold the value “http://localhost:6767”. This works in .Net 2.0 and up, and with .Net 3.0, you could even create a static method extension to make it even easier.

Sometimes, Microsoft Gets it Right (The .NET Framework 4)

Parallel Programming are two words which are not nearly used enough by programmers today. I think this is partially due to the fact that most developers are answerable to management types who simply “want to get the job done”. It’s also highly susceptible to deadlocks, race conditions and other problems, which are somewhat more avoidable in traditional single-threaded-apartment model applications. The problem is, that we’ve reached a precipice in CPU architecture where CPUs are scaling out instead of up. In other words, instead of simply working harder and faster, they’re working smarter – executing many simultaneous operations.

The only problem with this is that applications need to be programmed to capitalize on this architecture – and making Multi-threaded applications easier is obviously on Microsoft’s mind with the announcements of features in the upcoming The .NET Framework 4.0.

One of the main the main features I am looking forward to is the Parallel class to easily thread simple loops. This Parallel class represents a significant advancement in simplistically managing loops.  The .Net 4.0 team assures us that “for many common scenarios, it just works, resulting in terrific speedups”.  A similar technique can be used to write parallel loops over iteration spaces of non-integral objects.

Parallel.For(0, N, i=>
  {
    DoWork(i);
  });

There are also overhauls to the ThreadPool class (which was in dire need of serious attention) and the inclusion of “Tasks” – simple generic types which assist developers in creating native IAsyncResult objects: this means that Task can be used as the core of a Begin/End implementation.  They’ve also really thought about these improvments, with easy and clear ways to cancel parallel operations, as well as a number of great ways to handle Exceptions within parallel blocks.

There are of course other advantages to the 4.0 Framework, but it’s the big emphasis on easing MTA (Multi-Threaded Apartment) model application development that’s got me excited.

Enjoy!

.Net Remoting Error – Win32Exception: The logon attempt failed

Quite a while ago, in the absence of any alternatives, we built a remote deployment utility so we could push updates to our staging and production servers without manual intervention.

Recently however, while deploying the latest code for an internal project to a new production server, the .Net 2.0 automatic deployment  I had created threw the following, rather unfriendly error:

Exception Details: System.ComponentModel.Win32Exception: The logon attempt failed
[Win32Exception (0x80004005): The logon attempt failed]
[InvalidCredentialException: The server has rejected the client credentials.]

In order to protect the server from attack we have a system service which we communicate to using .Net remoting, which requires authentication.

Apparently the bug occurred, because I created the user account which we authenticate against on the new server, after I have installed the system service.

I uninstalled the system service, reinstalled it and it magically worked like it should.

What’s the best Way for 2 Processes to Communicate in .Net?

While trawling the internet the other day, I came across this question, and thought it might be something that others might like to know.  The question was:

What’s the best (or maybe not the best — just good) way for two processes in the same machine to communicate, using .NET?

Actually the two processes in the app I’m working on aren’t even two different programs; they’re just two instances of the same EXE. I wanted to do something like a singleton app, but have it per user (meaning a Terminal Server or Citrix or App-V server with multiple users should be able to launch their own single copy of the app). If another instance is run by the same user, it should just delegate the task to the already running instance, then exit. Only one instance per user of the program should be running. So far I’ve done (thanks to StackOverflow) the part that detects whether an instance of the app is already running, using Mutex. But I need the second app instance to be able to send data to the first app instance.

I’m leaning towards using named pipes and WCF’s NetNamedPipeBinding for this, but if you have better ideas I’ll really appreciate it. Thanks 🙂

IPC is what I’ve used in the past for this. And it is supprisingly easy. .Net remoting is a good option but unfortunately it is a restricted option becasue you can’t for example use it on the CF.

Below is a copy of the class I use to perform Inter-process Communication, you can use it in conjuction with a MutEx if you wish, but it isnt necessary. As long as the “pMappedMemoryName” and “pNamedEventName” are the same in both processes, it should work just fine. I tried to make it as event driven as possible.

The class looks a little like this:

  public class IpcService {
    private IServiceContext mContext;
    const int maxLength = 1024;
    private Thread listenerThread;
    private readonly string mMappedMemoryName;
    private readonly string mNamedEventName;
    public event EventHandler IpcEvent;
    private readonly bool mPersistantListener;

    public IpcService(bool pPersistantListener)
      : this(pPersistantListener, "IpcData", "IpcSystemEvent") {
      ;
    }

    public IpcService(bool pPersistantListener, string pMappedMemoryName, string pNamedEventName) {
      mPersistantListener = pPersistantListener;
      mMappedMemoryName = pMappedMemoryName;
      mNamedEventName = pNamedEventName;
    }

    public void Init(IServiceContext pContext) {
      mContext = pContext;
      listenerThread = new Thread(new ThreadStart(listenUsingNamedEventsAndMemoryMappedFiles));
      listenerThread.IsBackground = !mPersistantListener;
      listenerThread.Start();
    }

    private void listenUsingNamedEventsAndMemoryMappedFiles() {
      IntPtr hWnd = EventsManagement.CreateEvent(true, false, mNamedEventName);
      while (listenerThread != null) {
        if (Event.WAITOBJECT == EventsManagement.WaitForSingleObject(hWnd, 1000)) {
          string data = Peek();
          EventsManagement.ResetEvent(hWnd);
          EventHandler handler = IpcEvent;
          if (handler != null) handler(this, new TextualEventArgs(data));
        }
      }
      EventsManagement.SetEvent(hWnd);
      Thread.Sleep(500);
      HandleManagement.CloseHandle(hWnd);
    }

    public void Poke(string format, params object[] args) {
      Poke(string.Format(format, args));
    }

    public void Poke(string somedata) {
      using (MemoryMappedFileStream fs = new MemoryMappedFileStream(mMappedMemoryName, maxLength, MemoryProtection.PageReadWrite)) {
        fs.MapViewToProcessMemory(0, maxLength);
        fs.Write(Encoding.ASCII.GetBytes(somedata + "\0"), 0, somedata.Length + 1);
      }
      IntPtr hWnd = EventsManagement.CreateEvent(true, false, mNamedEventName);
      EventsManagement.SetEvent(hWnd);
      Thread.Sleep(500);
      HandleManagement.CloseHandle(hWnd);
    }

    public string Peek() {
      byte[] buffer;
      using (MemoryMappedFileStream fs = new MemoryMappedFileStream(mMappedMemoryName, maxLength, MemoryProtection.PageReadWrite)) {
        fs.MapViewToProcessMemory(0, maxLength);
        buffer = new byte[maxLength];
        fs.Read(buffer, 0, buffer.Length);
      }
      string readdata = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
      return readdata.Substring(0, readdata.IndexOf('\0'));
    }

    private bool mDisposed = false;

    public void Dispose() {
      if (!mDisposed) {
        mDisposed = true;
        if (listenerThread != null) {
          listenerThread.Abort();
          listenerThread = null;
        }
      }
    }

    ~IpcService() {
      Dispose();
    }

  }

Simply use the Poke method to write data, and the Peek method to read it, although I designed it to automatically fire an event when new data is available. In this way you can simply subscribe to the IpcEvent event and not have to worry about expensive and constant polls.  Enjoy.

Simple Solution to Illegal Cross-thread Calls in C#

If the thread call is “illegal” (i.e. the call affects controls that were not created in the thread it is being called from) then you need to create a delegate so that even if the decision / preparation for the change is not done in the control-creating thread, any resultant modification of them will be. Basically, this is a long winded way of saying you can’t (and shouldn’t) access controls on a form from a thread that didn’t create the control in the first place.

.Net version older than 2.0 (1.0 and 1.1) would actually allow this to happen, but cross-threaded operations should always be dealt with cautiously and properly. The technical solution to the problem is to create a delegate function, and pass the delegate function to the Invoke() method on the control, which allows code to execute as if it was being executed from the control’s parent thread, but if you need to do this a lot, all the extra functions and delegates can make the code unreadable, if a lot of it is going on. Fortunately there are 2 “cheats” to the problem. The first is to use the ThreadStart delegate (System.Threading namespace), since its already setup as a simple delegate with one parameter. The second, is to use anonymous delegates, which is something I have covered in the past.

if (label1.InvokeRequired) {
  label1.Invoke(
    new ThreadStart(delegate {
      label1.Text = "some text changed from some thread";
    }));
} else {
  label1.Text = "some text changed from the form's thread";
}

Now, the more curious and perceptive of you are asking, why not just use control.Invoke() everytime you change a value? Well, the truth is you could. But calling control.Invoke() has a great deal more overhead than not calling it. However, when you avoid calling control.Invoke() and access UI objects directly from the UI thread, you’re writing incorrect code that could cause stability problems in your application.

The problem is that a “window” object in the underlying Windowing API in Win32, as represented by the HWND handle, has thread-affinity. It must be directly accessed only from the thread that created it. If it’s not, the results are unpredictable and can cause subtle, intermittent bugs.

By all means skip control.Invoke() if you’ve only got one thread. However, if you need to affect a UI object from a worker thread, you absolutely must use control.Invoke() to transition back to the UI thread before making that call or you’re in for a world of pain.