December 2, 2007

Pattern for Detecting Object Leaks

A simple method
// Add these to the class
private static int instanceId = 1;
private int instance = 1;

// Call this within the contructor
public SetObjectInstance(...)
{
    instance = instanceId;
    instanceId++;
    Debug.WriteLine("XXX instance \'" +
        instance.ToString() + "\' constructed");
}

// Within the finalizer OR if the object does not have a Finalizer add one
~XXX()
{
    Debug.WriteLine("XXX instance \'" + instance.ToString() + 
     "\' finalized");
}

Deploying Unmanaged DLLs

Found this neat trick here Nice idea. Tried it and it works. Heres my version of the resource extractor:
public static class ResourceExtractor
{
    public static void ExtractResourceToFile(
      string resourceName, 
      string filename)
    {
        if (System.IO.File.Exists(filename))
        {
            System.IO.File.Delete(filename);
        }
        if (!System.IO.File.Exists(filename))
        {
            using (System.IO.Stream s = System.Reflection.Assembly.
               GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                using (System.IO.FileStream fs = new System.IO.
                            FileStream(filename, System.IO.FileMode.Create))
                {
                    byte[] b = new byte[s.Length];
                    s.Read(b, 0, b.Length);
                    fs.Write(b, 0, b.Length);
                }
            }
        }
    }
}