Tag Archives: C#

Super Simple Single Instance Application in Windows using C#

There are cases in the Windows world where you only want a single instance of an application.  So, if we launch the application either from the Start menu or command line, or we launch the process from another application, we only ever want one instance – the same one.

If an instance of the application already exists, we want the application to come to the foreground.  Not only that but we want the view in that single instance to change based on how the second instance was invoked.

Much has been written on this including using .NET remoting.  I chose a far simpler way involving memory mapped files, passing command line information from the second instance to the first.  (I freely acknowledge that there is a hack component to it.)

We will begin with the essence of the operation in the main function of your application.

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
  // The helper object for single instances
  ApplicationManagement applicationManagement = new     ApplicationManagement();

  // If we have arguments, pass them to the original instance.
  // If we are creating the first instance, the same memory mapped file mechanism is used for    simplicity.
  if (args.Length > 0)
    applicationManagement.SetArguments(args);

  // if a previous instance exists..
  if (applicationManagement.DoesPreviousInstanceExist())
  {
    // Exit stage left
    applicationManagement.ShowPreviousInstance();
    return;
  }

  // in the case where we are the first instance and we don't have a previous one, then
  // default to the default view
  if (args.Length == 0)
    applicationManagement.SetArguments(new string [] {   frmMain.commandLineFlagForm1 });

  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);

  // pass the application management object to the main form
  frmMain main = new frmMain();
  main.applicationManagement = applicationManagement;
  Application.Run(main);
}

Here is the operation truth table with this code.

command line new instance created previous instance exists
no arguments show default view do nothing (but set to top of Z-order)
has arguments set view to the argument  set view to the argument

Notice that if a previous instance exists, we want to bring the previous instance window to the top of the Z-order.  The previous instance itself can not go to the foreground (without attaching to thread input of the top order window but we are not doing this).  While a new process is being created, until the first window of the application is created, the new process can send any other window of any other process to the top of the Z-order.  This is a peculiarity of Windows.

Now a hacky part…  In the main form, there is a timer that periodically checks for new arguments to appear.

private void tmrArguments_Tick(object sender, EventArgs e)
{
 string[] arguments = applicationManagement.GetArguments();
 if (arguments.Length > 0)
 {
 switch (arguments[0])
 {
 case commandLineFlagForm1:
 Form frm = ViewChildForm(typeof(frmForm1));
 if (arguments.Length == 3)
 (frm as frmForm1).SetSelectedProperty(arguments[1], arguments[2]);
 frm.WindowState = FormWindowState.Maximized;
 break;
 case commandLineFlagForm2:
 ViewChildForm(typeof(frmForm2)).WindowState = FormWindowState.Maximized;
 break;
 }
 }
}

Essentially, the form’s timer will periodically check to see if there are new arguments.  In this example, the command line can specify a form 1 or a form 2.  If form 1, it can pass additional information in as well.

So now we will get to the handling of the previous instance and bringing it to life and then we will deal with passing command line information.

For single instance, the applicationManagement class that you see handles the single instance.  The constructor determines if a previous instance exists.

public ApplicationManagement()
{
  Process currentProcess = Process.GetCurrentProcess();
  m_previousInstance = (from process in Process.GetProcesses()
                         where
                         process.Id != currentProcess.Id &&
                         process.ProcessName.Equals(
                         currentProcess.ProcessName,
                         StringComparison.Ordinal)
                         select process).FirstOrDefault();
  CreateArgumentStream();
}

/// <summary>
/// Does the previous instance exists?
/// </summary>
/// <returns></returns>
public bool DoesPreviousInstanceExist()
{
  return m_previousInstance != null;
}

/// <summary>
/// Shows the instance of the specified window handle
/// </summary>
/// <param name="windowHandle">The window handle.</param>
private void ShowInstance(IntPtr windowHandle)
{
  ShowWindow(windowHandle, WindowShowStyle.ShowNormal);
  EnableWindow(windowHandle, true);
  SetForegroundWindow(windowHandle);
}

/// <summary>
/// Shows the previous instance.
/// </summary>
public void ShowPreviousInstance()
{
  ShowInstance(m_previousInstance.MainWindowHandle);
}

