01 May 2013

Using the Nugetter CodePlex project with TFS 2012 build throws TF215097 error

Problem

While working with a client recently I came across an issue that I think needs to be better documented. 

We were implementing Nuget packaging in their TFS 2012 build process.  I knew from past engagements that the Nugetter project on CodePlex is an excellent way to easily add this activity to an existing build process.

We created the build definition using the NuGetterMultiPkgBuildVersionedTemplate20.xaml build process template. When we ran the build, it failed with the following error

TF215097: An error occurred while initializing a build for build definition
[Build Definition] nuget:

Exception Message: The invocation of the constructor on type
'TfsBuild.NuGetter.Activities.NuGetterProcess' that matches the specified
binding constraints threw an exception. (type XamlObjectWriterException)


Exception Stack Trace:
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType,
Object[] args)
at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(
ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter,
Boolean closeWriter)
at System.Activities.XamlIntegration.FuncFactory`1.Evaluate()
at System.Activities.DynamicActivity.OnInternalCacheMetadata(
Boolean createEmptyBindings)
at System.Activities.Activity.InternalCacheMetadata(Boolean createEmptyBindings,
IList`1& validationErrors)
at System.Activities.ActivityUtilities.ProcessActivity(ChildActivity childActivity,
ChildActivity& nextActivity, Stack`1& activitiesRemaining,
ActivityCallStack parentChain, IList`1& validationErrors,
ProcessActivityTreeOptions options, ProcessActivityCallback callback)
at System.Activities.ActivityUtilities.ProcessActivityTreeCore(
ChildActivity currentActivity, ActivityCallStack parentChain,
ProcessActivityTreeOptions options, ProcessActivityCallback callback,
IList`1& validationErrors)
at System.Activities.ActivityUtilities.CacheRootMetadata(Activity activity,
LocationReferenceEnvironment hostEnvironment, ProcessActivityTreeOptions options,
ProcessActivityCallback callback, IList`1& validationErrors)
at System.Activities.Validation.ActivityValidationServices
.InternalActivityValidationServices.InternalValidate()
at Microsoft.TeamFoundation.Build.Workflow.WorkflowHelpers.ValidateWorkflow(
Activity activity, ValidationSettings validationSettings)
at Microsoft.TeamFoundation.Build.Hosting.BuildProcessCache.LoadFromXaml(
String workflowXaml, TextExpressionImports textExpressionImports)
at Microsoft.TeamFoundation.Build.Hosting.BuildControllerWorkflowManager
.PrepareRequestForBuild(WorkflowManagerActivity activity, IBuildDetail build,
WorkflowRequest request, IDictionary`2 dataContext)
at Microsoft.TeamFoundation.Build.Hosting.BuildWorkflowManager.TryStartWorkflow(
WorkflowRequest request, WorkflowManagerActivity activity,
BuildWorkflowInstance& workflowInstance, Exception& error, Boolean& syncLockTaken)

Inner Exception Details:

Exception Message: Exception has been thrown by the target of an invocation.
(type TargetInvocationException)

Exception Stack Trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments,
Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr,
Binder binder, Object[] parameters, CultureInfo culture)
at System.Activities.XamlIntegration.ActivityXamlServices.GetXamlSchemaContext(
Assembly assembly, String helperClassName)
at System.Activities.XamlIntegration.ActivityXamlServices.InitializeComponent(
Type componentType, Object componentInstance)
at TfsBuild.NuGetter.Activities.NuGetterProcess.BeforeInitializeComponent(
Boolean& isInitialized)
at TfsBuild.NuGetter.Activities.NuGetterProcess.InitializeComponent()

Inner Exception Details:

Exception Message: Could not load file or assembly 'System.Management.Automation,
PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
The system cannot find the file specified. (type FileNotFoundException)

Exception Stack Trace:
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName,
String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint,
StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound,
Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef,
Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark,
IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection,
Boolean suppressSecurityChecks)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at XamlStaticHelperNamespace._XamlStaticHelper.Load(String assemblyNameVal)
at XamlStaticHelperNamespace._XamlStaticHelper.LoadAssemblies()
at XamlStaticHelperNamespace._XamlStaticHelper.get_SchemaContext()

I’ve pasted the entire error message here so that it will be indexed by search engines and thus easier to find. :)

Solution

We did a little bit of searching online and followed a few dead-end trails.  We finally tracked down a discussion article on the Nugetter project’s discussion page that pointed to a mismatched PowerShell version on the build controller.

While our build controller machine was running Windows Server 2008 R2, we found that it only had PowerShell v1.0 installed.  We need to have PowerShell v3 installed for this to work.

We installed PowerShell v3 on the build controller and build agent and rebooted both machines.  When we triggered the build again it ran to completion.

I’m not sure if the updated PowerShell was necessary for the Build Agent machine but the client decided to install it anyway.

Synopsis

If you encounter this error, make sure the Build Controller box has PowerShell v3 installed on it.

30 March 2013

How To: Create an offline installer for Visual Studio from a Web Installer

Synopsis

If you have the need to download the complete set of files for a given Visual Studio update so that you can burn them to media or place them on an internal network share for distribution, you can run the Visual Studio 2012 installation bootstrapper with the /layout switch to force it to download all of the update packages and place them on your drive in a folder of your choosing.

   1:  "VS2012.2 CTP.exe" /layout
 

You can now use that installation folder’s contents as the source for your upgrades. Please realize that you will need a couple of GBs of space to save the installation.  The complete download for VS 2012.2 CTP 4 comes in at 1.66GB.


 tl;dr

Problem

The current VS Updates use a small installation “bootstrapper” that figures out what you have installed (Pro vs. Premium vs. Ultimate) and then does an install-time download of the needed updates. As you can see in Figure 1, the update installer is only 1.3MB in size so it downloads fast and your installation can begin immediately.  You will also notice that there is no option to download the entire update for all Visual Studio versions as a single MSI or ISO file.

SNAGHTML3ca3dd

Figure 1: Downloads page from Visual Studio 2012 Update 2 CTP 4 ds page - http://www.microsoft.com/en-us/download/details.aspx?id=36833 

When you run this installer you will see that the installation take a while to start.  It will eventually get to the “Install” screen.  There is a “More Information” link that changes the display to show you all of the packages that will be downloaded and installed for your particular installation.  As you can see in Figure 2, updating my Visual Studio 2012 Ultimate installation will cause the installer to download an additional 775MB of data during the install.  If I had Visual Studio Premium the download would be smaller and if I had Visual Studio Pro, it would be even smaller yet. So the architecture of a small bootstrapper that figures out and downloads only the needed updates is a good one to reduce overall bandwidth, especially in bandwidth constrained environments or countries.

But what if you have to do this to multiple machines?  You are now performing the same download over and over again.  The time-to-download tax is being paid by everyone on the team. Another scenarios is that you might be working in a highly-secure environment and your development machine doesn’t have access to the internet. In this case you absolutely have to get the update from an internet-connected machine and then place it somewhere it can be accessed by the secure PCs (or burn it to disk).

SNAGHTML4fe466

Figure 2: The additional downloads needed to update VS 2012 Ultimate Update 1 to VS 2012 Ultimate Update 2 CTP 4

 

Solution

To allow for this scenario, Microsoft has added a command-line switch option to the installation bootstrapper executable. You can use the /layout parameter to force the installer to download all of the update packages to specified folder.

SNAGHTML664b92

Figure 3: Command-line parameters for VS installs - http://msdn.microsoft.com/en-us/library/e2h7fzkw.aspx

When you run the installer with the /layout option, the installer will display a dialog that allows you to select the download location.

SNAGHTML6b9290

Figure 4: Using the /layout option to have the installer prompt for a download location

Clicking the Download button on the installer dialog will start the download.  As you can see in Figure 5, the download pulls all of the packages and stores them in a Packages folder under the folder you specified.  You can also see that it is complete download of all languages.  I am downloading from a machines whose locale is set to en-us but Figure 5 is showing that it is downloading the “Entity Framework Designer for Visual Studio 2012 – JPN”.

SNAGHTML709b95[4]

Figure 5: Downloading installation packages.

When it finishes you will se the “Setup Complete” message. 

Notice that in Figure 2, Visual Studio was telling me that it needed to download an additional 775MB of installation packages to update my machine.  In Figure 6 you can see that using the /layout option actually cause Visual Studio to download 1.66GB of packages. 

SNAGHTML82906e

Figure 6: Download complete. Requires 1.66GB for VS 2012.2 CTP 4

So regardless of whether the machine you are using has VS Ultimate, Premium, Pro or nothing at all, the /layout switch will pull down all of the packages that would be shipped as an .ISO or .MSI. That will allow you to do this process once and be able to update any Visual Studio installation across your company, even localized versions.

Summary

To create a stand-alone, offline installer for Visual Studio or it’s updates from a Web Installer, you can use the /layout command-line option.  This will download all of the installation packages that Microsoft provides for all versions and languages of Visual Studio. This download can then be burned to disk, copied to USB or copied to a network share for distribution.

Using the bootstrapper alone will significantly save on bandwidth since it will determine your VS version and language so that it only downloads those updated packages that you truly need for your installation.

Technorati Tags: ,,,,,,

06 March 2013

TFS 2012 Quick Note: How to add text formatting and line breaks to the DEFAULT text of a work item field

This is a quick note so that I can find this in the future. Smileimage

What:

There are times when you want modify a work item so that the value of an HTML string field, like the Description field on a Requirement, has some default value when a new work item is created. You may also want to put some formatting on some or all of this text.

I was working with a customer that wanted to have a “template” for data security that would help the Business Analysts be more consistent in their requirement documentation. We added some bold template text that would be used as a reminder.  The BA would just add the field name and security requirements in plain text next to the defaulted labels.

SNAGHTMLb8342

How:

To get this effect we set the DEFAULT rule on the underlying HTML field to a string of HTML that will get rendered at runtime.  There are two ways that you can enter the HTML to be rendered, through the Process Template Editor or directly within the work item type definition file.  Please note the caveat at the end of this article so you don’t get burned by a limitation of the work item definition schema.

Using the Process Template Editor

When using the Process Template Editor you need to create a DEFAULT rule for your field. In the FROM field select “value” and in the VALUE field you enter your HTML fragment.  In this editor you can enter your HTML just like you would in Visual Studio.  When you hit OK to close the DEFAULT dialog it will escape all of the special characters in the HTML fragment.

SNAGHTML1632e2

Editing the Work Item Type Definition directly

If you edit the work item type definition directly, you have to escape all of the “special” characters so that they don’t interfere with the raw XML surrounding them.  When uploaded to TFS, the escaped entries will be converted to HTML tags that can be rendered at runtime.

   1:  <FIELD name="Security" refname="MyCompany.Security" type="HTML">
   2:      <DEFAULT from="value" value="&lt;b&gt;Field Name:&amp;nbsp;&lt;/b&gt;&lt;br/&gt;&lt;b&gt;Security:&amp;nbsp;&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;&lt;b&gt;Field Name:&amp;nbsp;&lt;/b&gt;&lt;br/&gt;&lt;b&gt;Security:&amp;nbsp;&lt;/b&gt;" />
   3:  </FIELD>

Caveat

There is one thing that really limits the usefulness of this technique.  There is a limit of 255 characters in the value attribute of the DEFAULT element.  This limit is imposed when you import the work item type definition into the team project, so you have to be aware of this when using the Process Template Editor as the text entered there will be escaped on save and could easily go over the character limit.

22 January 2013

Community TFS Report Extensions open-source reports hits v1.0 milestone

Microsoft ALM MVP Tommy Norman and I have been working on creating a set of reports that fill some of the gaps in the TFS 2010 out-of-box process templates.  The output of this effort is the Community TFS Report Extensions project on Codeplex which was started this past summer but has finally become stable enough to reach the v1.0.0 milestone.

Tommy has crafted a nice write-up on his blog, so please pop over there and take a look then head on over to the project and check out the first two reports.

 

TestPlanStatusReport

Figure 1 - Test Plan Status report

 

SNAGHTML90acb5

Figure 2 – Release Plan report

23 December 2012

VS 2012 - Coded UI Tests (CUIT) Now Automatically Closes Browser or App Upon Test Completion

VS2012Logo

Synopsis

  • Microsoft changed the behavior of Coded UI Tests between Visual Studio 2010 and Visual Studio 2012.
  • The change is that the browser window or app window being used for the test case will automatically be closed after each test case unless you add code to keep it open.
  • In any event, the browser window or app window used will always be closed at the end of a test run.
  • During development you can use a Breakpoint to halt test execution prior to the windows being closed.

Issue

There is a behavior change between Coded UI Tests (CUIT) running in Visual Studio 2010 and Visual Studio 2012 .  In Visual Studio 2010, a test case would leave windows open on the desktop unless they were explicitly closed in code in the test class.  In Visual Studio 2012 , the window of the application under test (browser, WPF app, etc.) is automatically closed whether or not it was closed in code during the test run.  If you are new to CUIT and you only use VS 2012 then you weren’t aware that the behavior changed.  If you have upgraded from VS 2010 then this is something new.

Why did the folks at Microsoft make this change?

This change was added to make it easier to create an maintain test cases because it saves you from explicitly having to close your app window or browser at the end of every test. An automated test run that has many test cases launching browser windows but never closing them will leave the test client’s desktop in a messy state.  I agree that it makes CUIT easier.

So why write a blog post about something you agree with?

The reason for this post is that it changes the way that folks from VS 2010 interact with coded UI tests, specifically if you use a manual test’s Action Recording as the starting point for your CUIT. 
In VS 2010 I would create a new CUIT and use the action script from a manual test case to generate a base test without any validation as in the code below. I’d then run this test to make sure everything worked as expected.  At the end the browser would close.
   1:  [TestMethod]
   2:          public void KioskSmokeTest()
   3:          {
   4:              // To generate code for this test, select "Generate Code for Coded...
   5:              // For more information on generated code, see http://go.microsoft...
   6:              
   7:              this.UIMap.StartDinnerNowKiosk();
   8:              this.UIMap.ExerciseUI();
   9:              this.UIMap.CloseKiosk();
  10:          }
Figure 1: Basic coded UI test that explicitly closes the app under test

Now I need to add some validation to my test.  Normally I would just comment out the line that closes the windows, in my example this.UIMap.CloseKiosk() and re-run the test.  This would leave the app window open and the app would be in the correct state for me to add validations. 
   1:  [TestMethod]
   2:          public void KioskSmokeTest()
   3:          {
   4:              // To generate code for this test, select "Generate Code for Coded...
   5:              // For more information on generated code, see http://go.microsoft...
   6:              
   7:              this.UIMap.StartDinnerNowKiosk();
   8:              this.UIMap.ExerciseUI();
   9:              //this.UIMap.CloseKiosk();
  10:          }
Figure 2: Basic coded UI test that is supposed to leave the app window open at the end
My example is fairly simple, but what if the ExerciseUI() method actually navigated through 4 or 5 screens and added test data. In this case, my process has allowed the test to perform all of the data entry and I am assured that the app is in the correct state for my validations.  This saved me a lot of work and headaches.
In VS 2012, this behavior isn’t the same.  The CloseKiosk() method is no longer needed as the test engine will automatically close the app between test cases unless told to keep them open.  In effect, the first code example is now equivalent to the second one.

But I liked the old behavior, is there a workaround?

Your only option is to set a breakpoint on the last executable line within your test case and then go to Test View and right-click on the test’s name then select Debug Selected Tests.  When the breakpoint gets hit, press F10 to let the last executable line run then just stop debugging.  That will leave your app in the correct state and you can now use the Coded UI Test Builder to create your Assertions.
SNAGHTML1fe8b15b
Figure 3: Use a breakpoint and debug your test to get to the right app state for validation
SNAGHTML1fe63578
Figure 4: Stop debugging when you have finished execution of all of the preparatory steps

What if I chain test cases together and assume that the app stays open between tests?
Some folks write completely self-contained tests like my KioskSmokeTest above.  Other folks have more complex needs and write tests that get run in a specific order, each collaborating to setup the state of a system and then performing validations. This can be called “chaining tests”.
If you have chained tests, the new behavior will break your test runs since the application under test gets closed after each test case is run.  Microsoft has added some new flags that can be set (depending on app platform) to tell the test engine to leave your app alone between tests cases in a single test run.
If your target app is browser-based, you can tell the testing framework to leave the browser open at the end of the test case by setting the BrowserWindow.CloseOnPlaybackCleanup property to false (Line 5 below).
   1:          [TestMethod]
   2:          public void VerifyValidDefaultSearchTest()
   3:          {           
   4:              //Leave the browser open            
   5:              this.UIMap.UIDinnerNownetWindowsIWindow.CloseOnPlaybackCleanup = false;
   6:   
   7:              this.UIMap.StartvalidsearchParams.UIDinnerNownetWindowsIWindowUrl                                                = "http://WebTest/DinnerNow/Default.aspx";   
   8:              this.UIMap.Startvalidsearch();
   9:              this.UIMap.ClicktheFindbutton();
  10:          }
Figure 5: Use CloseOnPlaybackCleanup to keep the browser open


The Microsoft Visual Studio ALM team has a nice blog post describing this in more detail.

If your target app is not browser-based (WPF/WinForms/etc.) then you need to use the ApplicationUnderTest.CloseOnPlaybackCleanup() property.


Note: There is a bug in VS 2012 RTM that causes ApplicationUnderTest.CloseOnPlaybackCleanup() property to be ignored.  This bug is fixed in VS 2012 Update 1.


Unfortunately the ApplicationUnderTest object isn’t as easy to access as the BrowserWindow objects.  To make this work you will have to capture the instantiation of your app in the UIMap.Designer.cs file and store the reference in a variable that can be seen from your test methods.
Below you see the code that was generated in the UIMap for my application.  This code launches the DinnerNowKiosk application and uses a local variable to store the handle to the app.  Once the StartDinnerNowKiosk method goes out of scope, the reference is no longer accessible.  Also, you can’t just go and add a call to dinnerNowKioskApplication.CloseOnPlaybackCleanup = false because this is a generated code file so the added code will be lost of the UIMap is regenerated.

   1:          public void StartDinnerNowKiosk()
   2:          {
   3:              ApplicationUnderTest dinnerNowKioskApplication = ApplicationUnderTest.Launch
                                                                     (this.StartDinnerNowKioskParams.ExePath,
                                                                      this.StartDinnerNowKioskParams.AlternateExePath);
   4:          }

Figure 6: The generated application launch code in the UIMap.designer.cs file
Instead you have to use the UIMap.cs partial class to add your new startup code.  Just copy the StartDinnerNowKiosk() method into the partial class and set the CloseOnPlaybackCleanup property to false.
   1:      public partial class UIMap
   2:      {
   3:          static ApplicationUnderTest dinnerNowKioskApplication_persistent = null;
   4:   
   5:          public void StartDinnerNowKiosk_Persistent()
   6:          {
   7:              if (null == dinnerNowKioskApplication_persistent)
   8:              {
   9:                  dinnerNowKioskApplication_persistent = ApplicationUnderTest.Launch                                                                      (this.StartDinnerNowKioskParams.ExePath,                                                                       this.StartDinnerNowKioskParams.AlternateExePath);
  10:                  dinnerNowKioskApplication_persistent.CloseOnPlaybackCleanup = false;
  11:              }
  12:          }
  13:   
  14:      }

Figure 7: The new app launch code from the non-generated partial class in the UIMap
And then change your test to call the new app launcher method.
   1:      [CodedUITest]
   2:      public class KioskSmoke
   3:      {
   4:    
   5:          [TestMethod]
   6:          public void KioskSmokeTest()
   7:          {
   8:              this.UIMap.StartDinnerNowKiosk_Persistent();
   9:              this.UIMap.ExerciseUI();
  10:          }
  11:   
  12:          [TestMethod]
  13:          public void KioskSmokeTest2()
  14:          {
  15:              this.UIMap.StartDinnerNowKiosk_Persistent();
  16:              this.UIMap.AdditionalSteps();
  17:          }
  18:      }

Figure 8: The updated tests that call to the new app launcher.
In the example above, the StartDinnerNow_Persistent() method is called from each test case because we don’t know the order these test will be run. If you need to have the tests run in a specific order then you need to create an additional test method that calls them in the order desired.

Can I keep the app under test open between test runs?

No.  The app/browser is launched by the test agent process (QTAgent).  At the end of a test run QTAgent is shut down, so any child processes are also shut down. I have confirmed this behavior in VS 2012 RTM and VS 2012 Update 1.

Resources

MSDN: BrowserWindow class - http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.browserwindow.aspx
MSDN: ApplicationUnderTest class - http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.applicationundertest.aspx
MSDN:
Visual Studio 2012 Update 1 Download - http://www.microsoft.com/en-us/download/details.aspx?id=35774
Visual Studio 2012 ALM Blog: Coded UI Test: Why does application close after each test in Visual Studio 2012? - http://blogs.msdn.com/b/visualstudioalm/archive/2012/11/08/using-same-applicationundertest-browserwindow-across-multiple-tests.aspx

11 June 2012

Team Foundation Service is open to the public (and free!)

SNAGHTML80a046dThe Visual Studio Team has hit another major milestone in the evolution of Team Foundation Server.  Back at the BUILD conference last year they announce a hosted TFS offering called Team Foundation Service.  This hosted solution brings TFS based Work Item Tracking, Version Control and Automated Build through a browser and is connectable from Visual Studio just like an on-premises deployment of Team Foundation Server.  Use of the service was limited to those few that were able to get their hands on an Invitation Code.  This was done primarily to allow for a slow ramp-up in users of the service to help find and remedy scalability problems.

“Since we announced the Team Foundation Service Preview at the BUILD conference last year, we’ve limited the onboarding of new customers by requiring invitation codes to create accounts.  The main reason for this has been to control the growth of the service to make sure it didn’t run away from us and end up with a bad user experience.  In this time period, we’ve continued to work on our infrastructure, performance, scale, monitoring, management and, of course, some cool new features like cloud build. ”   - Brian Harry

Today, Brian Harry announced that there is no longer the need for an Invitation Code.  The Service is now open to the Public.  This means that they are confident in the service’s ability to handle the load as well as their ability to monitor activity and upgrade the service with little disruption to the global user community.

They are still offering the service without charge and while they get the final pieces in place to offer a complete commercial service.

“The service will remain in “preview” for a while longer while we work through additional features like data portability, commercial terms, etc but the terms of service support production use, the service is reliable and we expect to carry all of your data forward into production. ”  - Brian Harry

Brian has an excellent walk-through on how to get access to the service and begin playing with the service, the cloud-hosted build servers and the new Azure continuous deployment features.

Brian’s complete post can be found at http://blogs.msdn.com/b/bharry/archive/2012/06/11/team-foundation-service-preview-is-public.aspx

07 May 2012

How do I know if I have all of the Visual Studio 2010 Updates?

QuestionMarkWhenever I go to a customer site to perform a TFS installation or upgrade, one of the questions I invariably get from the IT team is “What has to be installed on everyone’s machines to use TFS?  I currently keep a list of handy-dandy blog posts and OneNote notes updated to answer just this question.

Other folks in the TFS space have also come across this question.  One of then, Terje Sandstrom (Visual Studio ALM MVP), has decided to do something about it.  He has written a tool that helps answer this question.  Best of all, it is a Visual Studio plugin.

You can read about this tool on his blog.

After reading his blog I followed the link to the Visual Studio Gallery to do the installation. Once installed, I fired up Visual Studio 2010 and used the new Help | Version Info menu item.

SNAGHTML23786ed3

It brought up a dialog that shows the status of the Visual Studio installation on my development laptop.

SNAGHTML23796e85

Hmmm…

Looks like I’m a bit behind the times.  Luckily Terje has added a link to the update I’m missing which is the Visual Studio 2010 SP1 Team Foundation Server 11 Compatibility GDR.

After a quick install, I re-ran the Version Info tool and voila, I’m up to date on Visual Studio 2010!

SNAGHTML238445ff

Thanks to Terje for creating this handy little add-in.

Question mark pic by Leo Reynolds.

19 April 2012

Visual Studio 2010–New and little-know features–Part 5–Better Unit Tests

lego_explorerTable of Contents for this series.

I occasionally give a talk about “Driving Quality through the Development Process”.. One of the things I try to drive home with developers is that you can’t test for software quality, you have to build it in from the start.  One of the ways you can do this is to write a good set of Unit Tests. 

For those not familiar with the term, here’s a thorough definition that I like:

“Unit Testing is a level of the software testing process where individual units/components of a software/system are tested. The purpose is to validate that each unit of the software performs as designed.

A unit is the smallest testable part of software. It usually has one or a few inputs and usually a single output. In procedural programming a unit may be an individual program, function, procedure, etc. In object-oriented programming, the smallest unit is a method, which may belong to a base/super class, abstract class or derived/child class. (Some treat a module of an application as a unit. This is to be discouraged as there will probably be many individual units within that module.)”    
                                    - Software Testing Fundamentals –
Unit Testing

My personal definition is a bit simpler:

“Unit tests are small pieces of code testing small pieces of code”

The really great thing about unit tests is that they pay for themselves over and over again.  There is an up-front cost to writing the tests but it saves you significant time and therefore money over their lifetime. This is described on ExtremeProgramming.org:

“The biggest resistance to dedicating this amount of time to unit tests is a fast approaching deadline. But during the life of a project an automated test can save you a hundred times the cost to create it by finding and guarding against bugs. The harder the test is to write the more you need it because the greater your savings will be. Automated unit tests offer a pay back far greater than the cost of creation.”
                                    - Extreme Programming – Unit Tests

Another great thing is that Unit Tests aren’t just for folks doing Agile development processes. They are equally applicable to teams doing Traditional software development practices.

For the rest of this article I’m going to assume that you are writing Object Oriented code.  I’m also going to assume that your definition of a Unit is the same as mine, namely that it is a Method. 

Ok, great! We write code that tests code. So that brings up a few questions…

  1. How many tests do I need to write for each “unit” (method)?
  2. How can I tell which logic paths my tests aren’t covering?
  3. How do I know what test to write if I don’t have enough?
  4. I have lots of legacy code and no tests, how do I start?

Let’s look at each of these questions in turn.


Q1: How many tests do I need to write for each “unit” (method)?

The answer here is “as many as are required to fully cover that method”. Not a really profound answer, huh?  What I mean is that there has to be a certain “minimum” number of tests to cover my method’s behavior.  Basically I want to be able to write enough tests to cover the “happy path” through my code. How many test is that?

To find that number all we have to do is run the Code Metrics tools in Visual Studio and look at the Cyclomatic Complexity metric for our method.

Cyclomatic Complexity can be defined as the number of decisions that are made within our source code. Another way to put it is to say that it is the number of distinct paths through a given piece of code.

So we have a tool that gives us a count of the “distinct paths” through our code. Guess what? Those “distinct paths” are the “happy path”. Look at the following example.

NOTE: You can click any image to display it at it’s original size.

SNAGHTML6e98e6 

The ShoppingCart class has 3 overrides for the AddItem() method.  The first 2 versions call the third version passing in additional default parameters. Since the first two only make a single call out they have a Cyclomatic Complexity of 1.  They only have a simple “happy path”.

The third AddItem() method does all of the real work.  As the diagram shows, the Code Metrics for this method show that it has a Cyclomatic Complexity of 5.  There are 5 basic paths through this code.

Important!: Cyclomatic Complexity does not show the total number of tests needed, just the minimum.  It does not account for boundary conditions and the like.  It is just a basic metric of complexity that we can use to get a handle on our testing.

This leads us nicely into the next question…


Q2: How can I tell which logic paths my tests aren’t covering?

So let’s say that you have the AddItem() method with a cyclomatic complexity of 5 and you want to start writing tests for it.  How do you know you’ve written the correct tests to cover the happy path?  I know I need a minimum of 5 unit tests, but how can I tell which paths have been tested and which haven’t? 

To answer this question we want to bring in the Code Coverage tool in Visual Studio.  Code Coverage determines how much of your code is being exercised by your unit tests.

To enable Code Coverage you need to do four things:

  • First, turn on Code Coverage in your .testsettings file.
    • Open the local.testsettings file in the Solution Items folder in your SolutionSNAGHTML7aadcd 
    • Navigate to the Data and Diagnostics tab and check the box next to Code Coverage.

SNAGHTML7e21e4 

    • While the Code Coverage entry is selected, the Configure button will be enabled.  Click on it to open the Code Coverage Detail dialog.

SNAGHTML81e86d 

    • In the Code Coverage Detail dialog, select the assemblies that you wish to collect against.  This is usually all of your custom assemblies. We generally don’t collect coverage data on the unit test assemblies, but you could if you had a need.
    • You can click Ok then Apply and Close to close the dialogs. 

 

  • Second, tell Visual Studio to use our .testsettings file.
    • In the Visual Studio menus, select Test –> Select Active Test Settings –> Local (Local.testsettings)

SNAGHTML867f6e 

  • Third, run our unit tests in Visual Studio
    • Open the Test View window to show the tests in our Solution. From the menu select Test –> Windows –> Test View

SNAGHTML8ca5c3 

    • In the Test View pane, select one or more tests and click the Run button.  This will launch the Test Results window.

SNAGHTML933832 

    • When the tests are finished running, click on the Show Code Coverage Results button in the Test View.

SNAGHTML970485 

    • This will bring up the Code Coverage Results window.  From here you can drill down to the methods that interest you. Once there you can see how much of the code is covered.

SNAGHTMLacb4e0

    • In the example above, the AdjustQuantity() method (yellow highlight) had zero blocks touched by the test run.  This shows up as a red highlight over the lines of code that were not exercised.  The ClearItems() method on the other hand have every block touched by the tests that were run.  This does not indicate that every possible test was run for this block of logic, only that all of the lines of code were hit. 

Q3: How do I know what test to write if I don’t have enough?

The Code Coverage tools have the ability to color your code to visually indicate which paths weren’t hit by your tests in that run. 

  • Turn on code coloring by clicking on the Show Code Coverage Coloring button on the Code Coverage Results toolbar.

SNAGHTML9d2001

  • It is possible to have a partially covered method. The EntityBase() constructor below was tested for a case where the passed parameter was an instantiated object, but no test was run that checked for a null object being passed.

SNAGHTMLa5e053


Q4: I have lots of legacy code and no tests, how do I start?

This is an easy one.  Just write your first test. Smile

To help with this process here are some things that I’ve used with my own code to help me get unit testing started.

Feathers-WorkingEffectivelyBook: Working Effectively with Legacy Code by Michael Feathers

“Get more out of your legacy systems: more performance, functionality, reliability, and manageability

Is your code easy to change? Can you get nearly instantaneous feedback when you do change it? Do you understand it? If the answer to any of these questions is no, you have legacy code, and it is draining time and money away from your development efforts.

In this book, Michael Feathers offers start-to-finish strategies for working more effectively with large, untested legacy code bases. This book draws on material Michael created for his renowned Object Mentor seminars: techniques Michael has used in mentoring to help hundreds of developers, technical managers, and testers bring their legacy systems under control.

The topics covered include

  • Understanding the mechanics of software change: adding features, fixing bugs, improving design, optimizing performance
  • Getting legacy code into a test harness
  • Writing tests that protect you against introducing new problems
  • Techniques that can be used with any language or platform—with examples in Java, C++, C, and C#
  • Accurately identifying where code changes need to be made
  • Coping with legacy systems that aren't object-oriented
  • Handling applications that don't seem to have any structure

This book also includes a catalog of twenty-four dependency-breaking techniques that help you work with program elements in isolation and make safer changes.”
                                                      - Back cover of book from Amazon.com

This is the one book that I recommend to my customers that are starting out with Unit Testing.  It has practical advice and techniques on how to make untestable-code testable. 

Tool: Pex and Moles from Microsoft Research

“Pex and Moles are Visual Studio 2010 Power Tools that help Unit Testing .NET applications.

  • Pex automatically generates test suites with high code coverage. Right from the Visual Studio code editor, Pex finds interesting input-output values of your methods, which you can save as a small test suite with high code coverage. Microsoft Pex is a Visual Studio add-in for testing .NET Framework applications.

The great thing about Pex is that it will generate test cases for all of your boundary conditions.  It is very thorough.  In fact, if your code can pass a full set of Pex-generated tests, it is robust indeed. Smile


Summary

So to wrap it all up…

  • You want to write unit tests to save yourself from injecting bugs into existing code while making changes or refactoring code. 
  • To determine the minimum number of unit tests for a given method, run the Code Metrics on your assembly or Solution and review the Cyclomatic Complexity metric for your method.
    • Cyclomatic Complexity does not give the total number of tests needed.  It does not take into account boundary conditions for a given algorithm or formula, only the decision points in the code.
  • To determine how much of your code is being exercised by your unit tests, turn on Code Coverage and review the metrics for your methods.
  • To visually determine which code paths weren’t hit in a method, turn on Code Coverage Coloring.
  • If you don’t currently have any unit tests, start by writing one, then one more, then one more.

 

 

Table of Contents for this series.

 

14 April 2012

Visual Studio 2010–New and little-know features–Part 4–Code Snippets

SNAGHTML14b76cTable of Contents for this series.

Code Snippets

Code Snippets have been around since Visual Studio 2005 so I’m amazed when I show the functionality to developers that have been using Visual Studio for years and they tell me they have never seen it.

Code Snippets are feature of Visual Studio that allow you to add small pieces of code to your project using shortcuts.  This allows you to add common code elements like Property Declarations or Class Definitions, basically things that you have to type all the time to make your programs run but are pure drudgery.

So let’s say you want to create a new property on your class with a backing private variable.  This code is exactly like the thousands of other properties you’ve created over the years.  You could copy one of the other variable declaration/property declaration statement pairs that already exist in your project and paste it in then go and make changes to the names, types, etc. to make is unique.  Of course at some time you have probably done this and then forgotten to go back and make the changes thus causing your program to fail compilation, if you are lucky.  If you aren’t lucky, you changed the name but left the old Type or failed to change the Getter or Setter of the Property and your app behaves incorrectly at runtime (harder to find).

To use the Code Snippets, all you have to do is begin typing the shorthand code and IntelliSense will show the code snippets available along with any other appropriate tokens.

SNAGHTML2f0ec0

I can then use the arrow keys to navigate the list until I find the one that gives me a property and backing field.  That snippet’s shorthand code is propfull.  I select that one from the list and then press the TAB key twice to trigger snippet expansion.

SNAGHTML32758d

Once expansion completes for this snippet, you can see that the variable’s type field (the int) has a blue background an has the focus.  You can immediately begin typing in the new Type for this variable.  When you do, the snippet feature will change the type of the Property declaration to match.  Once you change the Variable type you can press the TAB key to move to the Variable Name field.  When you change the name, the statements in the body of the Property that refer to the Variable’s name will also change.  Neat, huh?

SNAGHTML3bdc3b

There are all kinds of snippets that ship in the box with Visual Studio.  To see the list all you have to do is go to the Tools | Code Snippets Manager… menu item.

SNAGHTML3dd4ad

This will bring up the Code Snippets Manager dialog where you can peruse snippets until you collapse from the sheer joy. The code snippets are first categorized by Language.  There are snippets for HTML, T-SQL, JScript, Visual Basic, C#, SQL and XML.  Each language has sub-groupings.

SNAGHTML437c80

You can also create your own snippets for commonly used pieces of code and add them to the My Code Snippets group.

SNAGHTML432961

To wrap up, Code Snippets are great for taking code that is painfully common and mind-numbingly error-prone and turns it into an activity that saves not only keystrokes, but brain cells as well.  I highly encourage you to look at the snippets that are shipped with Visual Studio. If you are interested in creating your own for you or your entire team, look at the structure of the .snippet files that back the existing snippets.

Here’s a link to the root of the MSDN Library documentation on Code Snippets.

Happy Snippeting!

 

Table of Contents for this series.

13 April 2012

Visual Studio 2010–New and little-know features–Part 3–IntelliSense Improvements

Mind-reader

Table of Contents for this series.

Sometimes it’s the most subtle improvements that make the biggest difference to your productivity.  Some of these subtle improvements falls into the “Search” and “IntelliSense” categories.  Visual Studio 2010 improved the way that it helps us save keystrokes and how we discover the capabilities of the classes in our programs.

IntelliSense features

Add using  (C# only)

The Add using feature is pretty cool.  IntelliSense reviews your Type usage.  If it finds that you have declared a variable of a Type that is not a member of one of the declared Namespaces (those listed with a Using statement at the top of the file) it will flag this “unbound type” with the dreaded “red squiggly” with a message of “C#: Unknown type”.  It will then look around all of the referenced assemblies in your project for a matching type. If it finds one or more namespaces that contain a Type with the declared name, it will add a Smart Tag to the unbound type.  In the example below, I’m declaring a variable t of type Timer.  The Timer type is not bound to a known namespace.  The Smart Tag is the blue line below the word Timer.

SNAGHTML102c6c

When you place the mouse over the tag it will expand to give you the option of adding a Using statement to the top of the file, fully-qualify the Type declaration or let it generate a new class or type for you.

SNAGHTML1478e6

This way you don’t have to go hunting around for the namespace reference and then pop to the top of the file to add the Using statement. You can just keep working where you are and let IntelliSense handle it for you without a disruption to your workflow.

MSDN Library – Add using


“Contains” searching

In Visual Studio versions prior to 2010, the IntelliSense system would return matching classes or methods based on a “Starts with” search pattern.  So if you have a variable List<int> numbers and want to get the available methods and properties, you just type the variable name then a period and IntelliSense will display the available properties and methods.  IF you keep typing, the list will be filtered down to those entries that start with the text that you type.  In the example below, I typed numbers.as and the list filtered down to just the members that began with “As”.

SNAGHTML2ae5ec

Starting in Visual Studio 2010, we can now do a contains search, so given the code above, I can write numbers.inde and I’ll see entries that start with inde but also ones that contain inde

SNAGHTML2fc3cc

 

Camel case searching

You can also search for members by typing just the capital letters of the member.  So using the prior example, if I know want to use one of the IndexOf methods, I can type numbers.IO and IntelliSense will show me IndexOf and LastIndexOf members.  This only work because I used CAPITALS.  If I had typed numbers.io it would have brought up members that contained “io” together.

SNAGHTML35bb24

 

Table of Contents for this series.