Archive for the ‘General’ Category

Post

NMock expectations for functions accepting “ref” and “out” arguments

In General on November 17, 2008 by Sid Tagged: , , ,

There appears to be inadequate documentation on setting up expectations in NMock for methods that accept arguments by reference using “out” and “ref” keywords. Here is a quick note to give an example demonstrating how it can be done.

Consider the following interface:

public interface IFoo
{
void Bar(out int a, ref int b);
}

“Bar” method takes one “out” parameter and another “ref” parameter.

To start mocking “IFoo” you would obviously first create a new mock object implementing interface “IFoo”.

IFoo aFoo = mocks.NewMock< IFoo >();

We store it in a variable named “aFoo”.

Here’s how you would set up an expectation to ask NMock to expect a call to method “Bar” on “aFoo” object with an “out” parameter and a “ref” parameter with 2 as its value.

Expect.Once.On(aFoo)
.Method(“Bar”).With(Is.Out, 2)
.Will(new SetNamedParameterAction(“a”, 10),
new SetNamedParameterAction(“b”, 20));

The actions specified in the “Will” part cause the “out” and “ref” parameters to be set to values 10 and 20 respectively after “Bar” is called on “aFoo”.

int a, b = 2;
aFoo.Bar(out a, ref b);

// At this point “a” will be set to 10 and “b” will be set to 20 because
// of the expectation specified above.

Hope this helps.

Post

Automating windows forms UI testing

In .NET, General, Tech/Hacks on November 6, 2008 by Sid Tagged: , ,

If you have been blessed with a windows-forms application that has business-logic invading the user-interface, I have something that’ll help you. The most practical approach in this situation is to rearchitect the business layer and switch the UI over in a piecemeal fashion. While you’re doing this, automated testing of the user-interface will make your job a lot faster compared to manual testing.

For the purpose of this article let us consider a simple Windows Forms application (download link below). The application allows the user to provide two inputs and then either add them or subtract them. Simple, right?

The application
screenshot

Here’s the code for the event-handlers of interest to us:

private void MainForm_Load(object sender, EventArgs e)
{
this.lblAnswer.Text = “0″;
}

private void btnAdd_Click(object sender, EventArgs e)
{
this.lblAnswer.Text = Convert.ToString(this.numericUpDown1.Value + this.numericUpDown2.Value);
}

private void btnSubtract_Click(object sender, EventArgs e)
{
this.lblAnswer.Text = Convert.ToString(this.numericUpDown1.Value – this.numericUpDown2.Value);
}

The handler for the load event of the form just sets the answer label to display “0”. The handler for the click event of each of the buttons retrieves the selected values from the numeric drop-downs, applies the appropriate operation, and writes the result into the label.

The tests

In order to write tests for this application, you can start by right-clicking on the class of the form (in this case MainForm), and selecting “Create Unit Tests…”. Hit “OK” on the dialog that pops up to create unit-tests in a separate project. Another dialog will pop up asking for the name of the test project. Just hit “Create”.

This will cause Visual Studio to do some heavy lifting for us and generate accessors to allow us to call methods and properties defined on MainForm, from our tests. We don’t have to write code for accessors using the Reflection API ourselves – so this is extremely cool. Doing it on our own is quite painful (proof).

Delete all the tests marked with the TestMethod attribute in the generated class because we’re going to write our own.

The first one is pretty simple. We expect the answer label to display a “0” when the form is initially loaded – so let’s test that.

///


///A test for MainForm_Load
///

[TestMethod()]
[DeploymentItem("AppUnderTest1.exe")]
public void MainForm_LoadTest()
{
MainForm_Accessor target = new MainForm_Accessor();
target.MainForm_Load(null, null);
Assert.AreEqual(“0″, target.lblAnswer.Text, “Initial answer is zero”);
}

Notice that we can call MainForm_Load directly (no ConstructorInfo, MethodInfo – reflection stuff required).

Once that’s done we can just check the text displayed in the answer label and make sure it is “0”.

We can take the same approach to call the click event handlers of the buttons and check the results for addition/subtraction.

Since there are various cases to test, I have a separate function GetTestTable that returns a two dimensional array where each row contains the two test-inputs, result of subtraction, and result of addition – in that order.