You can see the methods where we determine if a previous instance exists and also showing the previous instance.  The ShowWindow, EnableWindow, and SetForegroundWindow API calls can be optained here:  http://www.pinvoke.net/.

Finally, the here is the code in the applicationManagement class that handles passing through the memory mapped buffer.

/// <summary>
/// The map name used for passing arguments through the MMF
/// </summary>
private const string mapName = "MySecretMapName";

/// <summary>
/// The argument stream length in bytes
/// </summary>
private const int argumentStreamLength = 512;

/// <summary>
/// The argument reference that will be used to pass arguments through a memory mapped file.
/// </summary>
private MemoryMappedFile m_arguments = null;

/// <summary>
/// The accessor to pass arguments through the memory mapped file
/// </summary>
private MemoryMappedViewAccessor m_argumentViewAccessor = null;
/// <summary>
/// Creates the argument stream.
/// </summary>
private void CreateArgumentStream()
{
  m_arguments = MemoryMappedFile.CreateOrOpen(mapName, argumentStreamLength, MemoryMappedFileAccess.ReadWrite);
  m_argumentViewAccessor = m_arguments.CreateViewAccessor();
  // Set up the buffer with nulls
  ClearArguments();
}

/// <summary>
/// Clears the arguments by setting everything to nulls which is still a valid string but has no meaning
/// </summary>
private void ClearArguments()
{
  byte[] buffer = new byte[argumentStreamLength];
  m_argumentViewAccessor.WriteArray<byte>(0, buffer, 0, buffer.Length);
}

/// <summary>
/// Gets the arguments from the memory mapped file and convert back to a string array.
/// We are using a less than pristine synchronization method of looking for any nulls in the string.
/// This method does however work as we are looking for the last null to be removed which should happen
/// in SetArguments.
/// </summary>
/// <returns></returns>
public string[] GetArguments()
{
  byte[] buffer = new byte[argumentStreamLength];

  m_argumentViewAccessor.ReadArray<byte>(0, buffer, 0, buffer.Length);
  // get the string of arguments from the buffer
  string args = Encoding.Unicode.GetString(buffer);
  // if there are any nulls, then we do nothing but return an empty string
  if (args.IndexOf('\0') != -1)
    return new string[0];

  // if there are no more nulls the we have something to evaluate
  args = args.Trim(); // remove the spaces
  ClearArguments();
  // split the string based on our marvelous separator
  return args.Split(new string[] { argumentSeparator }, StringSplitOptions.RemoveEmptyEntries);
}

/// <summary>
/// Sets the arguments from the command line. This is a poor mans way of doing this. A more "pristine" way would be to
/// serialize and deserialize the command line argument string array.
/// </summary>
/// <param name="args">The arguments.</param>
public void SetArguments(string[] args)
{
  // puts the nulls into the MMF
  ClearArguments();

  // Removes all the null when it is finally written to the MMF
  string arguments = String.Join(argumentSeparator, args).PadRight(argumentStreamLength, ' ');
  byte[] buffer = Encoding.Unicode.GetBytes(arguments);
  m_argumentViewAccessor.WriteArray<byte>(0, buffer, 0, buffer.Length);
}

This is a really simple information passing with some inherent synchronization although it is a bit hacky.  Essentially, the memory mapped buffer is full of nulls.  When the previous instance is going to put the command line arguments into the MMF, it copies all the command line arguments converting from a string array to a joined single string with a clever separator (lame).  Then it pads to the length of the buffer with spaces.

The primary instance will wait until there are no more nulls in the buffer before evaluating.  In this way, we achieve some form of synchronization.  After the complete string is read and split to the original string array, the buffer is cleared out.  (This is also a clear last one in wins scenario.)

So there it is.  If there are questions, post a comment.  I would love to see something other than “buy Nike shoes written in Chinese”.

Restricting input on winform text boxes

How do you get a text box to only support positive floating point numbers on a Windows Form text box? (I know. I know. This is old school. However, it does pay the bills.)

One way that I thought was appealing was to implement the KeyDown event and control the key-presses; like this:

