Friday, February 29, 2008

Speeding up Unit Testing in Visual Studio 2008

I've been doing unit testing in Visual Studio 2008. I noticed it takes a while for the tests to execute after I start the test run.

Initially I thought it was copying data into the TestResults directory. Some of our unit tests rely on files and our test run copies ~30 MB of data into the TestResults directory.

I found out it was the code coverage instrumentation process slowing it down. On my machine it seems to take about a second to instrument an assembly for code coverage. Our project has 8 assemblies which adds ~8 seconds to every run. While it is important for our server build to have all the assemblies instrumented, when I'm creating unit tests I just need to have my assembly instrumented. Going into the GeneralRun.testrunconfig --> Code Coverage and instrumenting only the assembly I'm working on reduces the run speed by about 7 seconds.

If you do this, ensure you don't accidentally check this change into Team Foundation Server or you won't get complete code coverage results.

Skipping the deployment of the 30MB of data had no noticeable effect on the test run times.

Monday, February 25, 2008

Creating a metafile in .NET

Metafiles are a way to save scalable vectory graphics. This blog creates a simple image containing a diagonal line. It also shows the proper way to save the metafile, as the class method saves it as a png file.

MSDN article on MetaFiles:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

MemoryStream metafileStream = new MemoryStream();

Graphics offScreenDC = Graphics.FromHwndInternal(IntPtr.Zero);

IntPtr myImagePointer = offScreenDC.GetHdc();

Metafile meta =
//new Metafile(myImagePointer, EmfType.EmfOnly); //unable to do memoryStreamSave
new Metafile(metafileStream, myImagePointer, EmfType.EmfOnly); //able to do memoryStreamSave

Graphics aGraphic = Graphics.FromImage(meta);

aGraphic.DrawLine(new Pen(Brushes.Black), new Point(0, 0), new Point(29, 29));

aGraphic.Dispose(); //Dispose must be called to flush the drawing instructions.

meta.Save(@"c:\metaSave.wmf"); //saves as a png file.

FileStream aWrite = new FileStream(@"c:\StreamSave.wmf",FileMode.Create); //saves as a wmf file