public int[,] GetTestTable()
{
// Format of each row:
// A, B, (A-B), (A+B)
int[,] table =
{
{0, 0, 0, 0},
{10, 0, 10, 10},
{0, 10, -10, 10},
{-10, 0, -10, -10},
{0, -10, +10, -10},
{10, 10, 0, 20},
{-10, -10, 0, -20},
{-10, 10, -20, 0},
{10, -10, 20, 0}
};
return table;
}

Following is the function that actually does the testing. We basically process each row returned by GetTestTable one by one. First we set the two inputs on the numeric drop-downs. Next we call the click event-handlers of both buttons verifying what is in the answer label against what we expect. Again notice that we can directly invoke the event handlers and even access properties of the answer label (lblAnswer).

///


///A test for btnSubtract_Click
///

[TestMethod()]
[DeploymentItem("AppUnderTest1.exe")]
public void AddSubtractTest()
{
MainForm_Accessor target = new MainForm_Accessor();

int[,] table = this.GetTestTable();

for (int i = 0; i < table.GetUpperBound(0); i++)
{
int a = table[i, 0],
b = table[i, 1],
subtract = table[i, 2],
add = table[i, 3];

target.numericUpDown1.Value = a;
target.numericUpDown2.Value = b;

target.btnSubtract_Click(null, null);
int result = Convert.ToInt32(target.lblAnswer.Text);
Assert.AreEqual(subtract, result, String.Format(“Subtract {0} and {1}”, a, b));

target.btnAdd_Click(null, null);
result = Convert.ToInt32(target.lblAnswer.Text);
Assert.AreEqual(add, result, String.Format(“Add {0} and {1}”, a, b));
}
}

To run these tests, select Test->Run->All Tests in Solution from the main-menu in Visual Studio. The “Test Results” window in Visual Studio should show that all tests passed.

Summary

There’re multiple ways to go about automating UI testing. You could use an automated testing tool like Mercury Quick Test. However if you want to take things into your own hands and take advantage of greater control, you could write your tests using NUnit or MS-Test and make PInvoke calls to send messages to various controls in the UI of your application under test. You could use the SendKey API in Windows.Forms too.

However if you want to take advantage of knowledge of the internals of the application under test, we have to use Reflection to set properties of the controls, invoke event handlers, call other methods and then test whether this resulted in the changes that we expected. This makes the job extremely painful. I hope this article shows how much easier it is if we leverage Visual Studio Team System to generate accessors for us.

I don’t see why the technique described above cannot be used to test WPF and Silverlight applications as well.

Download
Click here to download the code accompanying this article.

Post

Automatic properties with custom logic

In General, Tech/Hacks on October 24, 2008 by Sid Tagged: , , ,

There should be a compiler supported way in C# to declare a property with custom getter/setter logic without having to explicitly declare a backing field. In the absence of such a feature, if you want to have custom getter/setter logic you have to ditch automatic properties, declare a backing field explicitly and then there’s nothing stopping a future programmer from assigning directly to the backing field and the custom getter/setter logic not getting executed probably leading to bugs.

Update:Check out part 2 where I take an example to bring the problem into perspective and propose a solution…

Post

What you should do…

In General, Tech/Hacks on May 1, 2008 by Sid Tagged: ,

I am fortunate enough to work with a couple of great individuals. Recently I was able to hypnotize persuade them into discussing things which should and shouldn’t be done in a software project :)

I am absolutely sure that the discussion will help me in the future (and them). However I thought the merged list is generic enough to help anyone, and hence this post.

In the beginning…

  • Before you start on a project, follow up with your managers and ensure that a detailed feasibility analysis has been done. This should include business planning, market analysis, and of course technology investigation to identify major road-blocks that are likely to be encountered in the future. For the technical analysis, you must involve the person who is going to actually write most of the code later on – because he’s the only one who’s most likely to consider all the possible issues.
  • Involve engineers during requirement gathering phase. If possible, ask each of them to take a good look at a system of other competitors and report back with their findings. This will help the Product Manager in that there’s a better guarantee of the surface area of features being covered. The other bigger benefit is that the engineers would have a much clearer idea of the sort of product they’re supposed to build without having to read hundreds of pages in the requirements documents. This will also make them, I believe, more receptive to changes made in the requirements later on as they’ll have a better picture of the landscape. Being receptive to changes is very important.
  • Identify major fears and unknowns that can negatively affect the outcome of a project. Make a proactive effort to address them at the start of the project.
  • Make responsibilities of all individuals involved in the project clear for accountability. Assign roles to them appropriately.
  • There should be a designated Project Manager whose role should be to maintain timelines, and escalate issues up to and from senior management. Asking a person in another role to also perform as a PM might not be effective always.

