Category Archives: .net

C# lists: add some elegance to your code

It is a fairly common programming scenario to find ourselves with a list of identical objects. In the past, without adequate support from programming languages, we found ourselves writing a lot of searching and sorting code, and that may have put you off using lists in favour of arrays. All that has changed with C# (particularly 2.0) – its implementation of a list makes handling such lists remarkably easy.

For example, given the following class Person:

[code lang=”C#”]
public class Person
{
public int age;
public string name;

public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}
[/code]

We can create a list of Person objects and add six people like so:

[code lang=”C#”]
Listpeople = new List();

people.Add(new Person(50, “Fred”));
people.Add(new Person(30, “John”));
people.Add(new Person(26, “Andrew”));
people.Add(new Person(24, “Xavier”));
people.Add(new Person(5, “Mark”));
people.Add(new Person(6, “Cameron”));
[/code]

C#’s list mechanism provides us with a number of useful methods. Personally, I find ForEach, FindAll and Sort to be very useful. ForEach allows us access to each item in the list. FindAll allows us to search for objects in the list that match a specific condition. Sort allows us to sort the objects in the list. The following code demonstrates how we might use each of these methods:

[code lang=”C#”]

Console.WriteLine(“Unsorted list”);

people.ForEach(delegate(Person p)
{ Console.WriteLine(String.Format(“{0} {1}”, p.age, p.name)); });

// Find the young
List young = people.FindAll(delegate(Person p) { return p.age < 25; }); Console.WriteLine("Age is less than 25"); young.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); }); // Sort by name Console.WriteLine("Sorted list, by name"); people.Sort(delegate(Person p1, Person p2) { return p1.name.CompareTo(p2.name); }); people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); }); // Sort by age Console.WriteLine("Sorted list, by age"); people.Sort(delegate(Person p1, Person p2) { return p1.age.CompareTo(p2.age); }); people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); }); [/code] And here is the output that we should expect: Unsorted list
50 Fred
30 John
26 Andrew
24 Xavier
5 Mark
6 Cameron

Age is less than 25
24 Xavier
5 Mark
6 Cameron

Sorted list, by name
26 Andrew
6 Cameron
50 Fred
30 John
5 Mark
24 Xavier

Sorted list, by age
5 Mark
6 Cameron
24 Xavier
26 Andrew
30 John
50 Fred

Lists are powerful and result in fewer, and more elegant, lines of code. Hopefully this short example has demonstrated their ease and you will find yourself using them in your day-to-day development activities.

DDD3 – Session voting opens

ddd3.gif

I am pleased to announce that you may now vote for those sessions that you would like to see on the DeveloperDeveloperDeveloper 3 agenda!

There’s a great line up of speakers available to choose from – some of whom are travelling from further afield to be here! And it sees the return of some familiar speakers, such as Steve Scott.

I have submitted a session, Unit Testing and Code Coverage: Putting it all together, here’s the abstract:

With Test-Driven Development (TDD) now entering the mainstream via such tools as NUnit and more recently Visual Studio 2005 Team System (VSTS), you may be wondering how to “get more” from TDD. I believe that we can improve the quality of our application by using a combination of TDD and code coverage.

Code coverage, whereby we “track” how much of our code is covered during testing, is not new. Indeed, we can practice code coverage and TDD in isolation. However, applying what we know about code coverage against our unit tests allows us to move our applications to the next “quality” level:
no longer is it acceptable to have unit tests on their own, we must know how well written the unit tests are, how much of the classes under test are really being tested?

Over the course of 60 minutes I will introduce the benefits of code coverage using both manual methods and automated tools. I will briefly introduce TDD and will go on to demonstrate the benefits of using code coverage tools against your unit tests, i.e. how well do your tests exercise your classes/application?

Whilst I will be using Visual Studio 2005 and C#, I will discuss Visual Studio 2003 compatibility too. I will be looking at a handful of the code coverage tools that are available, both free and commercial.

If you would like to see this session, please vote for it! And if there’s anything you would like me to cover in this session, please feel free to send me an e-mail or leave a comment here!

Shutting down a PC using WMI and C#

I found myself needing to re-work some code that was originally part of my WMI presentation from 2003.

After a little bit of re-writing and a little bit of searching, I re-wrote my original Delphi routine, which looked like this:

[code lang=”Pascal”]
[Delphi]
procedure TfrmMain.btnShutdownClick(Sender: TObject);
var
wmiLocator: TSWbemLocator;
wmiServices: ISWbemServices;
wmiObjectSet: ISWbemObjectSet;
wmiObject: ISWbemObject;
Enum: IEnumVariant;
ovVar: OleVariant;
lwValue: LongWord;

begin
wmiLocator := TSWbemLocator.Create(self);
wmiServices := wmiLocator.ConnectServer( edtComputer.Text, ‘root\cimv2’, edtUser.Text, edtPass.Text, ”, ”, 0, nil);

