Historical Debugger and Test Impact Analysis in Visual Studio Team System 2010

I was browsing some of the awaited-for Visual Studio 2010 and I found a video about two interesting features related to what we do everyday (and I do not mean coding ;))

The first feature is related to debugging “history”. Normally, when you find a bug while running your program, you insert multiple breakpoints on the statements you suspect might caused it, and repeat the scenario or restart the debug session.

With history debugging, you don’t need to do so, since the history debugger “logs” every event in your application, so you can “pause” running and inspect all the previous events and may be check if there were “swallowed” exceptions.

The second feature, is when you want to modify some “unit-tested” code either for bug fixing or refactoring, and you want to re-run the impacted tests. Normally it is hard to determine which tests are affected so you run all of them, but with Test Impact Analysis in VS 2010, you can get the impacted tests once you save your modifications, so you can either commit your changes or undo.

Here is the 19 minutes video showing these two features on Channel 9

Historical Debugger and Test Impact Analysis in Visual Studio Team System 2010

C# 4.0: What’s next

Since I have talked before about Visual Studio 2010 and Dynamic Typing, it is now time to talk about the upcoming C# 4.0 which we are expecting soon.

To understand how C# evolved and what is the paradigm of C# 4.0, let’s get a quick overview of previous versions.

In 1998 the C# began as a simple, modern, object-oriented, and type-safe programming language for the .NET platform. Since launched in the summer of 2000, C# has become one of the most popular programming languages in use today.

With version 2.0 the language evolved to provide support for generics, anonymous methods, iterators, partial types, and nullable types.

When designing version 3.0 of the language the emphasis was to enable LINQ (Language Integrated Query) which required the addition of:

  • Implicitly Typed Local Variables.
  • Extension Methods.
  • Lambda Expressions.
  • Object and Collection Initializers.
  • Anonymous types.
  • Implicitly Typed Arrays.
  • Query Expressions and Expression Trees.

Although C# is an object-oriented programming, but C# 3.0 included some capabilities of functional programming to enable LINQ

In version 4.0 the C# programming language continues to evolve, although this time the C# team were inspired by dynamic languages such as Perl, Python, and Ruby.

Another paradigm that is driving language design and innovation is concurrency and that is a paradigm that has certainly influenced the development of Visual Studio 2010 and the .NET Framework 4.0.

Essentially the C# 4.0 language innovations include:

  • Dynamically Typed Objects.
  • Optional and Named Parameters.
  • Improved COM Interoperability.
  • Safe Co-variance and Contra-variance.

To show these features, I’ll show some examples posted by Doug Holland on his The C# Programming Language Version 4.0 blog post…

Dynamically Typed Objects

In C# today you might need to get an instance of a class and then calls the Add method on that class to get the sum of two integers:

Calculator calc = GetCalculator();
int sum = calc.Add(10,20);

Our code gets all the more interesting if the Calculator class is not statically typed but rather is written in COM, Ruby, Python, or even JavaScript. Even if we knew that the Calculator class is a .NET object but we don’t know specifically which type it is then we would have to use reflection to discover attributes about the type at runtime and then dynamically invoke the Add method.

object calc = GetCalculator();
Type type = calc.GetType();
object result = type.InvokeMember("Add", BindingFlags.InvokeMethod, null,
    new object[] { 10, 20 });
int sum = Convert.ToInt32(result);

With the C# 4.0 we would simply write the following code:

dynamic calc = GetCalculator();
int sum = calc.Add(10,20);

In the above example we are declaring a variable, calc, whose static type is dynamic. We’ll then be using dynamic method invocation to call the Add method and then dynamic conversion to convert the result of the dynamic invocation to a statically typed integer.

Optional and Named Parameters

Another major benefit of using C# 4.0 is that the language now supports optional parameters (like C and C++) and named parameters.

One design pattern you’ll often see as that a particular method is overloaded because the method needs to be called with a variable number of parameters.

In C# 4.0 a method can be refactored to use optional parameters as the following example shows:

public StreamReader OpenTextFile(string path, Encoding encoding =  null, bool
    detectEncoding = false, int bufferSize = 1024) { }

Given this declaration it is now possible to call the OpenTextFile method omitting one or more of the optional parameters.

OpenTextFile("foo.txt", Encoding.UTF8);

It is also possible to use the C# 4.0 support for named parameters and as such the OpenTextFile method can be called omitting one or more of the optional parameters while also specifying another parameter by name.

OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 1024);

Named arguments must be provided last although when provided they can be provided in any order.

Improved COM Interoperability

When you work with COM interop methods, you had to pass a reference to Missing.Value for unneeded parameters, like the following:

object filename = "test.docx";
object missing = System.Reflection.Missing.Value;

doc.SaveAs(ref filename,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing);

Now, in C# 4.0 you can only write:

doc.SaveAs(filename);

