Go to content Go to navigation Go to search

Brokenwire.NET::NET

How to unittest internals
· 2010-12-08 16:13 by Thijs Kroesbergen for Brokenwire.NET

This how-to is written by Mark Groot, and published on here on Brokenwire.net with his permission.

Normally when you try to unit test a method from an internal class, u will receive a message saying something like ‘… is inaccessible due to its protectionlevel’. The typical response in these kind of situations is either ‘ah, f.. it. I’ll just skip this test’ or ‘I’ll just make the class public. Who cares.’.

What you actually want to do is to make the internal method accessible to your unit test project. As it turns out, that this isn’t really all that difficult. Visual Studio will do most work for you. There are however a few things u have to keep in mind. In this article I will stretch out on those things.

First, let’s make a little console app which contains an internal class. (The entire solution can be downloaded here).

public interface ICoinFlip
{
  bool YouWon(bool choiceIsHead);
}


internal class CoinFlip : ICoinFlip
{
  public CoinFlip()
  {
  }

  bool ICoinFlip.YouWon(bool choiceIsHead)
  {
      // You can only win if you pick head
      // This is stupid, but that is not the point here
      return choiceIsHead;
  }
}

static void Main(string[] args)
{
  ICoinFlip flip = new CoinFlip();
            
  bool coinSideIsHead = (new Random()).Next(0, 2) == 1;

  if (flip.YouWon(true) == coinSideIsHead)
    Console.WriteLine("You win!");
  else
    Console.WriteLine("You lose!");
}

When you run this code you will get a nice little console window telling u whether or not you won.

Now how to test this? There are a few steps you have to take.

Let Visual Studio create a unittest and a unit test project for you.

You can create a unit test for the YouWon method by right-clicking the method and selecting ‘Create Unit Tests…’ from the contextmenu.

Clicking the menu option will popup the following window.

In the treeview you can select additional methods for which you want to create unit tests. You have to select a project from the listview in which the test has to be created.

Now Visual Studio will create a test class for the selected method in your selected unit test project including all the necessary references.

Visual Studio will also add the assembly:InternalsVisibleTo attribute to the AssemblyInfo file of your console application.

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("coinflipTest")]

By using this attribute the unit test assembly will become a “friend assembly ” of the main assembly, and therefore the main assembly will allow the test assembly access to its internals.

Edit the test method

Visual Studio will generate a TestMethod in the new test class looking like this:

After some clean up the code looks like this:

[TestMethod()]
[DeploymentItem("coinflip.exe")]
public void YouWonTest()
{
  ICoinFlip target = new CoinFlip();
  bool choiceIsHead = false;
  bool expected = false;
  bool actual;
  actual = target.YouWon(choiceIsHead);
  Assert.AreEqual(expected, actual);
}

We enter the value false into the method and we expect to receive a value false back. If that is true, then the test passed.

The following steps are only necessary when you have a strongly signed project:

Find the public key of your unit test project

There was a time where finding the public key token using sn –T was enough. Now however, the InternalsVisibleTo  attribute uses the public key.
We can retrieve that key in two steps by using the sn.exe tool.
First create a file with the public key from the assembly key file using the following command (inside a Visual Studio command prompt)

sn –p NameOfYourKeyFile.snk NameOfYourOutputFile.PublicKey.

Use the output file to retrieve the public key with the –tp option of sn.exe:

sn –tp NameOfYourOutputFile.PublicKey.

The result is some text and a large key looking like this:

Microsoft (R) .NET Framework Strong Name Utility  Version 4.0.30319.1
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key is
00240000048000009400000006020000002400005253413100040000010001003b825be7fe7e93
f782f0ff49cb2c86845698b15301834dc63cf9b9c62ea95aa02151a069cafb82f1902dfec1e2be
16b7f05d99e84a5796060d044ab62a1bcc6ffc7d12ab03827c22b4a70a67797bc82aea51a6c9b9
c31fee99410dbbc54b32dd9b18f202e97912b967120d4655a8575a2568738e7a08b662a0004440
91d500cf