wmiServices.Security_.Privileges.Add(wbemPrivilegeShutdown, True);
wmiObjectSet := wmiServices.ExecQuery(‘SELECT * FROM Win32_OperatingSystem WHERE Primary=True’, ‘WQL’, wbemFlagReturnImmediately, nil);
Enum := (wmiObjectSet._NewEnum) as IEnumVariant;
while (Enum.Next(1, ovVar, lwValue) = S_OK) do begin
wmiObject := IUnknown(ovVar) as SWBemObject;
wmiObject.ExecMethod_(‘Shutdown’, nil, 0, nil);
end;

wmiLocator.Free;
end;
[/code]

…it now looks like this:

[code lang=”C’#”]
[C#]
using System.Management;

public enum ShutDown
{
LogOff = 0,
Shutdown = 1,
Reboot = 2,
ForcedLogOff = 4,
ForcedShutdown = 5,
ForcedReboot = 6,
PowerOff = 8,
ForcedPowerOff = 12
}

ManagementClass W32_OS = new ManagementClass(“Win32_OperatingSystem”);
ManagementBaseObject inParams, outParams;
int result;

W32_OS.Scope.Options.EnablePrivileges = true;
foreach(ManagementObject obj in W32_OS.GetInstances())
{
inParams = obj.GetMethodParameters(“Win32Shutdown”);
inParams[“Flags”] = ForcedShutdown;
inParams[“Reserved”] = 0;

outParams = obj.InvokeMethod(“Win32Shutdown”, inParams, null);
result = Convert.ToInt32(outParams[“returnValue”]);
if (result !=0) throw new Win32Exception(result);
}
[/code]

Here’s a link to more information about this on the MSDN.

[job for tonight – sort out this code format…once and for all]

Automated Code Coverage and Unit Tests

How well have your tests exercised your code?

Over the course of this posting I plan to demonstrate a number of tools and topics that encompass “testing”. I’ll be looking at code coverage – how much of our code is “exercised” or used. I’ll be looking at tools that can help us with code coverage. I’ll focus on using NUnit for testing and will demonstrate how we can tie it into the code coverage activity. Finally, I’ll be looking how we can integrate all of this good stuff into the Visual Studio IDE…using TestDriven.NET.

With that in mind, I will go through the following:

  1. The creation of a simple class that does something trivial, in this case a calculator (Visual Studio, C#)
  2. The creation of a simple front-end application that uses the calculator (Visual Studio, C#)
  3. An examination of code coverage using the front-end application (NCover and NCoverExplorer)
  4. An examination of code coverage using unit tests (NUnit)

These four topics will demonstrate two things. Firstly, the benefit of using a code coverage tool to help you learn more about your application and the way that it works. Secondly, how that added benefit of a set of unit tests coupled with a code coverage tool can yield increased levels of confidence in your application’s testing strategy. Of course, prior to code coverage tools being automated, the simplest form of code coverage was the debugger: even as recently as 1998 I recall laboriously slaving over the Delphi debugger whilst I was “testing” my application. It was worth the toil, the few additional bugs that came to light meant that the application had years of trouble free use. Now, with code coverage integrated into the IDE, and with unit tests sitting side-by-side with the application source code, the time required to run the tests and perform a code coverage analysis is so short, it can be done with every build.

TestDriven.NET
TestDriven.NET provides an integration layer between a number of testing frameworks, such as NUnit, and the IDE. Before TestDriven.NET, we would write our tests, write some code, build everything and then we would fire up a separate application that would run the tests (e.g. the NUnit front-end). Generally this is/was fine as the benefits of test execution greatly outweighed the use of a secondary application. Whilst the NUnit front-end allows us to choose which tests we want to run (as opposed to running all tests), we still find ourselves leaving the IDE and jumping into another application.

So, in addition to integrating NUnit into the Visual Studio IDE, it also provides integration with NCover and NCoverExplorer.

Code Coverage
For the purposes of this posting, I am going to do and explain things in a slightly “out of order” fashion. I know that I have mentioned test-driven development already, and by rights we should be developing our application in that fashion. However, I would like to introduce code coverage first. Luckily the example that I plan to use is so simple, it could almost be tested without the need for test-driven development. The example that I plan to use to demonstrate code coverage is that of a simple calculator – I could have been more original, I apologise for my banality!

The Calculator Class
Implementing a simple calculator isn’t rocket science, but since I need you to be at least familiar with the code layout, here’s the code that I am using:

test1

Here’s a little front-end WinForms application that makes use of [some] the MyCalculator class.

test3

And here’s the code behind the WinForms application and the “add” button:

test8

So, having compiled CalcApp, we can submit the .exe to NCover. Before we do that, it’s probably useful if I introduce NCover.

What is NCover?
NCover is a command-line tool that scans your application’s code and records information about which lines of code were executed. NCover uses the “sequence points” that the compiler generates and stores in the .pdb file (debug information) to determine which lines of code are executed and how frequently. Without getting bogged down in detail, a sequence point is essentially a single program state or a line of code.

NCover’s command-line syntax is:

Usage: NCover /c [/a ]

/c Command line to launch profiled application.
/a List of assemblies to profile. i.e. "MyAssembly1;MyAssembly2"
/v Enable verbose logging (show instrumented code)

After NCover has analysed your code, it creates two files: coverage.log and coverage.xml.. The .log file contains the events and messages that NCover creates as it analyses your code base. The .xml file is very it all happens: it contains NCover’s analysis of your code base. There is a third file, coverage.xsl. It’s an XSL stylesheet that takes coverage.xml as its input, allowing it to be displayed in a neat tabular fashion inside Internet Explorer.

Running CalcApp through NCover
NCover’s output:

C:\Program Files\NCover>NCOVER.CONSOLE "...\dev\VS2005\Test\DDG\CalcApp\CalcApp\bin\Debug\CalcApp.exe"
NCover.Console v1.5.4 - Code Coverage Analysis for .NET - http://ncover.org
Copyright (c) 2004-2005 Peter Waldschmidt

Command: ...\dev\VS2005\Test\DDG\Calc
App\CalcApp\bin\Debug\CalcApp.exe
Command Args:
Working Directory:
Assemblies:
Coverage Xml: Coverage.Xml
Coverage Log: Coverage.Log

Waiting for profiled application to connect...
******************* Program Output *******************
***************** End Program Output *****************

Alternatively, with TestDriven.NET installed, there is the IDE menu integration:

test7

It’s important to note that the Coverage menu option is context sensitive. Depending upon “where” you right click, say either on the CalcApp solution or the TestLibrary, NCover will be invoked for the item you right clicked on. We will see this difference emerge later on in this posting when we demonstrate the difference between code coverage for CalcApp vs. code coverage for our NUnit tests.

Now, you may recall that I only implemented the “add” calculation. This is deliberate as I need to use the missing calculations to demonstrate code coverage.

Coverage.xml is too large to reprint here and it’s not all that easy to read. Fortunately, NCover’s author realised this and created an XSL (stylesheet) that transforms the XML into something a) more readable and b) more useful. The screenshot below presents a snapshot of that output – notice the green bars and red bars, we’re clearly in the ‘testing’ domain now. The full NCover coverage.xml file can be viewed here.

test10

From this report, we can easily see that we’ve only covered 25% of the MyCalculator class. However, and this is a key point, in order to get this far, we had to perform manual testing. We had run the application “through NCover” such that it could watch what was happening. We had to enter the number 38 and 4 and we had to move the mouse and click on the Add button. Whilst this is a better than stepping though code with the debugger, it’s not automated therefore it’s not repeatable.

NCover’s report looks great and it serves a good purpose. NCoverExplorer moves things to the next level, it takes the output from NCover and presents it graphically in a treeview with integrated code viewing:

test4

NCoverExplorer uses colour-coding to highlight the status of code coverage. It is configurable as the screenshot below demonstrates:

test9

Introducing unit tests with NUnit
Without going into too much detail about test-driven development and NUnit (further information can be found in the Resources section of this post), our next step is to prepare a new class that allows us to test the MyCalculator class. In reality, we would have written our tests before writing the MyCalculator class, we’re doing things in a slightly different order for the sake of this post.

So, using Visual Studio we simply add a new Class Library to our solution, add a reference to the ClassUnderTest namespace and we’re off. The following code demonstrates how we might use the NUnit testing framework to exercise MyCalculator. Whilst not an NUnit requirement, I prefer to name my test methods with the prefix “test”, other unit testing frameworks may vary. As you can see, we’re simply recreating the manual test that we performed using the desktop application and we’re still only testing the “add” method.

test2

Inviting NUnit to run these tests, in the absence of TestDriven.NET, would mean leaving the IDE. However, with TestDriven.NET, we can right click on the TestLibrary and run the tests using NUnit. The screenshot below presents the output from the NUnit front-end. It clearly demonstrates that the test for addition succeeded and with that we gain the confidence that “everything’s working”. However, what it doesn’t tell us is the fact that we’ve missed out testing some 75% of the MyCalculator class. For that, we need to use NCover on our tests.

test11

Here’s a screenshot of NCoverExplorer viewing NCover’s Coverage.xml after it has analysed the tests:

test5

The key takeaway from this screenshot, and indeed this posting, is the fact that we have automated our test and our code coverage: we can see in a single screenshot how well our tests are exercising our code.

I discovered NCover and NCoverExplorer via a couple of blog posts and was suitably impressed – I am always on the look out for ways of ensuring that my applications are as well tested as they can be. After all, there is nothing worse than a stream of ‘phone calls from your users each complaining about a show stopping crash or feature that does not appear to work. With careful use of the tools mentioned above, we can get ensure that our applications are tested and that we have no code that is unused. Code that is unused is often the source of bugs or feature failures. In the past, without tests and without code coverage tools, we had to resort to using a debugger to test all paths through our code – that was a laborious process fraught with repetition and boredom.

My recommendation: install NCover, install NCoverExplorer, install NUnit, install TestDriven.NET.

Further Reading
TestDriven.NET
TestDriven.NET Google Group
NUnit
MbUnit
Microsoft Team System
Peter Waldschmidt.’s NCover
NCoverExplorer
NCoverExplorer FAQ

DotNet Developers Group articles:
Test-Driven Development: a practical guide, Nov/Dec 2003
Test-Driven Development Using csUnit in C#Builder, Jan/Feb 2004

Using LDAP to locate a user name

I found myself needing to extract the current user’s full name from our Active Directory today. For a variety of reasons, I’ve not done too much work in this area, so I had to hunt around for a few minutes before arriving at a solution.

Firstly, I had to add a reference to System.DirectoryServices to my project – no problem, right click on the References node in Visual Studio and choose Add Reference. Secondly, I had to add using System.DirectoryServices to my source code.

Anyway, here’s the C# code that I used – note the use of the UserName property from the Environment class.

using System.DirectoryServices;
...
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://dc=DOMAIN_CONTEXT,dc=com");
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = "(&(objectCategory=person)(sAMAccountName=" + Environment.UserName + "))";
DirectoryEntry result = directorySearcher.FindOne().GetDirectoryEntry();

string name = result.Properties["displayName"].Value.ToString();

In my case, the username CMurphy became Craig Murphy (displayName). Your properties may vary, and you’ll need to know your own domain context (dc).

Creating SWF movies in Delphi

I reviewed Delphi+Flash for The Delphi Magazine: it’s a great product and is especially useful if you need to add animation to your application.

Merry Xmas

Here are a couple of sample animations:

Example SWF 1
Example SWF 2

And some sample code:


var Movie: TFlashMovie;
label1, label2, label3, label4: TSWFOffsetMarker;
EA: TSWFExportAssets;
begin
Movie := TFlashMovie.Create(0, 0, 400 * twips, 200 * twips, 20);
Movie.Version := 6;
Movie.SystemCoord := scPix;

Movie.AddRectangle(0, 0, 400, 300).SetLinearGradient(SWFRGBA($663300), SWFRGBA($CCFF99), 270);
Movie.PlaceObject(Movie.Shapes[0], 1);
Movie.BackgroundColor.RGB := SWFRGB(0,0,0);

{ Text }
Movie.AddFont(Font, false);
With Movie.Fonts[0] do
begin
Size := 2 * twips;
Name := 'Times New Roman';
Bold := true;
end;
Movie.AddText('The Delphi Magazine', cswfWhite, Movie.Fonts[0], Point(0, 100), taRight);
Movie.AddSprite;
With Movie.Sprites[0] do
begin
PlaceObject(Movie.Texts[0], 10);
with PlaceObject(Movie.Texts[0], 9) do
begin
SetTranslate(2, 2);
InitColorTransform(true, -$FF, -$FF, -$FF, -150, false, 0, 0, 0, 0, true);
end;
end;
Movie.PlaceObject(Movie.Sprites[0], 10000).SetTranslate(395, 0);

{ one snow }
Movie.AddStar(0, 0, 3, -3, 4).SetSolidColor(SWFRGBA($EE, $EE, $FF, $DD));

Movie.AddSprite;
With Movie.Sprites[1] do
begin
PlaceObject(Movie.Shapes[1], 1);
With FrameActions do
begin
ConstantPool(['this', '_x', '_y', 'ZielX', 'ZielY']);
Push([400, 0], [vtInteger, vtConstant8]);
GetVariable;
Push([1], [vtConstant8]);
GetMember;
Less2;
_Not;
label1 := _If.BranchOffsetMarker;
PushConstant(0);
GetVariable;
Push([1, 10], [vtConstant8, vtInteger]);
SetMember;
SetMarker(label1);
PushConstant(0);
GetVariable;
Push([1], [vtConstant8]);
GetMember;
Push(0);
Less2;
_Not;
label2 := _If.BranchOffsetMarker;
PushConstant(0);
GetVariable;
Push([1, 250], [vtConstant8, vtInteger]);
SetMember;
SetMarker(label2);
PushConstant(0);
GetVariable;
PushConstant(2);
GetMember;
Push(0);
Less2;
_Not;
label3 := _If.BranchOffsetMarker;
PushConstant(0);
GetVariable;
Push([2, 250], [vtConstant8, vtInteger]);
SetMember;
SetMarker(label3);
Push([300, 0], [vtInteger, vtConstant8]);
GetVariable;
PushConstant(2);
GetMember;
Less2;
_Not;
label4 := _If.BranchOffsetMarker;
PushConstant(0);
GetVariable;
Push([2, 10], [vtConstant8, vtInteger]);
SetMember;
SetMarker(label4);
Push([3, 4], [vtConstant8, vtInteger]);
RandomNumber;
SetVariable;
Push([4, 4], [vtConstant8, vtInteger]);
RandomNumber;
SetVariable;
PushConstant(0);
GetVariable;
PushConstant([1, 3]);
GetVariable;
PushConstant(0);
GetVariable;
PushConstant(1);
GetMember;
Add2;
SetMember;
PushConstant(0);
GetVariable;
PushConstant([2, 4]);
GetVariable;
PushConstant(0);
GetVariable;
PushConstant(2);
GetMember;
Add2;
SetMember;
end;
ShowFrame;
RemoveObject(1);
FrameActions.GotoFrame(0);
FrameActions.Play;
ShowFrame;
end;

EA := TSWFExportAssets.Create;
EA.Assets.Objects[EA.Assets.Add('bot')] := Pointer(LongInt(Movie.Sprites[1].CharacterId));
Movie.ObjectList.Add(EA);

With Movie.FrameActions do
begin
ConstantPool(['max', 'i', 'zufall', 'bot', 'attachMovie', '_root', '_x', '_y', '_xscale', '_yscale', '_alpha']);
Push([0, 100], [vtConstant8, vtInteger]);
SetVariable;
Push([1, 0], [vtConstant8, vtInteger]);
SetVariable;
label2 := SetMarker;
PushConstant(1);
GetVariable;
PushConstant(0);
GetVariable;
Less2;
_Not;
label1 := _If.BranchOffsetMarker;
Push([2, 150], [vtConstant8, vtInteger]);
RandomNumber;
SetVariable;
Push([1], [vtConstant8]);
GetVariable;
PushConstant([3, 1]);
GetVariable;
Add2;
Push([3, 3, 4], [vtConstant8, vtInteger, vtConstant8]);
CallFunction;
Pop;
PushConstant(5);
GetVariable;
PushConstant([3, 1]);
GetVariable;
Add2;
GetMember;
Push([6, 800], [vtConstant8, vtInteger]);
RandomNumber;
SetMember;
PushConstant(5);
GetVariable;
Push([3, 1], [vtConstant8, vtConstant8]);
GetVariable;
Add2;
GetMember;
Push([7, 360], [vtConstant8, vtInteger]);
RandomNumber;
SetMember;
PushConstant(5);
GetVariable;
PushConstant([3, 1]);
GetVariable;
Add2;
GetMember;
PushConstant([8, 2]);
GetVariable;
SetMember;
PushConstant(5);
GetVariable;
PushConstant([3, 1]);
GetVariable;
Add2;
GetMember;
PushConstant([9, 2]);
GetVariable;
SetMember;
PushConstant(5);
GetVariable;
PushConstant([3, 1]);
GetVariable;
Add2;
GetMember;
PushConstant([10, 2]);
GetVariable;
SetMember;
PushConstant([1, 1]);
GetVariable;
Increment;
SetVariable;
Jump.BranchOffsetMarker := label2;
label2.JumpToBack := true;
SetMarker(label1);
end;

Movie.ShowFrame;
Movie.MakeStream;
Movie.SaveToFile('demo.swf');
Movie.Free;

ShellExecute(handle, 'open', 'demo.swf', nil, nil, SW_Normal);

TDD, Visual Studio 2005, Scott Bellware’s blog post

In response to the MSDN Test-Driven Development Guidelines, Scott Bellware has an interesting rant over here.

Update: before I could post this entry, the MSDN posting had been removed, luckily I saved a copy elsewhere. Since I’ve just spent the last few minutes writing this, I’m posting it anyway. Here’s what’s there now:

Guidelines for Test-Driven Development
This topic is obsolete and has been removed from the MSDN documentation.

It would appear that the MSDN posting has hit a nerve in the TDD community, and on first impressions, rightly so. I’m about to embark on a couple of days travel, I’ll be taking some of the material surrounding this posting and rant with me to read, expect to see me follow it up later this month.

To pick on a few posting (on the off chance you’re not following this rant elsewhere): Scott Dockendorf steps up and denounces any involvement in the article over here. Agile guru Roy Osherove is very vocal about the article in his Microsoft fails miserably to explain or promote Test Driven Development in Team System posting. And Julian M Bucknall is all depressed about it over here.

On a separate note, and it’s perhaps why I associated this posting with my “Opinion” category (not that this counts for much, but I feel as if that category lets me write what I like and not get sued! That’ll be right!), as an MVP should I be seen to be criticising Microsoft? Ignoring the relationship that exists, if an organisation did something that was wrong (in the eyes of the majority), I would feel professionally obliged to point out the error in their ways. Even after nearly a decade in the same organisation where such an attitude is pretty much frowned upon, I still maintain this professional desire to see things done properly. However, again on first impressions, I see that the MSDN posting is rapidly becoming MSTDD, so at least the differentiation is there. Hopefully all the TDD newbies will catch up on TDD postings prior to embarking on what amounts to a shoe-horned flavour of TDD.

More when I return from my travels.

Here’s the original MSDN posting:

Visual Studio Team System
Guidelines for Test-Driven Development
If your software-development project uses test-driven development, or TDD, you can benefit from features of Visual Studio 2005, and in particular, features of Visual Studio 2005 Team System. These features include the unit test type of Team Edition for Testers, and especially the ability to generate unit tests automatically; automatic refactoring capabilities that are introduced in Visual Studio 2005, and the Class Designer tool.

The unit test support of Team Edition for Testers is particularly suited to TDD because these Team System testing tools can generate tests from a minimum of production code.

Process Example
In your TDD project, you might want to follow these steps:

  1. Define the requirements of your application.
  2. Familiarize yourself with the feature areas of your application, and decide on a single feature, or the requirements of a feature, to work on.
  3. Make a list of tests that will verify the requirements. A complete list of tests for a particular feature area describes the requirements of that feature area unambiguously and completely.
  4. File work items for feature requirements and for the tests that need to be written.
  5. In Visual Studio, create a project of the type you want. Visual Studio supplies the initial production code in the form of files such as Class1.cs, Program.cs, and Form1.cs, depending on the project type.
  6. Define the interfaces and classes for your feature or requirement. You can add a minimum of code, just enough to compile. Consider using the Class Designer to follow this step. For more information, see Designing Classes and Types.
  7. Note
    The traditional TDD process does not contain this step. Instead, it advises that you create tests first. This step is included here so that, while creating tests, you can take advantage of two features in Visual Studio 2005 Team System: the GUI design capabilities of the Class Designer, and the automatic test-generation capabilities of Team Edition for Testers.

  8. Generate tests from your interfaces and classes. For more information, see How to: Generate a Unit Test.
  9. Compare the tests that have been generated with the list of tests you prepared in step 3. Create any tests that are missing from the list you wrote in step 3. For more information, see How to: Author a Unit Test.
  10. Organize your tests into test lists. You can, for example, base your lists on test use, such as check-in tests, BVTs, and tests for a full-test pass; or on area, such as UI tests, business-logic tests, and data-tier tests. For more information, see How to: Organize Tests into Test Lists.
  11. Update the generated tests to make sure they exercise the code in ways that cover the requirements that you have defined.
  12. Run your tests. For more information, see How to: Run Selected Tests.

    Verify that all your tests fail. If any test produces a result of Inconclusive, it means that you did not update the generated code to add the appropriate verification logic for that test. If any test produces a result of Passed, it means that you did not implement the test correctly; this is because you have not implemented your production code, so no tests should pass.

  13. Implement the interfaces and classes of your production code.
  14. Run your tests again. If a test still fails, update your production code to respond. Repeat until all the tests pass.
  15. Pick the next feature or requirement to work on and repeat these steps.

Visual Studio 2003 and 2005 Service Packs…

Scott Wiltamuth’s C# blog has hinted that we might might see some service packs for Visual Studio 2003 and the recently launched Visual Studio 2005. Rumour has it, the service packs for Visual Studio 2005 might be available during the first half of 2006.

Whilst service packs are usually welcomed, I am a little concerned that there is talk of a service pack for Visual Studio 2005…so soon. I mean, it’s only a matter of hours since it was launched, and days since it reached RTM. I suppose Microsoft had to release the product during 2005 and have enough time to ensure a timely series of launch events, hence early November. Given that revenue shouldn’t be a real problem for Microsoft, I’m pretty confident that this isn’t a case of early release to bring in early profit.

Visual Studio 2005, SQL Server 2005 and BizTalk 2006 launch

Steve Ballmer delivered the launch speech via satellite from San Francisco where he shared an auditorium with 3000 or so guests (developers). The UK launch was held at the London Stock Exchange yesterday. There’s an on-demand web cast available here.

The key launch message that came across revolved around: better decisions, faster results, better insight. These are values/principles that guided the individual product development (Visual Studio, SQL Server, BizTalk) and the broad platform development (encompassing SharePoint, Windows clients, Microsoft Office, Microsoft Dynamics, developer tools, management tools, XML web services, ind std and Microsoft own .net innovations)

Steve went on to highlight some statistics from IDC. Platform momentum, five years after the launch of .NET – when asked what platform are you using for mission critical applications: 35% of customers are using .NET whereas 25% using Java. “35%, number one clearly is .NET”. In calendar year 04, SQL Server out-sold DB2 and Oracle. And with the sheer power provided by Intel and various hardware vendors, the combination of hardware and Microsoft product sets, Steve came out with this quote:

“There is no job that is too big to run on entirely on the Windows and Microsoft platform”

The launch speech saw a student and Brian Goldfarb extol the virtues of the Visual Studio 2005 and SQL Server 2005 Express Editions. What’s important to note about the Express Editions is that fact that they are free. Obviously the Express Editions don’t have all the features of the full product versions, but the projects you create with them are upwardly compatible and they’ll give you great exposure to the Visual Studio and SQL Server family. Aimed at hobbyist and students, the Express Editions are a good way of getting that much needed product experience that will put you in good stead in your first job. Download your Express Editions here.

There seemed to be some arm waving surrounding the introduction of “My” – something that has been introduced into the Visual Basic.net language. I’m not sure what all the fuss is about, but will take this opportunity to remind everybody that Juval Lowy has gone ahead and implemented in C#. There’s some good stuff about the Visual Basic.net version over here. There’s more about “My” for C#, this and that, over here…or you can just download it from here.

I also got to meet Tim Anderson – I shook his hand and that’s about it: three weeks of ‘flu, cold, coughing and sore throat cost me my voice…I was sipping Lemsip all day!

My voice eventually returned…Microsoft’s Phil Cross put up with me for the best part of an hour – we seem to share the same ideas about the concept of feedback. Feedback is important, if you (as a “vendor”) ask your customer(s) for some feedback, e.g. a restaurant owner asking guests for feedback after their meal, please take the feedback and do something with it: don’t turn it back on the customer and make them feel guilty. Towards the end of the evening IT Week’s Martin Banks passed by to say “hello, goodbye”…I shook his hand too! Of course, all this hand-shaking is nothing in comparison to Richard Costall’s experience in this department! (I shook Richard’s hand before I knew where his hand had been…may be something will have rubbed off on me?)

Sign up for the Ready To Launch Tour!

Information Week’s take on the launch is here.

NUnit under Visual Studio 2005

With reference to this, Visual Studio 2005 Professional doesn’t come with the unit testing support that its big brother Visual Studio Team System does…

Charles explains how to get NUnit to work with Visual Studio 2005. Thanks Charles!

If you are planning to move to Visual Studio Team System, James Newkirk has written an NUnit convertor, available here.

One of NUnit’s key players, Charlie Poole, has blogged about the alleged demise of NUnit – read more about it here.

Fresh MSDN content

Courtesy of INETA, here’s some fresh reading material from the MSDN

.NET development
Windows Presentation Foundation Hands-On-Labs
http://msdn.microsoft.com/windowsvista/building/presentation/hands_on_lab/default.aspx

Development; Development tools
Celebrate the 20-year anniversary of C++ with the top C++ speakers in
the world in Las Vegas
http://www.devconnections.com/shows/cppfall2005/default.asp?s=67

Development guide
.NET development

patterns & practices Guidance: Complete Catalog
http://msdn.microsoft.com/practices/compcat/default.aspx

.NET development; Deployment; Design; Development; practices; Scalability

patterns & practices – VB6 to VB.NET Migration Guide: Home
http://www.gotdotnet.com/codegallery/codegallery.aspx?id=07c69750-9b49-4783-b0fc-94710433a66d

Threat Modeling Web Applications
Author: J.D. Meier, Alex Mackman, Blaine Wastell
http://msdn.microsoft.com/practices/default.aspx?pull=/library/en-us/dnpag2/html/tmwa.asp

Register Now for patterns & practices Summits
http://www.pnpsummit.com/_practices.aspx

Generics FAQ: Fundamentals
Author: Juval Lowy
http://msdn.microsoft.com/netframework/default.aspx?pull=/library/en-us/dndotnet/html/Fundamentals.asp (Printed Pages: 51)

Generics FAQ: .NET Framework
Author: Juval Lowy
http://msdn.microsoft.com/netframework/default.aspx?pull=/library/en-us/dndotnet/html/NetFramework.asp (Printed Pages: 35)

Generics FAQ: Tool Support
Author: Juval Lowy
http://msdn.microsoft.com/netframework/default.aspx?pull=/library/en-us/dndotnet/html/ToolSupport.asp (Printed Pages: 5)

Generics FAQ: Best Practices
Author: Juval Lowy
http://msdn.microsoft.com/netframework/default.aspx?pull=/library/en-us/dndotnet/html/BestPractices.asp (Printed Pages: 16)

Multimedia Content
Microsoft After Dark: The Launch Show
http://www.microsoft.com/winme/0510/25540/welcome.htm

Security; Web Services
Web Service Enhancements (WSE) 3.0 and Secure Web Services
Author: Mark Fussell
http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20051027WSE3MF/manifest.xml

Web development
Video Series: Getting Started with Visual Web Developer 2005
http://go.microsoft.com/fwlink/?LinkId=51655

Prescriptive architecture guidance
patterns & practices Developer Center
http://msdn.microsoft.com/practices

Reference
.NET development; Architecture; Development; Development tools; Patterns; practices
patterns & practices for Visual Studio 2005
http://msdn.microsoft.com/practices/VS2005/

.NET development; Development; Development tools; Migration; practices
Visual Basic 6.0 to VB.NET Upgrade Guidance – Community Pre-Release
Author: Edward Lafferty, William Loefler
http://www.gotdotnet.com/codegallery/codegallery.aspx?id=07c69750-9b49-4783-b0fc-94710433a66d

Technical article
Launch2K5: GridView Examples for ASP.NET 2.0
http://msdn.microsoft.com/asp.net/beta2/default.aspx?pull=/library/en-us/dnaspp/html/GridViewEx.asp

.NET development; Audio and video; Development
Non-Destructive Media Edits
Author: Arian Kulp
http://msdn.microsoft.com/coding4fun/inthebox/NDMediaEdit/default.aspx

.NET development; Game development
Kid’s Programming Language: Pong!
Author: Jon Schwartz
http://msdn.microsoft.com/coding4fun/gamedevelopment/KPL1/default.aspx

Debugging; Design; Development; Performance; User interface
Improving the Performance of InfoPath 2003 Forms
Author: Andrew Begun, Dafina Toncheva
http://msdn.microsoft.com/office/default.aspx?pull=/library/en-us/odc_ip2003_ta/html/OfficeInfoPathTroubleshootPerformanceBestPracticeGuidelines.asp (Printed Pages: 18)

DevelopmentNamed Return Value Optimization in Visual C++ 2005
Author: Ayman B. Shoukry
http://msdn.microsoft.com/visualc/default.aspx?pull=/library/en-us/dnvs05/html/nrvo_cpp05.asp (Printed Pages: 12)

Development tools; Security
Adopting Visual Studio Express Within Your Organization
Author: Rudolph Araujo
http://msdn.microsoft.com/vstudio/default.aspx?pull=/library/en-us/dnvs05/html/vsexpresssecurity.asp (Printed Pages: 10)

Mobility
Step by Step: Building a .NET Compact Framework Application for a
Windows Mobile-based Device Using Visual Studio 2005
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnppcgen/html/med201_msdn_netcf_app_vs2005rtf.asp (Printed Pages: 56)

Revised Content
Technical article
.NET development; Web development
ASP.NET Spiced: AJAX
Author: Karl Seguin
http://msdn.microsoft.com/asp.net/default.aspx?pull=/library/en-us/dnaspp/html/ASPNetSpicedAjax.asp (Printed Pages: 17)

Architecture
Architecture Chronicles – Dynamic Modeling: Aligning Business and IT
(Landing Page)
Author: Dave Welsh, with Frederick Chong
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/MSArcSeriesMCSIntro.asp (Printed Pages: 2)

Web Service Deployment: Deploying Web Services in the Northern
Electronics Scenario (Architecture Chronicles – Dynamic Modeling:
Aligning Business and IT)

Author: Frederick Chong, with Jim Clark
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/MSArcSeriesMCS7.asp (Printed Pages: 18)

Web Service Health Modeling, Instrumentation, and Monitoring: Developing
and Using a Web Services Health Model for the Northern Electronics
Scenario (Architecture Chronicles – Dynamic Modeling: Aligning Business
and IT)
Author: Frederick Chong, with Jim Clark
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/MSArcSeriesMCS6.asp (Printed Pages: 46)

Web Service Solution Design: Developing a Solution Design for Web
Services in the Northern Electronics Scenario (Architecture Chronicles –
Dynamic Modeling: Aligning Business and IT)
Author: Frederick Chong, with Jim Clark
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/MSArcSeriesMCS5.asp (Printed Pages: 15)

Dealing with the “Melted Cheese Effect”: Contracts
Author: Maarten Mullender
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/MeltedCheeseContracts.asp (Printed Pages: 11)

Mobility
Step by Step: Migrating an eMbedded Visual C++ Application to Visual
Studio 2005
http://www.msdn.microsoft.com/library/en-us/dnppcgen/html/med303_msdn_migrate_evc_app_vs2k5.asp (Printed Pages: 22)

VistaDB 2.1 database for .NET has been released

This 2.1 update includes over 60 improvements, including new support for .NET 2.0 and Visual Studio .NET 2005. VistaDB is a small-footprint, embedded SQL database alternative to Jet/Access, MSDE and SQL Server Express 2005 that enables developers to build .NET 1.1 and .NET 2.0 applications. Features SQL-92 support, small 500KB embedded footprint, free 2-User VistaDB Server for remote TCP/IP data access, royalty free distribution for both embedded and server, Copy ‘n Go! deployment, managed ADO.NET Provider, data management and data migration tools. A free trial is available for download.

Learn more about VistaDB
Repost this to your blog and receive a FREE copy of VistaDB 2.1!

And of course, if Vista Software would like VistaDB 2.1 reviewed for publication, they’re free to contact me with details of how I can get my hands on a full NFR copy of VistaDB 2.1…over to you!

Whilst you’re looking over 2.1, look at what’s coming in 3.0!