Visual Studio 2013 Modifies NUnit Project Files

I’ve seen this several times now and an issue was just reported against the NUnit Visual Studio adapter, so I thought I would document my findings on this.

If you run non-Microsoft unit tests in Visual Studio using a test adapter, Visual Studio 2013 will modify the project file and add the following lines.

<ItemGroup>
  <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>

This happens for NUnit, XUnit and other 3rd Party test adapters. This behavior is a new feature of Visual Studio 2013.

In this issue on Connect, Microsoft says it is intentional and provides what I see as a less than ideal workaround.

Posted by Microsoft on 10/24/2013 at 7:38 AM

This behavior is intentional.

To support third-party test frameworks, like NUnit and XUnit, Visual Studio 2012 loaded Test Explorer on solution open, regardless of whether it contained test projects. This added seconds of delay to startup and solution open scenarios for all users, majority of whom don’t use tests.

In Visual Studio 2013, we changed it so that Test Explorer package is loaded only when the solution contains one or more test projects. Test projects are identified in two different ways. Projects created from one of the built-in unit test project templates are identified using project type GUIDs. Other types of projects, such as Class Library project with XUnit or NUnit tests, are identified by Test Explorer during first test discovery and “tagged” with the Service/item.

You can avoid Visual Studio automatically adding the Service/item to your test projects by creating them from any of the built-in unit test project templates. In other words, select the “Unit Test Project” template instead of the “Class Library” template in the New Project dialog.

If you want to change existing projects from a “Class Library” to a “Unit Test Project”, edit the project file and add the following to the first PropertyGroup

<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TestProjectType>UnitTest</TestProjectType>

This isn’t much different than the Service being added, but maybe it is more correct because it is a test project?

Unfortunately, this doesn’t work if anyone is using Xamarin studio since the Unit Test Project type is not supported.

Read More

C# 6.0 – Declaration Expressions

This is another post in the series on the new features that are coming in C# 6.0.

This is a complex name for a simple concept. Until now, if you ever wanted to use an out parameter in a method, you had to declare it before using it.

We’ve all written code like this,

int i;
if (Int32.TryParse(value, out i))
{
    // Use i here
}

Now you can write the much simpler,

if (Int32.TryParse(value, out var i))
{
    Assert.That(i, Is.EqualTo(expected));
}

There are a couple of things to note here. First is that i is only in scope within the if statement. You cannot use it outside the if statement. Second, notice that I used var and that the type was correctly infered as int.

It is also useful for casting. You no longer have to cast an object as something, then check if it is null. You can now do it all within the if statement.

if ((string str = obj as string) != null )
{
    Console.WriteLine(str);
}

It can also be useful for quickly supplying default args for a TryParse.

int x = Int32.TryParse(value, out var i) ? i : -1;

Sweet and simple…

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.

Read More

C# 6.0 – Null-Conditional Operators

This is another post in the series on the new features that are coming in C# 6.0.

This is one of my favourite new features. Have you ever written code like this?

if (line != null && line.Product != null)
{
    total += line.Product.Price * line.Quantity;
}

C# 6.0 introduces the ?. null-conditional operator that short circuits and returns null if anything in the chain is null. This combines really well with the null-coalescing operator allowing you to rewrite the above as follows.

total += line?.Product?.Price ?? 0 * line?.Quantity ?? 0;

This also works with indexers,

var firstProduct = OrderLines?[0].Product;	// Will return null if OrderLines is null

It also works with methods. This will be really handy for triggering events. Instead of writing,

if (OrderChanged != null)
{
    OrderChanged(this, EventArgs.Empty);
}

You will now be able to write.

OrderChanged?.Invoke(this, EventArgs.Empty);

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.

Read More

C# 6.0 – Auto-Property Changes

This is the second in a series of posts on the new features that are coming in C# 6.0. There have been a few small improvements to Auto-Properties.

Auto-Property Initializers

I hinted at this feature in my last post on Primary Constructors. Auto-Properties were introduced way back in C# 3.0, but unlike other members, you had to initialize their values in the constructor.

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public Product()
    {
        Name = "Toy Car";
        Price = 9.99m;
    }
}

In C# 6.0, you can now initialize the properties where they are declared.

public class Product
{
    public string Name { get; set; } = "Toy Car";
    public decimal Price { get; set; } = 9.99m;
}

Getter Only Auto-Properties

You could always declare the setter of an auto-property private or protected to prevent it from being used outside of the class.

public decimal Price { get; private set; }

Now you can omit the setter and it makes the underlying field read-only, so you can only set it in the constructor, or in an auto-property initializer. This is a great feature for creating and enforing imutable classes and also chains well with Primary Constructors.

public class Product(string name, decimal price)
{
    public string Name { get; } = name;
    public decimal Price { get; } = price;
}

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.

Read More

C# 6.0 – Primary Constructors

This is the first in a series of posts on the new features that are coming in C# 6.0. If you want to try out any of these features now, check out the Rosyln compiler and then install the latest CTP of Visual Studio 14 or fire up a VM in Azure with Visual Studio 14 already installed.

To enable the new language features in Visual Studio 14, you will need to hand edit your project file and add the following line to each of the configuration sections,

<LangVersion>experimental</LangVersion>

When you are done, it should look like this,

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <LangVersion>experimental</LangVersion>
  </PropertyGroup>

Previous releases of C# were centered around enabling new language features such as async support in C# 5.0 or Linq in C# 3.0. If I was to pick a theme for C# 6.0, I would say that it is around developer productivity. Most of the features are conveniences that allow you to write code more succinctly and clearly. Primary Constructors are one such feature.

Primary Constructors allow you to declare a constructor and parameters directly on the body of the class or struct instead of explicitly declaring it within the body of the class or struct. For example, prior to C# 6.0 you would write a constructor with parameters like this;

public class Employee
{
    private string _name;
    private string _department;
    private decimal _salary;

    public Employee(string name, string department, decimal salary)
    {
        _name = name;
        _department = department;
        _salary = salary;
    }

    public string Name { get { return _name; } }
    public string Department { get { return _department; } }
    public decimal Salary { get { return _salary; } }
}

There is a fair amount of redundant code in this example. I am creating member variables, assigning them from the parameters of the constructor and returning them from the properties. C# 6.0 simplifies this;

public class Employee(string name, string department, decimal salary)
{
    public string Name { get; } = name;
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

Notice that we no longer have a constructor, it is inline with the class declaration. We also do not have to declare the member variables, the constructor parameters are in scope everywhere within the class. Also, notice the properties are using the new Auto-property initializer syntax which I will cover in my next post.

Primary Constructor Bodies

If you need to add functionality or validation to the Primary Constructor, you do it by adding a body to the Primary Constructor as follows;

public class Employee(string name, string department, decimal salary)
{
    {
        if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("name cannot be null or empty");
    }
    public string Name { get; } = name;
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

Explicit Constructors

You can still add additional constructors to a class with a Primary Constructor, but those constructors must chain to the Primary Constructor by calling the this initializer like this;

public class Employee(string name, string department, decimal salary)
{
    public Employee(string name) : this(name, "Intern", 10000)
    {
    }

    public string Name { get; } = name;
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

Base Initializer

A Primary Constructor must always implicitly or explicitly call a base initializer. If you do not explicitly call a base constructor, it will call the parameterless base constructor. To explicitly call a base constructor, you do it like this;

public class Person(string name)
{
    public string Name { get; } = name;
}

public class Employee(string name, string department, decimal salary) : Person(name)
{
    public string Department { get; } = department;
    public decimal Salary { get; } = salary;
}

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.

Read More