Public key token is de3fc1b9aa83af40

Then add the key into the AssemblyInfo of the console application.

As we saw before, when we created the unit test the following entry was created in the AssemblyInfo file:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("coinflipTest")]

You have to change this into:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("coinflipTest, PublicKey=PASTE-YOUR-PUBLIC-KEY-HERE")]

Here you copy-paste the public key from the previous step into the marked section. You will have to remove the linebreaks, but that should be rather obvious. Don’t copy the key shown here, you have to use your own key…

To see if this works: build the project, and run the test.

Enjoy!

Permalink -

Equals is not Differs
· 2010-10-12 12:43 by Thijs Kroesbergen for Brokenwire.NET

Just a small code snippet I wanted to share with you… (it made me laugh and cry at the same time)

public bool Equals(Adres a2)
{
    return !Differs(a2);
}

public bool Differs(Adres a2)
{
    return (a2 == null)
    || (this.Straat != a2.Straat)
    || (this.Huisnummer != a2.Huisnummer)
    || (this.Postcode != a2.Postcode)
    || (this.Plaats != a2.Plaats)
    || (this.DatumIngang != a2.DatumIngang)
    || (!this.DatumEinde.HasValue && a2.DatumEinde.HasValue)
    || (this.DatumEinde.HasValue && !a2.DatumEinde.HasValue)
    || (this.DatumEinde.HasValue && a2.DatumEinde.HasValue && (this.DatumEinde.Value != a2.DatumEinde.Value))
    ;
}

Watch, learn, don’t repeat. Share the pain in the comments.

Permalink -

Christmas Lights updated
· 2009-12-11 17:40 by Thijs Kroesbergen for Brokenwire.NET

I just published a new version of the popular Christmas Lights. You can grab your free copy from the publish page right now.

So what’s new in this years update?

- New light bulbs: The new bulbs are bitmap based instead of “dynamic” WPF shapes, this reduces the CPU usage. And I think these look nicer too.

- Better stability: I resolved several issues which caused crashes when you changed the display resolution when the lights where active. Now you can also add/remove monitors while the lights are running.

- Plasma “burn-in” prevention: When this option is switched on the lights move a bit every minute so they don’t burn in your nice big plasma TV. :)

- Fully tested on Windows 7 but the lights will run on any pc having .NET framework 3.5(sp1). (This includes Windows XP, Vista, Server 2003)

DOWNLOAD NOW

I’ve already got some nice ideas for a future version, but suggestions (or patches) are always welcome!

Possible features for a next version:

- Make the blinking speed dependant on the power level of your laptop battery: As the battery gets empty the lights should blink slower (or faster).

- Make the lights blink when sound is detected, so they can sync up with your favorite Christmas tunes.

- Create more blinking patterns and add a pattern to cycle through all other patterns.

So prepare your PC for the Christmas season and install the lights!
And if you are curious about the code that makes all that goodness happen, take a look at the “Wpf Christmas Lights” CodePlex project page. There you can also report bugs or post suggestions.

Happy Holidays!

Permalink -

Pimp my software
· 2009-06-23 09:00 by Thijs Kroesbergen for Brokenwire.NET

Everyone who has done some (serious?) software development knows that we have several different methods to run our project. We also know that not all methods are equally successful. But one of our favorite things to do is compare our ways of doing things with others in the more “traditional” trades.

So a little while ago I was watching MTV’s "Pimp My Ride", and then I was thinking, what would software development look like if we did it the “Pimp My Ride” way?

So let’s see what that would look like. For those of you who don’t know the Pimp My Ride TV show, it goes like this:

The show starts by showing a teenager with a banged up car. That car gets picked up by the shows host and brought to a garage. Then a team of mechanics goes wild on the car by remodeling it completely. Then the owner is brought in, the car is presented and a happy guy (or girl) leaves the shop with a new ride. If you want to see this for yourself, take a look at the MTV website.

