Dynamic tests with mstest and T4

 Mar 5th, 2011 

 , , , , , ,

If you used mstest and NUnit you might be aware of the fact that the former doesn’t support dynamic, data driven test cases. For example, the following scenario cannot be achieved with the out-of-box mstest: given a dataset, create distinct test cases for each entry in it, using a predefined generic test case.

The best result that can be achieved using mstest is a single testcase that will iterate through the dataset. There is one disadvantage: if the test fails for one entry in the dataset, the whole test case fails.

So, in order to overcome the previously mentioned limitation, I decided to create a text template that will generate the test cases for me. As an example, I will write some tests for an integer multiplication function that has 2 bugs in it:

public int Multiply(int a, int b)
    //This conditions are simulating the 2 bugs
    if (a == 0 && b == 1)
        return 100;
    if (a == 1 && b == 0)
        return -100;
    return a * b;

The classical approach (no dynamic test)

Without using any ‘hacks’, one could write the tests for the Multiply function in the following way:

//Tuple description <value of param a, value of param b, expected result>
private static readonly Tuple<int, int, int>[] TestData = new Tuple<int, int, int>[]{
    new Tuple<int, int, int>(0,0,0),
    new Tuple<int, int, int>(2,3,6),
    new Tuple<int, int, int>(1,0,0), //These will trigger one of the bugs
    new Tuple<int, int, int>(-2,-3,6),
    new Tuple<int, int, int>(0,1,0) //These will trigger one of the bugs
public void TestMultiply()
    foreach (var data in TestData)
        Assert.AreEqual(data.Item3, Multiply(data.Item1, data.Item2),
                        "Failed for input ({0}, {1})", data.Item1, data.Item2);

Running the test will surface only one of the bugs, the one triggered by the input (1,0):

This is not only bad because it doesn’t give a complete overview of the bugs but it also violates the principle of one assertion per test because more than one assertion could be triggered in the test case above.

The T4 approach (dynamic test)

Read the rest of this post »

Modifying .NET binaries – Part 2

 Jul 21st, 2010 

 , , , , , , ,

ObjectiveRemove the ‘Trial protection’ from an obfuscated .NET application
  • WinDbg
  • CFF Explorer
Target audienceAdvanced users

The second part of the article discusses how to modify binaries that are obfuscated. For simplicity and clarity, I will not use obfuscated binaries. Doing this, allows the reader to understand what is actually happening. In the demo I will completely ignore the name of the methods or the actual, non-obfuscated, code.

I recommend reading the first part, if you didn’t already. It provides some information that might be needed to understand theis second part.

The same ‘TrialApp.exe’ binary is used. The current approach, as opposed the the former one, is:

  1. Load the application in debugger and break the execution when the trial message is displayed.
  2. Get the call stack
  3. Find the address of the trial check method
  4. Remove the call

1. Load the application in debugger and break the execution when the trial message is displayed

WinDbg can be obtained for free from Windows SDK (see the Microsoft Downloads website). If you are running a 64 bit OS, make sure you start the 32bit version of WinDbg (should be in Program Files (x86)).

Load ‘TrialApp.exe’ in WinDbg by clicking File -> Load Executable. In order to run it you have 3 options:

  1. Type ‘g’ and press ENTER
  2. Press F5
  3. Click Debug -> Go

The application will start and the execution will stop when the message box is displayed. Is actually waiting for the user to click OK. At this point break the execution by pressing Debug -> Break.

Before being able to debug the .NET application, 2 DLLs needs to be loaded. They help the debugger ‘understand’ the .NET internals. The actual paths might differ on your configuration. Anyway, make sure you load the 32 bit version of these files (the 64 bit version are in the Framework64 folder). The .load command loads external libraries.

.load c:\Windows\Microsoft.NET\Framework\v4.0.30319\SOS.dll
.load c:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll

Read the rest of this post »

Modifying .NET binaries – Part 1

 May 30th, 2010 

 , , , , , ,

The content of this post can be used for good and bad purposes. Modifying the source code to bypass trial/license checks is what crackers do in order to get paid software for free. Be advised that the purpose of this article is not to teach you how to steal. My target for this article are the .NET developers who should understand what a cracker will (try to) do in order to get access to paid features.

Before reading any further you should understand that each protection measure (as long as the cracker can access the source code) is useless. Is just a matter of time, for a motivated person, before she will bypass any protection.

For the demo, we are going to use a very simple Windows Forms Application that will display a message box with a trial message and will exit after that. The goal is to show a few techniques that will prevent the application from exiting (and will remove the trial message).

The code for the ‘trial’ application is kept in just one class. There is just one variable for checking the trial and we’ll consider that is always true – it makes no difference if there was a function call to determine if the trial has expired.

public partial class Form1 : Form
    bool hasExpired = true;
    public Form1()
    private void Form1_Load(object sender, EventArgs e)
    private void CheckTrialApp()
        if (hasExpired)
            MessageBox.Show("Trial has expired");

The binary used was compiled on the x86 Release configuration with VS2010 having .NET 4.0 as target framework. The IL Disassembler from VS2010 and a free application called CFF Explorer are used to view and edit the binary.

Read the rest of this post »

Fancy windows previewer

 May 5th, 2010 

 , , ,

Tutorial description

Create a fancy-looking application that displays the preview of the open applications.

Covered topics
  • Enumerating windows and getting various information about them
  • Creating the Aero glass effect
  • Using the DWM windows preview feature
  • Windows Vista/7 with the Aero theme active
  • Visual Studio 2010 (or 2008 but requires some changes in code which are not covered by this tutorial)
Target audienceIntermediate users
DownloadDownload IconTaskSwitcher (13.07 KB)

The basic idea behind this application is the following: upon start, we create snapshot (a list) of all the available windows and we use it to decide what previews to display. Once the list is created, a preview is drawn for each item. There is a drawback for this approach: if new windows are created or some existing are closed the interface will not display them (actually for closed windows will replace the preview with an icon). The advantage: is a simple implementation.

There are three parts for this project.

  1. Enumerating only the open applications’ windows
  2. Make a glass window
  3. Generate a live preview for each window

Enumerating windows

Enumerating all windows can be done with the EnumWindows function from user32.dll which can be easily imported in C#.

private static extern int EnumWindows(EnumWindowsCallbackDelegate callback, int lParam = 0);
private delegate bool EnumWindowsCallbackDelegate(IntPtr hWnd, int lParam);

However, the result of a pure enumeration will return hundreds of windows. The most powerful filtration is to keep just the windows that are visible. Again, a function from user32.dll called IsWindowVisible is used to check whether a hWnd belongs to a visible window. Probably, after this step you will have just 30-40 windows left in the list.

private static extern bool IsWindowVisible(IntPtr hWnd);

The next step is to decide which is the most meaningful representative window from each cluster of windows related by ownership. The Old New Thing blog presents an algorithm for this problem. The logic behind this algorithm is: “For each visible window, walk up its owner chain until you find the root owner. Then walk back down the visible last active popup chain until you find a visible window. If you’re back to where you’re started, then put the window in the Alt+Tab list.” A few Dll imports and the translation of the pseudocode to C# gives the following code.

Read the rest of this post »

Tip #1: Backup Outlook 2007 Accounts’ Information

 Jul 20th, 2009 

 , , , ,

This is a series of different tips and tricks for computer users. It will include: software usage tip, hacks, development tips, hardware tips, etc.

I will try to post tips every day but I don’t know if my schedule will allow me.

When you need to reinstall Windows and/or Outlook you might backup the .pst files (Outlook data files). Unfortunately these files do not contain account information. After reinstall and restore of backup files you need to reenter all information about each account which is a boring process – at least for me because I have 5 e-mail accounts.

If you want to backup accounts information you have to export the “HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook” key from Registry.

Export accounts’ information:

  1. Tip_01_01Start the Registry Editor (Start -> Run -> “regedit”) – in Windows Vista/7 you need administrative rights to start it.
  2. Navigate to the previously mentioned branch (HKEY_CURRENT_USER\Software\ … ).
  3. Right click the “Outlook” tree node.
  4. Choose export.
  5. Name the file accordingly.
  6. Click “Save”

After reinstalling Outlook, you have to import the accounts. Follow the steps below for this:

Import accounts’ information:

  1. Double click the exported file.
  2. Choose “Yes” when asked if you really want to import.

Windows Mobile 6.5 on Toshiba G900

 Jun 3rd, 2009 

 , , , , , , , ,

aboutBefore writing anything else I must warn all readers that changing the operating systems on your mobile will void the warranty. If the upgrade process fails the phone might be damaged and no service will fix that for free. Do it on your own risk and make sure the following list is satisfied:

  • Ask people about the ROM you want to install. Make sure it did not brake any phone.
  • The phone’s battery must be at least 50% charged (better 100%)
  • Make sure you have and UPS. Or a laptop with good battery because if you cancel the process after it started the results might be unexpected.
  • Make sure the USB cable is firmly connect and is not broken!

I cannot be made responsible for any damages caused directly or indirectly by this article.

Read the rest of this post »

Access private data with Reflection

 Feb 15th, 2009 

 , , , ,

This article shows how one of the basic OOP principles – encapsulation – can be violated using reflection.

Let’s assume that we have a simple class with a private field called “someHiddenValue”.

class ClassThatHidesSomething
    private int someHiddenValue = 5;

We want to modify that field from outside the class. This can be done extremely easy through Reflection. First of all we need to get the Type of the ClassThatHidesSomething and get some information about the someHiddenValue field.

Type classThatHidesSomethingType = typeof(ClassThatHidesSomething);
FieldInfo field = classThatHidesSomethingType.GetField(
                         BindingFlags.NonPublic | BindingFlags.Instance);
  • BindingFlags.NonPublic specifies that we want to search in all fields; by default it searches only the public fields – actually here is the trick that violates encapsulation.
  • BindingFlags.Instance specified that we want to search in instance fields also; by default it searches only in static ones.

Now that we have the FieldInfo of that specific field we can do whatever we want with it. Let’s display its value. But first, because the field is an instance field we need an instance of ClassThatHidesSomething.

ClassThatHidesSomething c = new ClassThatHidesSomething();
int hiddenFieldValue = (int)field.GetValue(c);
Console.WriteLine("Hidden field value: {0}", hiddenFieldValue);

Using the same instance c we can set the private field’s value.

field.SetValue(c, 6);

Below you can see the entire code (it is a console application):

Read the rest of this post »

Learn About Azure Services Platform

 Feb 12th, 2009 

 , , , , , , ,

Microsoft provides two ways of learning about Azure Services:

1. Azure Services Traning Kit

The Azure Services Training Kit which includes a comprehensive set of technical content including hands-on labs, presentations, and demos that are designed to help you learn how to use the Azure Services Platform. The February release includes the following updates:

  • 19 demo scripts that walkthrough several of the services
  • 10 presentations covering the entire Azure Services Platform
  • 3 additional hands-on labs for Live Services’

The technical content covers services including: Windows Azure, .NET Services, SQL Services, and Live Services.

It can be downloaded from here.

2. “How Do I?” videos for Azure Services Platform

For Windows Azure:

How Do I: Get Started Developing on Windows Azure?If you’re a developer and you’re new to Windows Azure, start here! You’ll see what you need to download and install, and how to create a simple “Hello World” Windows Azure application.
How Do I: Deploy a Windows Azure Application?In this brief screencast you’ll see what it takes to move your application into the cloud – you’ll see how to request and register a token, how to upload your Windows Azure application and how to move it between staging and production in the cloud.
How Do I: Store Blobs in Windows Azure Storage?In this brief screencast, learn how to leverage Windows Azure storage to store data as blobs. You’ll learn about blob storage, containers and the API that makes it easy to manage everything from managed code.
How Do I: Leverage Queues in Windows Azure?In this screencast, learn how to use queues to facilitate communication between Web and Worker roles in Windows Azure.
Debugging Tips for Windows Azure ApplicationsThe Windows Azure SDK provides a development fabric that provides a “cloud on your desktop.” In this screencast, learn how to debug your Windows Azure applications in this environment.

For .NET Services:

How Do I: Get Started with .NET Services?.NET Services are a set of highly scalable building blocks for programming in the cloud. In this brief screencast, you’ll learn about the registration process, the SDK and the built-in samples – everything you need to know in order to get started.
How Do I: Harness the Microsoft .NET Service Bus?The .NET Service Bus makes it easy to access your Web services no matter where they are. In this brief screencast, you’ll see how to take a basic Windows Communication Foundation (WCF) service and expose it to the Internet with the .NET Service Bus.

For Live Services:

How Do I: Get Started with the Live Framework?If you are looking to get started developing with the Live Framework, this is the place to start! In this screencast you’ll learn how to get a Live Services token and what you need to download in order to start writing Live Framework applications.
How Do I: Use the Microsoft Live Framework Resource Browser?The Live Framework Resource Model is a simple, straightforward information model based on entities, collections and relationships. In this brief screencast you’ll learn how to navigate the relationships between entities by using the Live Framework Resource Browser, which is a tool that ships with the Live Framework SDK.