Notice that you are able to omit the ref modifier although the use of the ref modifier is still required when not performing COM interoperability.

Also it was necessary to ship a Primary Interop Assembly (PIA) along with your managed application. This is not necessary when using C# 4.0 because the compiler will instead inject the interop types directly into the assemblies of your managed application and will only inject those types you’re using and not all of the types found within the PIA.

Safe Co-variance and Contra-variance

Co-variance means that an instance of a subclass can be used when an instance of a parent class is expected, while Contra-variance means that an instance of a super class can be used when an instance of a subclass is expected. When neither is possible, it is called Invariance.

Since version 1.0 arrays in .NET has been co-variant meaning that an array of string can be assigned to an array of object.

string[] strings = new string[] { "Hello" };
object[] objects = names;

Unfortunately arrays in .NET are not safely co-variant. Since objects variable was an array of string the following will succeed.

objects[0] = "Hello World";

Although if an attempt is made to assign an integer to the objects array an ArrayTypeMismatchException is thrown.

objects[0] = 1024;

To achieve safety, both C# 2.0 and C# 3.0 generics are invariant and so a compiler error would result from the following code:

List strings= new List();
List<object> objects = strings;

For the Liskov Substitution Principle (LSP) to be achieved, methods of a derived class need to have contra-variant inputs and co-variant outputs.

Generics with C# 4.0 now support safe co-variance and contra-variance through the use of the in (contra-variant) and out (co-variant) contextual keywords. Let’s take a look at how this changes the definition of the IEnumerable<T> and IEnumerator<T> interfaces.

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

public interface IEnumerator
{
    T Current { get; }
    bool MoveNext();
}

Given that an IEnumerable collection is read only, there is no ability specified within the interface to insert new elements, it is safe to treat a more derived element as something less derived. With the out contextual keyword we are contractually affirming that IEnumerable<out T> is safely co-variant. We can now write the following code without a compiler error:

IEnumerablestrings = GetStrings();
IEnumerable<object> objects = strings;

Using the in contextual keyword we can achieve safe contra-variance, that is treating something less derived as something more derived.

public interface IComparer
{
    int Compare(T x, T y);
}

Given that IComparer<in T> is safely contra-variant we can now write the following code:

IComparer objectComparer = GetComparer();
IComparer stringComparer = objectComparer;

It is important to notice that co-variance in IEnumerable<object> refers to the fact that its Current property can return a string instead of an object as output, while contra-variance in IComparer<string> refers to the fact that its Compare method can accept an object instead of a string as input.

SQL Server data types

Actually I have thought to write this post mainly for me as I always forget the differences of the different (yet similar) data types in SQL Server

Here is what I need to remember:

  • numeric is the same as decimal and they are both exact decimal values
  • float and real are approximate values
  • fLoat(n) complies with ISO SQL, n is the mantissa digits
  • [float(25) – float(53)] are stored in 8 bytes while [float(1) – float(24)] are stored in 4 bytes 
  • real is the same as float(24)
  • money is an exact decimal value stored on 8 bytes
  • nchar and nvarchar are the Unicode versions (2 bytes per character) while char and varchar use only 1 byte (so they can still accept UTF-8 characters but not UTF-16 like Japanese or Chinese)

That was some short notes, for the full details you can check

http://msdn.microsoft.com/en-us/library/ms187752.aspx

StyleCop for ReSharper has been released

StyleCop for ReSharper has been released last week as a plugin for ReSharper to bring StyleCop code styling issues to ReSharper real-time syntax highlighting, quick-fixes, and Code CleanUp.

Although I personally don’t like many of StyleCop rules, but like ReSharper rules, they can be turned off individually. The plugin performance can also be customized from within the ReSharper options window.

More about StyleCop:

Microsoft StyleCop analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. It is another static analysis tool by Microsoft like FxCop, but the later analyzes the compiled object code for design issues, not the source code.

More about ReSharper:

ReSharper is a Visual Studio add-in created by JetBrains (the creator of many software productivity tools like IntelliJ®IDEA the Java IDE, TeamCity™ the build integration server, and dotTrace Profiler)

I have been using ReSharper almost since I started using Visual Studio and it has always been a complement to it. Even when Visual Studio evolved from 2003 to 2005, and finally 2008, ReSharper has still much to add.

One of the features I like most in ReSharper is its ability to detect syntax and styling error while you type, refactor code quickly, suggest variable names based on classnames, highlight redundant code, make code more readible, find references and jump to it directly if only once.

There has been some talks that Visual Studio 2010 is actually 2008 + ReSharper because of a mistake they made when they posted some snapshots of Visual Studio 2010 with ReSharper menus and screens in it.

Microsoft on the other hand had been promoting one of ReSharper competitors and announced a cooperation with DevExpress to license a free version of CodeRush Express exculsively for C# developers working on Visual Studio.