Day to day…

  • Obtain sign-off for technical decisions and have a general plan for proceeding if a sign-off is not made within a specific amount of time.
  • Daily standup meetings help a lot in keeping every one up to date on status and outstanding issues. There’s a lot to be learned from body language which might otherwise be lost in other forms of communication. However it is important to keep the meetings short – 10 to 15 minutes. There’s lots of literature about how the meetings should and shouldn’t be done. I’ll just say that you need to try out different things and pick the one which works best with the personalities of the individuals in the team.

In the meetings…

  • Long weekly meetings drain the energy out of people and consequently the project. While I have my doubts on whether people pay attention after 45 minutes on average, I have even stronger doubts on the effectiveness of the meetings that go on for more than 2 hours. There might be exceptions of course, and I’d be interested in knowing what they did differently.
  • After the weekly meeting, ensure that the meeting minutes are sent out describing each item discussed in the agenda along with the decisions made, open issues, and action items (assigning a person responsible).
  • Be on time in meetings. Try to attend the meetings physically instead of over phone.
  • Try to avoid taking calls on your cell phones during meetings – especially when you are actively involved in a discussion.
  • Making decisions based on consensus is not always effective. Making decisions without considering inputs from others is equally bad.

When conducting code / design / UI reviews…

  • If the process is to do design / code reviews in the meetings, to make the review more effective, try to restrict the number of attendees to the minimum absolutely necessary. Assigning reviewers to subsystems, if possible, might help in this regard.
  • When performing a code review ensure that you enforce the positive aspects of the code, while identifying the aspects that need improvement. Too many details are bad; only give as many specifics as you think are needed to send the developer whose code is being reviewed forward in the right direction. When performing a review, pay attention and make an honest effort to understand the problem being posed to you.

When your code / design / UI is being reviewed by someone…

  • When asking someone for a code / design review, make a dedicated effort to get their feedback. This might require you to spend an hour preparing a sample application to demonstrate the problem, but the time spent in it would be worth the effort. Be open to feedback. Negative feedback is still better than no feedback at all.

In general…

  • Do not shoot down ideas point blank. This erodes the enthusiasm of the contributors which is very difficult to get back. Make sure you identify the positive aspects of every idea.
  • Do not be afraid to hire temporary contractors and subject matter experts if required. That’s why a feasibility analysis is important.
  • When involving new people in a project, ensure that they have received adequate training on other internal products and frameworks as required.
  • If you’re required to use a common piece of code, ensure that it has an adequate test-bed. Secondly, push for dedicating engineering resources for their maintenance, depending of course on the size of the common code. If there aren’t any developers accountable for the upkeep of the common piece of code, you’re likely to lose the confidence of the developers who’re supposed to use it.

But most importantly…

  • Work to a level where you can be proud of your contributions tomorrow. In the end, that’s all that matters.

Post

Two (useless but potentially) interesting tid-bits

In .NET, General, Tech/Hacks on April 29, 2008 by Sid Tagged: , ,

Try-Catch-Finally

A try-catch-finally is converted into IL by the C# compiler as a try-catch inside the try block of another try-finally. This allows for finally block to execute even when exceptions are raised in the catch block. Use ildasm and check it out yourself!

throw football;

Though you cannot throw an arbitrary managed object as “throw myObj” (you’ll get a compilation error), you can modify the generated IL to do so. However your catch block will actually receive a RuntimeWrappedException in these scenarios. Why is this allowed? Well, unlike C#, it is legal to throw arbitrary objects in managed C++ and in those cases a RuntimeWrappedException is thrown too.

Post

C# compiler optimizations and empty “try” block

In General, Tech/Hacks on April 28, 2008 by Sid Tagged: , ,

There is some misinformation you’re likely to stumble upon via Google when searching for “C# compiler /optimize+”. Interestingly, the following snippet can be seen on various forums.

The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.

The part in bold is incorrect.