private void txtBowelMovementsPerDay_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Allow numbers from keyboard
    if (e.KeyData >= Keys.D0 && e.KeyData <= Keys.D9)         return;     // Allow numbers from number pad     if (e.KeyData >= Keys.NumPad0 && e.KeyData <= Keys.NumPad9)
        return;

    // Allow periods from keyboard and number pad
    if (e.KeyData == Keys.Decimal || e.KeyData <= Keys.OemPeriod)
    {
        // but only one
        if (!txtBowelMovementsPerDay.Text.Contains('.'))
            return;
    }

    // Allow alt and shift to work
    if (e.Alt || e.Shift)
        return;

    // Allow the special keys to work
    switch (e.KeyData)
    {
        case Keys.End:
        case Keys.Enter:
        case Keys.Home:
        case Keys.Back:
        case Keys.Delete:
        case Keys.Escape:
        case Keys.Tab:
        case Keys.Left:
        case Keys.Right:
            return;
    }

    // Invalid input
    e.SuppressKeyPress = true;
    e.Handled = true;
}

A friend pointed out that while this was cool (ok, I may have change the tone there), it doesn’t internationalize well because a) it assumes the US keyboard layout and b) it assumes a ‘.’ is always the radix point. Bad, bad, bad.

Instead he turned me onto letting Windows do its job and checking the validity of the float to begin with and enabling the user to press “OK”. Like this…

private void txtBowelMovementsPerDay_TextChanged(object sender, EventArgs e)
{
    btnOk.Enabled = TrackSpacingMicronsTextBoxIsValid();
}

private bool TrackSpacingMicronsTextBoxIsValid()
{
    float trackSpacingMicrons;

    // is it a valid float?
    if (float.TryParse(txtBowelMovementsPerDay.Text, out trackSpacingMicrons))
    {
        // is it a positive number?
        if (trackSpacingMicrons <= 0)
            return false;
        return true;
    }
    else
        return false;
}

This is a much better approach and facilitates i18n. While Winforms is old-school, the problem is nicely solved in WPF.

