Find out how wpf is being rendered

WPF applications can render in three modes: everything in software, partial hardware rendering or full hardware rendering. The rendering mode may have a big effect to the application performance. This it is important to know which mode is active:

           Console.WriteLine("WPF Rendering " + GetStringForRenderCapabilityTier(RenderCapability.Tier));
            RenderCapability.TierChanged +=
                (sender, args) => Console.WriteLine("WPF Rendering changed to " + GetStringForRenderCapabilityTier(RenderCapability.Tier));


        private string GetStringForRenderCapabilityTier(int tier) {
            switch (tier / 0x10000) {
                case 0:
                    return "Software Rendering";
                case 1:
                    return "Hardware Rendering (partial)";
                case 2:
                    return "Hardware Rendering (full)";
                default:
                    return "Unknown Rendering Mode: " + tier;
            }
        }

Get a large corpus of text data

I needed to get a large corpus of text data in order to test some full-text-search functionality. Also the text data should not be in one big file but in many small files instead. This lead me to Project Gutenberg and to Wikipedia.

Here is how you can get lot’s of data (we exclude the zip from gutenberg because they contain just the other files that are downloaded anyway):

mkdir Gutenberg-orig/
cd Gutenberg-orig/
rsync -rlHtSv --delete --exclude '*.zip' ftp@ftp.ibiblio.org::gutenberg ./

wget --recursive --no-parent http://dumps.wikimedia.org/other/static_html_dumps/current/

Extending the LiquidCrystal library

When using the LiquidCrystal library to output some text on an LCD on my Arduino Uno, I stumbled upon the following problem: if a text is displayed on the screen (let’s say “hello world!”) and you try to display another text (let’s say “bye”) you end up with the following text: “byelo world!”.

The reason for this is that the screen doesn’t clear a line before writing to it.

I could easily solve the problem in my code (just print spaces for all remaining characters) but I thought it would be more convenient if I built the capability directly into the Library. I added a function printLine(int line, const String text) which solves this task.

Download LiquidCrystalExt. To install you just have to unzip and copy it into the folder library either of the Arduino IDE or of your sketchbook.

Example:

#include  	

const int LCD_WIDTH = 16;
const int LCD_HEIGHT = 2;

const int PIN_LCD_RS = 5;
const int PIN_LCD_ENABLE = 6;
const int PIN_LCD_D4 = 8;
const int PIN_LCD_D5 = 9;
const int PIN_LCD_D6 = 10;
const int PIN_LCD_D7 = 11;

LiquidCrystalExt lcd(PIN_LCD_RS, PIN_LCD_ENABLE, PIN_LCD_D4, PIN_LCD_D5, PIN_LCD_D6, PIN_LCD_D7);

// the setup routine runs once when you press reset:
void setup() {
  lcd.begin(LCD_WIDTH, LCD_HEIGHT);
  
  lcd.printLine(0, "hello world!");
  lcd.printLine(0, "bye");
}

void loop() {
  while (true) {
  }
}

Wikipedia Gotcha if using a proxy server

I was coding a small proxy server. It worked quite nicely with most webpages. But it had problems with Wikipedia.

Firefox issued a request like this:

GET http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png HTTP/1.1
Host: upload.wikimedia.org

but Wikipedia responded with (trimmed down version):

404 Not Found
The resource could not be found.
 Regexp failed to match URI: "http:/upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"  

However when I deactivated the proxy it worked. First I was puzzled but then I found out what the reason was. It was stated in the HTTP/1.1 Standard (http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5). In Section 5.1.2:

To allow for transition to absoluteURIs in all requests in future versions of HTTP, all HTTP/1.1 servers MUST accept the absoluteURI form in requests, even though HTTP/1.1 clients will only generate them in requests to proxies.

So this means that Firefox issues other requests if a proxy is configured (absolute URIs instead of relative ones) and that Wikipedia doesn’t obey the HTTP Standard as it should accept the absolute URIs as well

C# Pass Arguments to the first instance of a program

Sometimes you don’t want the user to run more than one instance of a program. But if the user associates a filetype with your programm it shall open the filetype in this first instance. The code below uses interprocess communication to find out if there is already another instance. It further allows the first instance to register an eventhandler which can be called from a second instance in order pass its command line parameters to the first instance.

This is how to use the code:

using System;
using System.Collections.Generic;
using System.Text;

namespace SingleInstanceApp
{
    class Program
    {
        static void myReceive(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine("MSG Received " + i.ToString() + ": " + args[i]);
            }
        }

        static void Main(string[] args)
        {
            // test if this is the first instance and register receiver, if so.
            if(SingleInstanceEnforcer.IamFirst(new SingleInstanceEnforcer.CommandLineDelegate(myReceive)))
            {
                // first instance
                while (true) {
                    System.Threading.Thread.Sleep(1000);
                }
            }
            // second instance
            else
            {
                // send command line args to running app, then terminate
                SingleInstanceEnforcer.PassCommandLine(args);
            }

            SingleInstanceEnforcer.Cleanup();
        }
    }
}

This is the SingleInstanceEnforcer class

using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Channels.Ipc;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;