Before I dive into a simple app that I wrote to prove that the information is incorrect, there’s a simple logical reasoning to refute the claim. Basically, a function that has had a try/finally block completely removed because of an empty try or finally will behave completely differently than one who hasn’t. Optimizing something doesn’t mean you stop doing important things to save some time :)

“We get rid of try-finally with an empty try”. Do they really?

For those who still aren’t convinced with the explanation above, I wrote a simple C# class and saved it in a file Test.cs. I compiled the code once from the command line without optimizations (“csc test.cs”) and once with optimizations (“csc /optimize+ test.cs”).

Here’s what Foo looked like in C#:

private void Foo()
{
int x;
try
{
}
finally
{
DoSomething();
DoSomethingElse();
}
}

Nothing much there… Just an unused variable “x”, an empty try, and some code in the finally block.

Here’s the IL without optimizations:

.method private hidebysig static void Foo() cil managed
{
// Code size 22 (0×16)
.maxstack 0
.locals init (int32 V_0) // Here’s our unused variable.
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_0014
} // end .try
finally
{
IL_0005: nop
IL_0006: call void Test::DoSomething()
IL_000b: nop
IL_000c: call void Test::DoSomethingElse()
IL_0011: nop
IL_0012: nop
IL_0013: endfinally
} // end handler
IL_0014: nop
IL_0015: ret
} // end of method Test::Foo

Here’s the IL with optimizations:

.method private hidebysig static void Foo() cil managed
{
// Code size 14 (0xe)
.maxstack 0
.try
{
IL_0000: leave.s IL_000d
} // end .try
finally
{
IL_0002: call void Test::DoSomething()
IL_0007: call void Test::DoSomethingElse()
IL_000c: endfinally
} // end handler
IL_000d: ret
} // end of method Test::Foo

As you can see:

  • The compiler got rid of the unused variable when optimizations were enabled
      Notice that the following declaration doesn’t appear in the second IL listing while it does in the first one:

      .locals init (int32 V_0)

  • Try / Finally is still there

If you’re still questioning why you would have a try/finally with an empty “try” in the first place, you might find an earlier article of mine interesting.

Hope this helps someone in an interview or something :)

Post

Make a file empty

In General on April 26, 2008 by Sid

Found someone using Google to figure out how to clear out the contents of a file and hitting my blog. Well, it’s pretty easy – use FileMode.Truncate when opening the file.

using (FileStream fs = File.Open(filepath, FileMode.Truncate, FileAccess.Write))
{
// Code to write to the file goes here
fs.Close();
}

Post

Which one is faster – FileStream.Position or FileStream.Seek?

In General on April 26, 2008 by Sid

FileStream.Position property is implemented in terms of File.Seek (essentially File.Seek(value, SeekOrigin.Begin)). Consequently setting the location of the virtual file-pointer by calling Seek directly instead of calling Position results in slightly faster execution speed. Seek is also better because it has more options.

Post

Switch vs if-else-if

In General on April 24, 2008 by Sid

This is an academic question. Which one is better?

private string Foo(int value)
{
string result;

switch (value)
{
case 10:
result = “something 1″;
break;
case 110:
result = “something 2″;
break;
case 150:
result = “something 3″;
break;
case 210:
result = “something 4″;
break;
default:
result = string.Empty;
break;
}

return result;
}

or

private string Bar(int value)
{
string result;

if (value == 10)
result = “something 1″;
else if (value == 110)
result = “something 2″;
else if (value == 150)
result = “something 3″;
else if (value == 210)
result = “something 4″;
else
result = String.Empty;
return result;

}

Even though both Foo and Bar do the same thing, Foo is better performance wise.

The compiler converts Foo into IL which roughly achieves the same thing as the following pseudo-code.

if value < 110 then
if value == 10 then
result = “something 1″
else
goto default_case
else
if value == 110 then
result = “something 2″
else if value == 150 then
result = “something 3″
else if value == 210 then
result = “something 4″
else
default_case:
result = String.Empty
end if

Foo when converted to IL splits the search space with 110 in the middle which reduces the number of comparisons needed. As a result Foo will be faster than Bar. However, I wouldn’t advise you to worry about performance at this scale. As I said in the beginning, this question was only academic :)

Post

Switch is just If-Else-If

