MassFlash v1.0
Preparing many flash disks with the same data is tedious and might I add very boring. On my quest to learn Powershell, I might just as well put it to good use. With just a few lines of code I managed to cook up a script to do the mind-numbing work of preparing flash disks. It does the work and I watch. Perfect!
It is a very simple script that:
- Formats each flash drive to FAT32;
- Copies the contents of the specified directory recursively onto the flash drive;
- Dismounts the volume.
The script finds all removable drives between 1gb and 64gb in size. We don’t want to slip up here, now do we?
At the top of the script, a default directory is specified from where all files will be copied if an alternative directory was not specified on the command line.
Write-Host "MassFlash - Version 1.0"
Write-Host "Author: SS du Plooy"
Write-Host "-----------------------"
If($args.Length -eq 0)
{
$DirectoryToCopy = "c:\DefaultFromCopyLocation"
}
Else
{
$DirectoryToCopy = $args[0]
}
Write-Host "Preparing flash disks with files from" $DirectoryToCopy
$drives = Get-WmiObject Win32_LogicalDisk -filter "DriveType=2"
Foreach($drive in $drives)
{
[int] $driveSize = $drive.Size/1073741824 #convert to gigabytes
If($driveSize -ge 1 -and $driveSize -le 64)
{
$driveLetter = $drive.DeviceID
$volume = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = '$driveLetter'"
$label = "TKP"+$(get-date -f ssfff)
Write-Host Formatting drive $driveLetter [$label] [$driveSize GB]
$volume.Format("FAT32", $true, 4096, $label, $false)
Write-Host "Copying $DirectoryToCopy to $driveLetter"
Copy-Item $DirectoryToCopy $driveLetter -recurse
Write-Host Dismounting drive $driveLetter
$volume.Dismount($true, $false)
}
}
Write-Host "Done."
Now you can put your time and mind to better use instead of preparing flash drives all day long.
Note: The script must be run with Administrator privileges.
Monitoring disk space with Powershell
Running out of disk space all of a sudden is just not cool. It tends to wake up men in black suits, bring on the gnashing of teeth and frothing at the mouth. I don’t like that type of drama.
So, I knocked up a little Powershell script that can be scheduled to email a disk space report everyday. Currently the script is written to send a report on a single drive only. There are many other variations of this type of script that reports on all the drives on a server.
$disk = Get-WmiObject -ComputerName $env:COMPUTERNAME Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3} | Where-Object {$_.DeviceID -eq ":"}
[float]$totalSize = [Math]::Round($disk.Size / 1073740824, 2)
[float]$freeSpace = [Math]::Round($disk.FreeSpace / 1073740824, 2)
$deviceID = $disk.DeviceID
$percentFree = [Math]::Round(($freeSpace / $totalSize) * 100, 2);
$smtpServer = ""
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$emailFrom = "$env:COMPUTERNAME"
$emailTo = ""
$subject = "$env:COMPUTERNAME - Disk space report"
$body = "$deviceID | Total: $totalSize GB | Available: $freeSpace GB | $percentFree % disk space available"
$smtp.Send($EmailFrom,$emailTo,$subject,$body)
When it comes to management, you might just as well only print the precentage of free disk space and perhaps add that to the subject of the email. That will give all the relevant information in one look. The script can be extended to report on multiple servers and multiple drives.
Have fun!
Getting Fit, Uncle Bob style!
Fit: Framework for Integrated Test
Great software requires collaboration and communication. Fit is a tool for enhancing collaboration in software development. It’s an invaluable way to collaborate on complicated problems–and get them right– early in development.
Fit allows customers, testers, and programmers to learn what their software should do and what it does do. It automatically compares customers’ expectations to actual results. [Cunn 07]
Read an introduction to FitNesse.
Installing FitNesse
To start using FitNesse with .net, you’ll need to download FitNesse and fitSharp. Once downloaded, place the fitnesse.jar file in a directory, for example c:\FitNesse. Extract the files from the fitSharp archive into a subdirectory in the same folder as fitnesse.jar called fitSharp.
Start FitNesse using java -jar fitnesse.jar -p 8080 where -p is the port number. FitNesse installs in a directory called FitNesseRoot. Browse to http://localhost:8080 and you should see the FitNesse front-end.
Creating a test fixture
To use FitNesse you’ll need to give a test fixture that FitNesse can execute. A test fixture is derived from one of the classes provided by the Fit framework. For this example, derive a test fixture from ColumnFixture. This will allow us to run the test case using a decision table with input and output values. Add a reference to both fit.dll and fitSharp.dll in your project.
namespace Humanresources.Domain
{
public class EmployeeTests : fit.ColumnFixture
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return string.Concat(FirstName, " ", LastName); }
}
}
Setting up the test case
To setup the test case, you will need to create a wiki-page. On the front page of FitNesse, click on Edit and enter a wiki-word with the name of the test case. A wiki-word is a word written in Pascal-case surrounded by square brackets, i.e. [EmployeeTests]. Click Save and then click on the question mark to go to the page and click on Edit.
To setup the test, you ‘ll need to define a couple of variables, they are
- location of the assembly under test;
- how to invoke the test runner;
- location of the test runner.
!path C:\Projects\Experiments\HumanResources\HumanResources.Domain\bin\Debug\HumanResources.Domain.dll
!define COMMAND_PATTERN {%m -r fitnesse.fitserver.FitServer,c:\FitNesse\FitSharp\fit.dll %p}
!define TEST_RUNNER {c:\FitNesse\FitSharp\Runner.exe}
|humanresources.domain.employeetests| |firstname|lastname|fullname? | |John |Lidin |John Lidin | |Joshua |Cohen |J Cohen | |Allan |Butler |A Butler |
The first line specifies the class that is under test, the second line specifies the input values that are assigned to the properties with the same name and the following lines give the input and expected output values. The last column with the question mark is the evaluation column. This is a simple decision table. The last column name may also be the name of a method.
In the table, we are assigning the value John to FirstName property and Lidin to the LastName property. The expectation is that FullName is a concatenation of FirstName, a space and then followed by the LastName.
Before the test is run, you’ll need to tell FitNesse that this page is a page that contains tests and is not just a simple wiki-page. To change the page type to test page, click on Properties, select Test and then click Save.
An important thing to note here is that all the property names and class names are in lower case. This is intentional as Pascal-cased words are interpreted as wiki-words. For your own sanity keep them in lowercase.
Your page should now look like this:
Run the test case
Click on Test and you should see the following output:
The tests can also be executed from the command line, are you thinking what I’m thinking?
Troubleshooting
- Fit.dll file load exception
System.IO.FileLoadException: Could not load file or assembly 'file:///c:\FitNesse\FitSharp\fit.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515) File name: 'file:///c:\FitNesse\FitSharp\fit.dll' ---> System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
To solve this issue, simply add a configuration file to the runner that you’re using. If you are using runner.exe then create a file called runner.exe.config and add the following text into runner.exe.config:
<configuration>
<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>
</configuration>
- If you encounter any other issues you can do the test run using a debugger.
References
[Cunn 07] Cunningham, Ward. Making Fixtures. Framework for Integrated Test. October 12, 2007. http://fit.c2.com/search.cgi?search=WelcomeVisitors
Unit testing with Jenkins
Continuing to setup a build for the first time with Jenkins there is, uh, another challenge. For some reason, I thought it clever to make use of MsTest. This works wonderfully on the development machine. But, of course, when it comes to the build server, you can expect all sorts of weirdness. For example, error CS0246: The type or namespace name ‘TestMethodAttribute’ could not be found…
We’re sorry, but our testing tools don’t come standard with the .NET Framework, or in any other way, except TFS and Visual Studio, unless you are willing to follow this brave soul. I share Derik Whittaker’s sentiment on the MsTest and build server issue.
This is another issue to me because MSTest is the ONLY test framework (for .Net) that I know of that does not run with a single DLL placed into the bin (or any other output directory). I just have to ask the genius’ over in Redmond what the hell were they smoking when they decided to build MSTest. It is pretty clear they had no prior knowledge of how to use the other tools such as NUnit, MBUnit or xUnit (I know, xUnit was not out yet). I know this because of all the various testing frameworks MSTest is the one that does everything different. You could argue they were on the cutting edge and were innovating, but I call BS on that.
This can be solved. So long MsTest… Hello NUnit!
Converting from MsTest to NUnit
Converting from MsTest is a simple case of find and replace of attributes. NUnit has the nifty Assert.Catch<T> which beats MbUnit, MsTest and xUnit. xUnit comes with Assert.Throws<T> but cannot assert the exception message whereas NUnit can. No more [ExpectedException] attributes.
Integrating NUnit with the build file (which is MsBuild) is pretty easy:
<Exec Command=”$(NUnitFolder)\nunit-console-x86.exe [TestAssembly] /framework=net-4.0 /xml=$(TestResultsFolder)\TestResults.xml” />
A single Exec statement and out comes an Xml file. To keep the build server clean, I decided to add all the necessary files for unit testing into source control along with the project. The bare minimum files for running NUnit from the command line comes down to the following files:
- nunit.core.dll
- nunit.core.interfaces.dll
- nunit.framework.dll
- nunit.util.dll
- nunit.console-runner.dll
- nunit-console-x86.exe
- nunit-agent-x86.exe
- nunit-agent-x86.exe.config
To make it work on .Net Framework 4.0, you have to include the /framework=net-4.0 switch on the command line.
Setting up Jenkins with NUnit
Install the NUnit plugin for Jenkins, point it to your test results file and after a build you’ll get the summarised test results. It’s a neat table with all the classes and their respective timings and so on.
Finally, I have a working build with unit testing. If only it had an installer…
Jenkins and Git
The road split for Hudson and Jenkins. It happens.
Getting the source code…
I don’t have Cygwin or MSysGit installed on the server for my own perverse reasons. In order for Jenkins to get hold of the source code from a git repository is usually straight forward. Well, now comes the time to get the source code from git. I can clone repository into a local directory using GitSharp. GitSharp is the .net version of git and very cool, but not quite finished yet. The alternative is a Java application called JGit. GitSharp, by the way, is a derived work of JGit.
Setting up Jenkins…
Download the shell script of JGit which, by the way, is a self-contained command line executable. With that, I am able to test the cloning of a repository into a new folder with the following command line:
C:\JGit>java -cp org.eclipse.jgit.pgm-0.10.1.sh org.eclipse.jgit.pgm.Main clone
http://dev/git/myproject.git c:\projects\myproject
After executing the above command line, I have the source files in the c:\projects\myproject directory. To use this in Jenkins, I need to make use of the batch command execution since the git plugin makes use of git.exe and all the other things I didn't setup.
After running a build, I have the following console output in Jenkins and the source code in the build factory directory:Started by user anonymous [MyProject] $ cmd /c call C:\Windows\TEMP\hudson12048252217381411.bat d:\builds\factory\MyProject>"C:\Program Files\Java\jre6\bin\java.exe" -cp c:\jgit\org.eclipse.jgit.pgm-0.10.1.sh org.eclipse.jgit.pgm.Main clone http://dev/git/myproject.git d:\Builds\Factory\MyProject Initialized empty Git repository in d:\Builds\Factory\MyProject\.git remote: Counting objects: 342, done From {0} * [new branch] master -> origin/master d:\builds\factory\MyProject>exit 0 Finished: SUCCESS
by Sydney du Plooy
Git and Hudson Brothers
For a while now, I’ve been thinking about creating a source control and build server for a couple of projects that I’m working on. I’ll admit, I moonlight. Anyway, a great analysis ensued. Starting with the OS; what will it be, what does it need to be? Considering that I’m building .NET projects and they’re Windows based; well that kind of settles that. Next up, which source control system? Oh boy, this took a while…
Source Control
Since everyone, OK, almost everyone, raves about Git, I suppose I’ll have to succumb. But, this is where the fun starts. I want Git, I want Windows. Pushing, cloning and so on is what really I want. What a painful story… This requires the installation of MSysGit or Cygwin and some SSH server, blah blah, whatever. It was simply too much.
I decided to run VisualSVN on the server and then use git-svn to bridge that little dilemma. Well, that kinda sucked. After formatting and configuring and formatting and configuring, I finally found this post by Jeremy Skinner. It explains how to setup Git on Windows using IIS 7.0, without any other fancy installations and configurations. He calls it git-dot-aspx (GitAspx). To my surprise, this worked elegantly, the first time. Push, pull and clone without any issues. Great.
Continuous Integration
What a mental battle this turned out to be! What should I use, what do I need to use? There is from CruiseControl.NET to Hudson. A colleague mentioned Hudson and, being quite popular, I decided to investigate. This turned out to be a fantastic piece of software. It is a Java application, but I decided that it is well worth it. One click and it installs as a Windows service. One command line and it uninstalls cleanly. Unbelievable! Such a polished product. Also, it has many plugins from MsBuild to Git to Twitter. Talk about pressure, having your build status published to Twitter!
For a good Windows alternative, these two products turned out to be highly effective and user friendly.
AutoMocking with RhinoMocks and StructureMap
Auto mocking is the process whereby mock objects are created and injected into an object. By using this technique we relieve ourselves from the burden of creating and injecting mocks manually. Consider the following test class that requires two dependencies; namely, IPropertyDependency and IConstructorDependency:
public class ClassToBeAutoMocked
{
private IConstructorDependency _ConstructorInjectedDependency;
public ClassToBeAutoMocked(IConstructorDependency dep)
{
_ConstructorInjectedDependency = dep;
}
private IPropertyDependency PropertyDependency
{
get;
set;
}
public string PrintConstructorDependency()
{
return _ConstructorInjectedDependency.Print();
}
public string PrintPropertyDependency()
{
return PropertyDependency.Print();
}
}
The one dependency is provided in the constructor and the other is injected via the private property. Out-of-the-box, StructureMap AutoMocker provides the ability to mock and inject the constructor dependency. Private properties, however, are not supported. This can be solved by means of an extension method applied to the RhinoAutoMocker type, for example:
public static class RhinoAutoMockerExtensions
{
public static void RegisterPropertyDependency<TARGETCLASS>(this RhinoAutoMocker autoMocker, string propertyName) where TARGETCLASS : class
{
var propertyInfo = typeof(TARGETCLASS).GetProperty(propertyName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (propertyInfo == null)
{
throw new ArgumentException(string.Format("Property {0} was not found on the type {1}",
propertyName, typeof(TARGETCLASS).Name));
}
var propertyType = propertyInfo.PropertyType;
var mockDependency = MockRepository.GenerateMock(propertyType, null);
autoMocker.Inject(propertyType, mockDependency);
propertyInfo.SetValue(autoMocker.ClassUnderTest, mockDependency, null);
}
}
We now have the necessary pieces to get an auto mocked instance of ClassToBeAutoMocked.
Next, create an instance of the RhinoAutoMocker class with the concrete type, which will then create the constructor dependency mock and inject it. Because the private property dependency injection is not supported we have to tell the AutoMocker that we want the private property mocked and injected as well. We accomplish this by calling the extension method RegisterPropertyDependency with the name of the property that must be mocked. To obtain a reference to the generated mock we can call the Get method with the dependency type which will return the mock instance. We are then free to stub or set expectations on that dependency as required by our unit tests.
For example:
static void Main(string[] args)
{
var mocks = new RhinoAutoMocker(MockMode.AAA);
mocks.RegisterPropertyDependency("PropertyDependency");
mocks.Get<IConstructorDependency>().Stub(x => x.Print()).Return("On fire with the constructor dependency!");
mocks.Get<IPropertyDependency>().Stub(x => x.Print()).Return("On fire with the property dependency!");
Console.WriteLine("Constructor dependency output: {0}", mocks.ClassUnderTest.PrintConstructorDependency());
Console.WriteLine("Property dependency output: {0}", mocks.ClassUnderTest.PrintPropertyDependency());
Console.ReadLine();
}
IConstructorDependency
Resizing a virtual hard disk
Recently, I had to resize a VHD (virtual hard disk) that I installed Windows Server 2008 on. I soon found out that the size of 10GB is not such a hot idea when installing Team Foundation Server 2010 and SQL Server 2008 on the same instance. Hence, I decided to resize the disk instead of re-installing all of the software.
Below is the recipe to resize the virtual hard disk:
Part 1:
The first part is to resize the container of the partition, which is done by means of a sector copy. After the resize completed, the container will have increased but the partition will not be fully extended yet.
- Download VHD Resizer from VMToolkit.
- Install and run VHD Resizer.
- In the file open dialog select the VHD that you want to resize.
- Type in the new filename to use for the extended VHD.
- Type in the size of the new container to create.
- Click on Resize. The process takes a few minutes…
Part 2:
Now that the container is resized, we must now extend the partition to make use of the full container size.
- Attach the new extended VHD as a non-primary drive to another virtual machine. Do not extend the partition using the virtual machine that will make use of it.
- Start the virtual machine to which the extended VHD was attached as the non-primary drive and open a command prompt.
- Type in diskpart and press Enter.
- Type in list disk.
- Ensure that disk 1 or greater is the extended disk.
- Type in select disk 1.
- Type in list partition.

- Ensure that the partition sizes matches the old size.
- Type in extend.
- Wait for the process to complete and type exit.
Remember to change the disk on the original virtual machine to now use the extended disk. The disk is now resized and ready to be used from the original virtual machine.
Mocking multiple interfaces using Rhino Mocks
A while back on StackOverflow I asked a question on how to create a mock object with Rhino Mocks that implements multiple interfaces. In other words, I want to generate a mock that implements more than one interface. This baffled me for a while and I was shown the light by one of my colleagues.
A multi-mock is created like so:
var mocker = new MockRepository(); var mock = mocker.CreateMultiMock<IPrimaryInterface>(typeof(IFoo), typeof(IBar)); mock.Expect(x => x.AnswerToUniverse()).Return(42); mocker.ReplayAll();
Note the call to ReplayAll. Without this call the mock will not be setup with the intended values.
Unit test deployment issue when file is untrusted
Recently, I decided to use NHibernate in a project so that I could achieve database affinity. That provided me with another benefit and that was the ability to create a database in-memory for testing purposes. Sounded great, but while trying to run the unit tests using MsTest and SQLite, I received the following error: “Test Run deployment issue: The location of the file or directory ‘C:\projects\myproject\SQLite\sqlite3.dll’ is not trusted.“.
That problem was easily solved by simply unblocking the file. Below are the steps on how to unblock the file:
- Right-click the blocked file (sqlite3.dll), and then click Properties.
- This will open the properties dialog:
- In the General tab, click Unblock.
- Click on OK.
That’s it, the file is now trusted and the runtime should be able to load the file successfully.






leave a comment