namespace Common.IPC {
    /// <summary>
    /// Helper class that allows the first instance to register a CommandLineHandler which can receive the command line arguments of subsequent 
    /// instances.
    /// </summary>
    [Serializable]
    public class SingleInstanceEnforcer : MarshalByRefObject {
        private static IpcChannel _mIpcChannel;

        // used to check if this is the only instance running
        private static Mutex _mMutex;

        // some constants to setup the channel between the server (the first) and the client (subsequent) instances
        private const string PORT_NAME = "IPCDemo";
        private const string SERVICE_NAME = "IPCDelegates";
        private const string SERVICE_URL = "ipc://" + PORT_NAME + "/" + SERVICE_NAME;
        private const string UNIQUE_IDENTIFIER = "03a28812-bf16-4db2-a03f-e0fb939813db";

        // signature of the handler
        public delegate void CommandLineDelegate(string[] args);

        /// <summary>
        /// Here we can assign methods that will be called if we receive command line arguments
        /// </summary>
        static private CommandLineDelegate _mCommandLine;
        static public CommandLineDelegate CommandLineHandler {
            get {
                return _mCommandLine;
            }
            set {
                _mCommandLine = value;
            }
        }

        /// <summary>
        /// Checks if this is the first instance. If it is it does also register the CommandLineDelegate
        /// </summary>
        /// <param name="r"></param>
        /// <returns></returns>
        public static bool IsFirst(CommandLineDelegate r) {
            if (IsFirst()) {
                CommandLineHandler += r;
                return true;
            }

            return false;
        }

        /// <summary>
        /// Does just check if this is the first instance. If you want to receive command line arguments from other instances you still need
        /// to register a CommandLineHandler
        /// </summary>
        /// <returns></returns>
        public static bool IsFirst() {
            _mMutex = new Mutex(false, UNIQUE_IDENTIFIER);

            if (_mMutex.WaitOne(1, true)) {
                //We locked it! We are the first instance
                CreateInstanceChannel();
                return true;
            }

            //Not the first instance
            _mMutex.Close();
            _mMutex = null;
            return false;
        }

        /// <summary>
        /// Registers the channel for the server
        /// </summary>
        private static void CreateInstanceChannel() {
            // correct serialization of delegates
            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider {
                TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full
            };

            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();

            // Create and register the channel
            Dictionary<string, string> properties = new Dictionary<string, string>();
            properties["portName"] = PORT_NAME;
            _mIpcChannel = new IpcChannel(properties, clientProv, serverProv);

            ChannelServices.RegisterChannel(_mIpcChannel, false);
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(SingleInstanceEnforcer),
                SERVICE_NAME,
                WellKnownObjectMode.SingleCall);
        }

        /// <summary>
        /// Cleanup all used resources. Can be called from the server or from a client
        /// </summary>
        public static void Cleanup() {
            if (_mMutex != null) {
                _mMutex.Close();
            }

            if (_mIpcChannel != null) {
                _mIpcChannel.StopListening(null);
            }

            _mMutex = null;
            _mIpcChannel = null;
        }

        /// <summary>
        /// A client (subsequent) instance can send its Command Line parameter to the first instance (server)
        /// This method might throw an exception for various reasons (could not register the channel, object was not in channel, ...)
        /// </summary>
        /// <param name="s"></param>
        public static void PassCommandLine(string[] s) {
            IpcChannel channel = new IpcChannel("IPC_Client");
            ChannelServices.RegisterChannel(channel, false);
            SingleInstanceEnforcer ctrl = (SingleInstanceEnforcer)Activator.GetObject(typeof(SingleInstanceEnforcer), SERVICE_URL);
            ctrl.ReceiveCommandLine(s);
        }

        /// <summary>
        /// Needs to be public because otherwise it cannot be called remotely!
        /// </summary>
        /// <param name="s"></param>
        public void ReceiveCommandLine(string[] s) {
            if (_mCommandLine != null) {
                _mCommandLine(s);
            }
        }
    }
}

C# Pitfalls

Closures

If you have code like this:

// strings is a list containing the values a, b and c
foreach (string str in strings) {
    Button btn = getButton(str);
    btn.Click += new EventHandler(delegate { MessageBox.Show(str); });
}

The result will be that each button shows a Messagebox with c. Altough one would expect to see a MessageBox with a for the first button. The reason is that the foreach loop gets unrolled into a while loop which has it’s str variable declared outside of the loop. The statement in the loop does not catch the value of the variable but the variable itself. After the foreach loop the value of the variable str is c.

See Blog-Post for details

Oracle SQL Functions

WIDTH_BUCKET

This function lets you create histograms.

This query does first (inner select) assign a bucket to the companies. This will be a number between 0 and 11. 0 is any company which has a minus value (underflow bucket), 1 is a company having a value between 0 and 100, 2 between 101 and 200, … 11 are all companies that have a value of more than 1000 (overflow bucket). The outer select does then group all companies according to their value. At the end we get a result like 5 companies have a value between 0 and 100, 300 companies have a value betwwen 101 and 200 and so on.

select
  bucket, 
  count(bucket)
from (select 
        width_bucket(c.value, 0, 1000, 100) bucket
      from 
        company c)
group by bucket
order by bucket;

See Oracle Documentation about WIDTH_BUCKET