In .NET, General, Tech/Hacks on April 24, 2008 by Sid Tagged: , ,

In an internal meeting of a bunch of developers at my current company, someone made the assertion that the Switch statement in C# (or Select Case in VB.NET) is just a compiler short-cut for writing a chain of If-Then-Else statements.

What do you think? Is that statement – true or false?

Take the following C# function for example:

public string DoSomething(char c)
{
switch (Char.ToLower(c))
{
case ‘e’:
case ‘g’:
case ‘k’:
return “something 1″;
case ‘a’:
case ‘d’:
case ‘h’:
case ‘r’:
return “something 2″;
case ‘p’:
case ‘i’:
case ‘l’:
return “something 3″;
default:
return “something default”;
}
}

One of the ways to deal with the switch statement is for the compiler to treat the above switch statement as a sequence of If-then-else clauses, like so:

char lowerC = Char.ToLower(c);
if (lowerC == ‘e’ || lowerC == ‘g’ || lowerC == ‘k’ )
return “something 1″;
else if (lowerC == ‘a’ || lowerC == ‘d’ || lowerC == ‘h’ || lowerC == ‘r’ )
return “something 2″;
else if (lowerC == ‘p’ || lowerC == ‘i’ || lowerC == ‘l’ )
return “something 3″;
else
return “something default”;

But, if you think about it, there’s a better way…

One can do better by having a lookup table to map each character that you can possibly see, to the address of the corresponding instruction which should be executed when that character is seen. With a lookup table like that, when you see ‘p’ for example, there’s no need to compare it against ‘e’, ‘g’, ‘k’… and all the other characters in the cases that preceded it in the switch statement. As a result, your code will be faster.

There’s a “switch” statement at the IL level which implements the jump-table concept. The generated IL for DoSomething looks like the following:

.method public hidebysig instance string
DoSomething(char c) cil managed
{
// Code size 125 (0×7d)
.maxstack 2
.locals init ([0] string CS$1$0000,
[1] char CS$4$0001)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: call char [mscorlib]System.Char::ToLower(char)
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.s 97
IL_000b: sub
IL_000c: switch (
IL_0063,
IL_0073,
IL_0073,
IL_0063,
IL_005b,
IL_0073,
IL_005b,
IL_0063,
IL_006b,
IL_0073,
IL_005b,
IL_006b,
IL_0073,
IL_0073,
IL_0073,
IL_006b,
IL_0073,
IL_0063)
IL_0059: br.s IL_0073
IL_005b: ldstr “something 1″
IL_0060: stloc.0
IL_0061: br.s IL_007b
IL_0063: ldstr “something 2″
IL_0068: stloc.0
IL_0069: br.s IL_007b
IL_006b: ldstr “something 3″
IL_0070: stloc.0
IL_0071: br.s IL_007b
IL_0073: ldstr “something default”
IL_0078: stloc.0
IL_0079: br.s IL_007b
IL_007b: ldloc.0
IL_007c: ret
}

Here’s what the compiler generated code to do:

  • The ordinal value of ‘a’ (i.e. 97) is subtracted from the character passed to the function.
  • As a result for characters between ‘a’ and ‘r’, you’d see values between 0 and 17 (both included).
  • For each value between 0 and 17, the compiler then specified the label of the instruction that the execution should jump to, in the IL switch statement.
  • Notice IL_0059: if the value does not lie between 0 and 17, code has been generated to directly jump execution to IL_0073 and we get ready to return “something default”.

Sweet, isn’t it?

Does the compiler always handle “switch” this way?

Nope. If the range of the values specified in the case clauses is large, creating a table as explained previously, will cause wastage of memory. So a function like the following won’t be utilizing the IL “switch” statement and will be treated like a sequence of “if-then-else” statements. However, for efficiency, the order of comparisons might be different from the order in which “case” clauses were specified in your code (more info).

public string DoSomethingElse(int bla)
{
switch (bla)
{
case 10:
case 45:
case 99:
return “something 1″;
case 21:
case 1091:
return “something 2″;
case 2048:
case 256:
case 1072:
return “something 3″;
default:
return “something default”;
}
}

Here’s a link to an article that presents some findings from comparing execution speed of “switch” against “if-else-if”. But like I said earlier, this qualifies as micro-optimization and there’re most probably other things in your code you should be worrying about.