Now let’s break that down into the parties involved. The core group of people involved is of course the team of mechanics. This team designs and builds the car. The way this team is composed is that several people with different specialties are brought together in the right mix. In our world this would be team of highly skilled software engineers. This way each member should have its own specialty like data-access, user interfaces and such. Perhaps the most important thing to notice is that all team members are involved from start to finish.

Then there’s the host of the show, he gets to pick up the car, monitor the work on it and deliver it back to the owner. In the software development world this could be the project manager with a bit of help from some sales guy perhaps.

Last but not least we have the owner of the crappy car. This is comparable our customer, who has a problem (a crappy car, or some complex business process) and needs someone to solve it for him.

That wraps up the parties involved, now lets move to the process.

At the start of each episode (project) the old car gets picked up from some lucky bastard by the presenter of the show, a rapper known as “Xzibit”. They chat a bit and X gets a pretty good idea about the likes and dislikes of the car’s owner. This translates to an combination of sales and analysis. There’s communication with the customer, and both the scope and the requirements are set. For example, the owner drives a VW Beetle (scope) and likes to sing (requirement).

Once this is done the car is brought back to the garage and the whole team gets to take a good look at it. Then they sit together and each specialist tells what he thinks that needs to be done to the car.

Lets see how that meeting works out…

Paint specialist:

“I’m gonna put on a base layer of toxic green paint, and then I’ll airbrush some hot flames on the side of this wicked car!”

User Interface guy:

“I’m going to design a WPF based interface with nice glowing buttons which animate on mouse-over”

Engine tuner:

“Let’s upgrade the engine so it can do 0-60mph in 2.9 seconds! For that I’ll use this nice turbocharger kit.”

Database guru:

“I recommend that we store our data in a clustered SQL Server database, and we’ll use LINQ for our data access layer. This way we will have performance and speedy development all at once!”

You get the point ;). This meeting is like the project kickoff. Here the architecture is determined and the individual components are defined.

Then they get to work. Each specialist does what he does best, and they work together as the gears of a well oiled machine. Sometimes they encounter something unexpected, but with all the knowledge they have on board they will continue to deliver the finished product right on schedule. This is actually exactly the same thing that is (or should be) happening in any software delivery process.

Finally during the last minutes before the car’s owner arrives the finishing touches, such as polishing the car, are applied. Then the big unveiling takes place, and a happy customer leaves the building.

“You’ve officially been pimped”

The handover of the car’s keys translates to the delivery phase in our world. This where the happy customer accepts the finished product. And a happy customer is what we are aiming for!

To conclude this rant, lets see why this “Pimp My Ride” process should work for software as well:

But of course there are some differences as well, so why doesn’t this work for software?

It looks like this comparison doesn’t hold up too well (but I had fun trying it anyway). I do think that we like to over-complicate things because with software it’s so easy to create anything our mind can come up with. And because of our human nature we just love to try stuff that hasn’t been done before. Perhaps, given some more time and thought, the expectations for software will become just as clear as the expectations we have of a car.

So what do you think? Does any of this make sense? Is building software harder then building a custom car? Are we spoiled by all the options we have and do we over-complicate?

Permalink -

Quick Visual Studio Tip
· 2009-04-19 14:07 by Thijs Kroesbergen for Brokenwire.NET

Press CTRL + SHIFT + V to cycle through previous clipboard entries (and paste them). This way you can “cut” several pieces of code, and “paste” them somewhere else without going back and forth. (You could also use “copy” multiple times and then use this to “paste” that, but of course nobody is interested in copying code…)

There are more hotkeys in Visual Studio that are not so well known, take a look here.

Permalink -

Decrypting Sql 2005 SPs made easy
· 2009-03-25 15:05 by Thijs Kroesbergen for Brokenwire.NET

Today I ran across a problem where I desperately needed to peek inside a stored procedure used by Team Foundation Server. The only trouble was that the stored procedure was created with the “WITH ENCRYPTION” clause appended, so I couldn’t see the source.

To decrypt the stored procedure I used a stored procedure called dbo.sp_SpDeObfuscation, which can be found here and/or downloaded here.

Please keep in mind that you need to run the SP from an DAC (Dedicated Admin Connection)

Permalink -

Previous