kick it on DotNetKicks.com

Scrum for Team System

It is unlikely to find an agile software project not using JIRA, Subversion, CruiseControl, or some other agile productivity suites. One of the most commonly used suites in Microsoft Environment is Team Foundation Server which combines Source Control, Task Planning, Testing, Bug and Issue Tracking, a Build Server, and a Dashboard interface to share documents and ideas in a wiki-like manner.

TFS has an out-of-the-box process template for agile projects, but this template is not fully compliant with Scrum. Since TFS is open for any custom process template, some vendors have provided free templates for Scrum.

The first effort in this area was Scrum for Team System by Conchango. Then a group of VSTS MVPs created a light-weight process template that is easier to install and configure which makes it more appropriate for small projects with small teams.The latest one is eScrum which is provided by Microsoft but as an additional download.

It was also convenient to view the sprint tasks in the form of task board with drag-n-drop capabilities to move tasks between panes. Conchango also had provided Task Board for Team System but it is commercial with one month free trial.

I personally prefer using the TFS integration with MS Office to add tasks in Excel with a running sum of used capacity and then post the tasks to TFS at once. There are many other uses for showing tasks in Excel like conditional formatting of cells to indicate different states, severity, priority and so on.

Duck Typing

While browsing the net, I found that Typemock Isolator 5.1.1 has been released, which is a mocking framework that I should try one day.

What I’m interested in is its ability to “swap” calls between real and fake objects even if they don’t implement the same interface, like this:

var duck = new Duck(); // The real, untestable class, with a Talk() method
var dummy = new Dummy(); // The fake, testable class, with another Talk() method
Isolate.Swap.CallsOn(duck).WithCallsTo(dummy);
Assert.AreEqual("Quack", dummy.Talk()); // Then the dummy is a duck

I guess the Isolate class is “borrowed” from Ruby, but anyway, it makes testing easier.

This can be possible by applying the concept of “Duck Typing” which was named as James Whitcomb Riley said


If it walks like a duck and quacks like a duck, I would call it a duck

 

So, regardless of the properties and methods of both the dummy and the real duck, a dummy can be considered a duck if it satisfies the properties and methods of a real duck in the current context, or in other words; it does not have to inherit from a duck nor satisfy all behavior of a real duck, but only what we need right now [Talk()]

Duck typing is a principle of Dynamic Typing (Which I plan to blog about next), and it is a heavily used in Dynamic Languages like Python, Ruby.

It is sometimes used in Static Languages, and may be more often than we expect. Here is a blog about Duck Notation in C# in which we find out that iterators in a foreach statement use duck typing. Also in BOO you can define a variable as duck.

Currently there is an open source project to enable duck-typing in C#, and also it is planned to be in the upcoming C# 4.0

An insight on functional programming

It has been a long vacation, with quite some events to talk about

I had been following up the release of F# CTP which I haven’t got comprehensive knowledge yet, but to sum it up, it is a functional, declarative programming language.

In a functional language, each function should get some inputs, and return an output, with no other “side effect”; which means the internal implementation of the function doesn’t affect the state of the object or the state of any other related objects or global variables.

This is what differs functional languages from procedural or object oriented languages where a “method” can affect the instance fields or properties of the same object and/or other objects, can print something on a screen, or can persist something on other media. Each of these action doesn’t qualify a language as a functional language.

Some “pure functions” are mathematical functions such as “SUM()”, “AVG()”, “MAX()”, “MIN()” which typically get one or more input and return an output regardless of the context it is called from.

That decoupling from the context, make it easy to define “what” instead of “how” and hence it is a declarative programming language as well.

You can get a quick understanding of this language and the concepts of functional languages from this 20 minutes tutorial.

Visual Studio 2010 (Rosario)

Microsoft has provided the first look at its new development platform Visual Studio 2010 which is based on the new .NET Framework 4.0.

Microsoft described the next release through the following five focus areas:

  • riding the next-generation platform wave
  • inspiring developer delight
  • powering breakthrough departmental applications
  • enabling emerging trends such as cloud computing
  • democratizing application life-cycle management (ALM)

Their efforts in the area of ALM is the next step after their launch of Team Foundation Server (TFS) in 2005 and their efforts to combine Management, Analysis, Design, Testing, and Deployment all together under one platform.

The new announced features includes enhanced modeling with new diagram types such as use case, activity, and sequence beside the tightly close integration of modeling with existing and new code.

My favorite in the new features is the new testing capabilities which includes a stand-alone Test Runner that allows for running manual test, and at the same time take system snapshots with pertinent information and can be even used to take video captures of what was done during the test and report a bug to TFS directly with the captured data as an attachment.

Another favorite is the Test Impact View, which allows the developer to view the code changes made and the impacted tests that needs to re-run before checking in the latest modification.

For more info you can check the Visual Studio Team System 2010 Overview page.