<TextBox Name="txtBowelMovementsPerDay" TextWrapping="Wrap" Text="{Binding Path=BowelMovementsPerDay, Mode=TwoWay, 
    UpdateSourceTrigger=PropertyChanged,StringFormat={}{##.##}}"></TextBox>

For systems where you must make a decision to validate or preempt keystrokes, validation will always be best. By validation, I mean that you do not let the user continue unless all the data is correct. This is true with web page development as well as Javascript will parse floats based on locale.

Simple Python JSON server based on jsonrpclib

I needed a simple python JSON server executing in its own thread but that was easily extensible.   Let’s get right to the base class code (or super class for those who build down).

#! /usr/bin/python

import threading

import jsonrpclib
import jsonrpclib.SimpleJSONRPCServer

class JsonServerThread (threading.Thread):
  def __init__(self, host, port):
    threading.Thread.__init__(self)
    self.daemon = True
    self.stopServer = False
    self.host = host
    self.port = port
    self.server = None

  def _ping(self):
    pass

  def stop(self):
    self.stopServer = True
    jsonrpclib.Server("http://" + str(self.host) + ":" + str(self.port))._ping()
    self.join()

  def run(self):
    self.server = jsonrpclib.SimpleJSONRPCServer.SimpleJSONRPCServer((self.host, self.port))
    self.server.logRequests = False
    self.server.register_function(self._ping)

    self.addMethods()

    while not self.stopServer:
      self.server.handle_request()
    self.server = None

  # defined class definitions

  def addMethods(self):
    pass

So the idea is simple,   Derive a new class from this and implement the addMethods method and the methods themselves.

#! /usr/bin/python

import jsonServer

class JsonInterface(jsonServer.JsonServerThread):
  def __init__(self, host, port):
    jsonServer.JsonServerThread.__init__(self, host, port)
    self.directory = directory

  def addMethods(self):
    self.server.register_function(self.doOneThing)
    self.server.register_function(self.doAnother)

  def doOneThing(self, obj):
    return obj

  def doAnother(self):
    return "why am I doing something else?"

In the derived class, implement the methods and register them in addMethods.  That is all.  Now we can worry simply about implementation.  Be aware of any threading synchronization of exception handling.  Jsonrpclib takes care of exception handling as well and converts it into a JSON exception.

One last item of note.  In the base class, the stop method is interesting.  Since handle_request() is a blocking call in the thread, we need to set the “stop” flag and make a simple request.  The _ping method does this for us.  Then we join on the thread waiting for it to end gracefully.

The jsonrpclib is a very useful library and well done.  By the way, this example is for Python 2.7.  On Ubuntu 14.04, you can install this using “apt-get install python-jsonrpclib”.

C++ Speed Test with FPU and ints

I wanted to test the difference on modern hardware between floating point match and integer math. Here is my code (which was similar to C# code previously written).

// CSpeedTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include 

using namespace std;

#define FP_MULT
//#define FP_NEG
//#define INT_MULT
//#define INT_NEG

class StopWatch
{
    LARGE_INTEGER m_freq;
    LARGE_INTEGER m_startTime;
    LONGLONG m_totalTime;
public: 
    StopWatch() : m_totalTime(0L)
    {
        QueryPerformanceFrequency(&m_freq);
    }

    void Start()
    {
        QueryPerformanceCounter(&m_startTime);
    }

    void Stop()
    {
        LARGE_INTEGER stopTime;
        QueryPerformanceCounter(&stopTime);
        m_totalTime += (stopTime.QuadPart - m_startTime.QuadPart);
    }

    void Reset()
    {
        m_totalTime = 0L;
    }

    double ElapsedTime()
    {
        return (double)(m_totalTime) / (double)(m_freq.QuadPart);
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    #if defined(FP_MULT) || defined(FP_NEG)
    volatile double poo = 0.0;
    #endif
    #if defined(INT_MULT) || defined(INT_NEG)
    volatile int poo = 0;
    #endif

    StopWatch stopWatch;
    for (int idx = 0; idx < 1000000000; idx++)
    {
      stopWatch.Start();
      #if defined(FP_MULT)
        poo = -1.0 * poo;
      #endif
      #if defined(FP_NEG) || defined(INT_NEG)
        poo = -poo;
      #endif
      #if defined(INT_MULT)
        poo = -1 * poo;
      #endif
      stopWatch.Stop();
    }

    double elapsedTime = stopWatch.ElapsedTime();

    int minutes = elapsedTime / 60;
    int seconds = (int) (elapsedTime) % 60;
    int ms10 = (elapsedTime - int(elapsedTime)) * 100;

    cout << setfill('0') << setw(2) << minutes << ':' << seconds << ':' << ms10 << endl;;

    return 0;
}

The code was compiled as a console application for Win32 Debug so the variables would get “registered”.

The test machine is a Dell Precision M4800. The process is an Intel Core i7-4800MQ CPU at 2.70 GHz with 16GB ram. The OS is Windows 7 Professional 64 bit with SP1.

Here is the results. I have also included the assembler for the operation under test.

define time assembly
FP_MULT 7.32s fld qword ptr [__real@bff0000000000000 (0BE7938h)]; fmul qword ptr [poo]; fstp qword ptr [poo]
FP_NEG 7.56s fld qword ptr [poo]; fchs; fstp qword ptr [poo]
INT_MULT 7.58s mov eax,dword ptr [poo]; imul eax,eax,0FFFFFFFFh; mov dword ptr [poo],eax
INT_NEG 7.59s mov eax,dword ptr [poo]; neg eax; mov dword ptr [poo],eax

I actually don’t believe I have accomplished too much as the setup to call the timing functions actually take many, many more opcodes.  However, this was an interesting experiment and I do now have a cool C++ stopwatch on Windows for more extensive testing on much larger blocks of test code.

CS-Script – C# scripting

A quick shout out is in order to Oleg Shilo.  The CS-script is fantastic for basic scripting needs or testing behaviors of C# and .NET.  Oleg has also included a plugin for Notepad++.

It also can be used to generate executable “scripts” to make useful utilities without bringing up an entire development environment and the overhead of projects and solutions.

For me personally, it will never really replace Python but it is good to know that there are alternatives for Windows based development when Python is not an option.  (Yes, those times do actually exist for some of us.)

More poo in the toolbox.

Notes on XML Serialization in C#

The poo crew was having some trouble understanding the behavior of XML serialization on .NET.  So we will add some clarity.

We wanted a serializer where default values could be set in code when reading older serialized XML and all tags were written regardless of “default value”.  This way, a human could inspect the XML and know that the properties they see are all of them, at the time of serialization.

XML Serializer

XmlSerializer has been there since the beginning of .NET time (or at least 1.1).  Here are some characteristics of XmlSerializer.

  1. All public properties from a public object are written using XmlSerializer as long as the [System.ComponentModel.DefaultValueAttribute(x)] is not attributed to the property.  This also can look like [DefaultValue(x)] and it is the same attribute.
  2. For strings, include [XmlElement(IsNullable = true)] as a decorator if you want the tag specifically in the XML and the string is not assigned.
  3. The default construction is performed when deserializing.  This is true for setting values in the constructor or assigning at declaration.

It is important to note that [DefaultValue()] has a second purpose.  Property grids use this to know whether or not to bold a value in the UI.  If the value = default value, the text is not bold.  If value != default value, the text is bold. That is all it does.  It absolutely does not change the class member no matter what your friends say.

Data Contract Serializer

This was added to the framework around .NET 3.0 (if we can believe Microsoft).  Here are the high points:

  1. All properties with [DataMember] appear to be written regardless of default values are set or not.  Why it didn’t work with SpiralToPolarPersistedData is something to look into.
  2. Constructors are not called when deserializing.  This is true for setting values in constructors or assigning at declaration.
  3. The only way to guarantee a default value is to assign the values in a method decorated with [OnDeserializing].  A common pattern is to call the default method assigning from the constructor and from the OnDeserializing method (assuming the default method isn’t overrideable).
  4. If you do not include OnDeserializing, the values in the class are the type’s default values regardless of construction or declaration.

XML Serializer Example Code

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class Script
{ 

  public class Record
  {
    private double n1;
    private double n2 = 100;
    private string operation;
    private double result;

    internal Record() 
    { 
      //n2 = 100;
    }

    internal Record(double n1, double n2, string operation, double result)
    {
      this.n1 = n1;
      this.n2 = n2;
      this.operation = operation;
      this.result = result;
    }

    public double OperandNumberOne
    {
      get { return n1; }
      set { n1 = value; }
    }

    public double OperandNumberTwo
    {
      get { return n2; }
      set { n2 = value; }
    }

    [XmlElement(IsNullable = true)]
    public string Operation
    {
      get { return operation; }
      set { operation = value; }
    }

    public double Result
    {
      get { return result; }
      set { result = value; }
    }

    public override string ToString()
    {
      return string.Format("Record: {0} {1} {2} = {3}", n1, operation, n2, result);
    }
  }

  static public void Main(string[] args)
  {
    Record record0 = new Record();
    Console.WriteLine(record0.ToString());

    Record record1 = new Record(1, 2, "+", 3);

    XmlSerializer serializer = new XmlSerializer(typeof(Record));

    using (FileStream stream = File.Open("test.xml", FileMode.Create))
    {
      serializer.Serialize(stream, record1);
    }

    Console.WriteLine("Press any key...");
    Console.ReadKey(false);

    using (FileStream stream = File.Open("test.xml", FileMode.Open))
    {
      Record record2 = (Record) serializer.Deserialize(stream);
      Console.WriteLine(record2.ToString());
    }
  }   
}

Data Contract Serializer Example Code

using System;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;

public class Script
{ 

  [DataContract]
  internal class Record
  {
    private double n1;
    private double n2; // = 100;
    private string operation;
    private double result;

    internal Record() 
    { 
      // n2 = 100; */ 
      SetDefaults();
    }

    [OnDeserializing]
    private void OnDeserializing(StreamingContext context)
    {
      SetDefaults();
    }

    private void SetDefaults()
    {
      n2 = 100;
    }

    internal Record(double n1, double n2, string operation, double result)
    {
      this.n1 = n1;
      this.n2 = n2;
      this.operation = operation;
      this.result = result;
    }

    [DataMember]
    internal double OperandNumberOne
    {
      get { return n1; }
      set { n1 = value; }
    }

    [DataMember]
    internal double OperandNumberTwo
    {
      get { return n2; }
      set { n2 = value; }
    }

    [DataMember]
    internal string Operation
    {
      get { return operation; }
      set { operation = value; }
    }

    [DataMember]
    internal double Result
    {
      get { return result; }
      set { result = value; }
    }

    public override string ToString()
    {
      return string.Format("Record: {0} {1} {2} = {3}", n1, operation, n2, result);
    }
  }

  static public void Main(string[] args)
  {
    Record record0 = new Record();
    Console.WriteLine(record0.ToString());

    Record record1 = new Record(1, 2, "+", 3);

    DataContractSerializer serializer = new DataContractSerializer(typeof(Record));

    using (FileStream stream = File.Open("test.xml", FileMode.Create))
    {
      serializer.WriteObject(stream, record1);
    }

    Console.WriteLine("Press any key...");
    Console.ReadKey(false);

    using (FileStream stream = File.Open("test.xml", FileMode.Open))
    {
      XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
      Record record2 = (Record) serializer.ReadObject(reader, true);
      Console.WriteLine(record2.ToString());
    }
  }
}

C# and nullable value types

In C# you can declare nullable value types.  (This isn’t really what happens but the syntax looks like it.)  This is an unusual construct for those who come from other “lower-level” languages such as C++.

For example, the following declaration of “i” can not be set to null.

int i = 42;

However, in the following example, the following can be done.

int? j = 42;
int? k = null;

This blows my C++ brain.  In reality, “j” and “k” are not ints.  They are objects of type System.Nullable<T> as Microsoft describes here.

So, to safely coerce to int, you will need to check the value to be sure it is not null.  One approach is to use the HasValue method to make decisions or the GetValueOrDefault to simply get the default base type value.  For that matter, you can assign in a try-catch block but that seems so evil.

Finally, the cleanest type is the null-coalescing operator which is another foreign concept to C++ type brains.

Check out each example below.

int? i = null;
int j;

if (i.HasValue)
   j = (int) i;
else
   j = 42;

// j = 42 as i is null
Console.WriteLine("j = " + j.ToString());

// y is set to zero 
j = i.GetValueOrDefault();
// j = 0 as i is null
Console.WriteLine("j = " + j.ToString());

// an exception? really?  
try
{
    j = i.Value;
}
catch (InvalidOperationException e)
{
    Console.WriteLine("Why would anyone do this?");
}

// my favorite
j = i ?? 42;
Console.WriteLine("j = " + j.ToString());

The output you ask?  (That’s right, I heard you.)

j = 42
j = 0
Why would anyone do this?
j = 42

Using an exception is like having only one square of single-ply toilet paper.  If it is all you have, you use it.  However, we both know there are better methods.

C# WebRequests without Proxy or Delay

WebRequest objects in C# are useful creations when you want to script interaction with a web server in your application.  However, there are some common gotchas that I always have to look up to rectify.  So here are three of the most common in one handy location.

Nagle Algorithm

First, remove the use of the Nagle algorithm.  The Nagle algorithm is great for protocols like telnet where there is a chance of sending small amounts of data.  It is not so good for a protocol where packet sizes are intentionally small.  It will kill performance while queuing up bytes of data to send.  Use the following:

System.Net.ServicePointManager.UseNagleAlgorithm = false;

Expect 100 Continue

Expect 100 Continue is an HTTP 1.1 addition where a request can detect the readiness of a server before sending the a large body in a post.  The WebRequest object always sends an Expect: 100-continue in the header.  Not all web servers support handling this (i.e. lighttpd).  I suppose there is value to the 100 status code when posting large bodies but for most data transfers (i.e. SOAP, REST, XMLRPC, etc.), it doesn’t seem to be very useful.  Use the following to disable this.

System.Net.ServicePointManager.Expect100Continue = false;

WebRequest Proxy

By default, Windows will use the proxy settings internally set.   If you know your network is local, allowing the .NET framework to evaluate the default proxy settings can take unnecessary time.  You can set .NET to not use or look for any proxy by setting the following code:

WebRequest request = WebRequest.Create (resource);
    request.Proxy = null;

or

WebRequest.DefaultWebProxy = null;

Please remember to flush.