Tag Archives: Visual-Studio-2015

Generating a NuGet package in a localized directory on each build

MSBuild can be a very powerful tool to handle, well, your build process. I will say up front that I haven’t got much experience with it but the little experience I do have, tells me that there are many possibilities to customize your workflow.

The situation that brought me in closer contact with MSBuild is the following: when you create a new project using the Diagnostic with Code Fix template, it will also include a .nuspec file. This file contains the metadata needed to release something on NuGet (name, description, version, release notes, dependencies, etc). It will essentially package your nuspec file into a nupkg file which can in turn be used to publish it onto some feed of your choice. The code in question is the following:

What happens is straightforward: if there is a file called Diagnostic.nuspec and NuGet.exe is packaged with our project, called NuGet.exe and pack the nuspec file into the root directory.

Local feeds

One of the features of NuGet is that it can retrieve packages from different sources and not just the official nuget.org feed. This is particularly interesting because we can also point to a local folder as our NuGet source! Doing so allows us to manually verify everything works with the NuGet package by using it locally and only publishing it after we are satisfied. However I’m not interested in having to create a separate feed for each project (remember that the OutputDirectory specifies the project root folder).

One more restriction to keep in mind: I don’t want to localize my project’s build structure to work on just my machine. Anyone should be able to pull the repo and get started which means I can’t just hardcode a directory in the MSBuild script.

The problem: how do you create a local NuGet feed that gets the latest version of a NuGet package as soon as I build it, in a location of my choice while keeping other devs in mind?

The solution

The solution I came up with (through some nods on SO) is very straightforward: if a certain environment variable is set, use that variable’s value as the outputdirectory. If it’s not set, use the root. This makes sure that by-default, people will have the same behaviour as a clean project. Only when you want custom behaviour, you should change it. I liked this result a lot because it meant that the project could still be pulled and built cleanly without having to do additional configuration steps (nobody likes doing that for a project you haven’t even started yet).

I added an environment variable with key NUGETLOCAL and value "C:\Users\jeroen\Google Drive\NugetLocal\VSDiagnostics" to my user-level system variables. Note that I added quotes around the value!

Environment variables
Environment variables

All that’s left now is adapting the .csproj file to account for this alternative action:

The code speaks for itself: if the value retrieved from the NUGETLOCAL environment variable is not empty (aka: it has a value), use that as outputdirectory. If it’s empty, use the root.

All that’s left now is setting up the local NuGet feed. You’ll notice that I pointed it to the /Google Drive/NugetLocal folder so I’ll do exactly that under Tools -> Options -> NuGet Package Manager -> Package Sources:

Local feed settings
Local feed settings

Using that feed is now a matter of selecting the correct package source in the NuGet package manager and all local feeds from that folder will show up:

Local feed results
Local feed results
Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this

Introducing: VSDiagnostics

I am happy to announce the first release of VSDiagnostics! This project is a group of diagnostics meant for Visual Studio 2015 (and up?) which will help the developer adhere to best practices and avoid common pitfalls.

These are a few examples of the scenarios currently supported:

If statements without braces


String.Empty instead of an empty string


ArgumentException that can use nameof()


A catch clause that catches a NullReferenceException


Throwing an empty ArgumentException


Catching Exception without other catch clauses


And many more!

For the full list, take a look at the Github page. If you have a suggestion in mind or you are interested in contributing, let me know: I want this to be a community powered project. I hope this first release already proves helpful to you and I’m eager to hear your feedback and criticism.

How do I use this?

Simply create a new project using Visual Studio 2015 RC and add the NuGet package! If you don’t find it: make sure you’re also looking in the NuGet V2 package source.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this

Introducing: RoslynTester

When you create a new solution using the “Diagnostics and Code Fix” template, 3 projects will be created:

  • The portable class library which contains your analyzers and code fix providers,
  • A unit test project
  • A Vsix project to install them as an extension

If you look at the 2nd project you will notice that it creates a few files for you from the get-go: classes like CodeFixVerifier, DiagnosticVerifier, DiagnosticResult, etc.
These classes can be used to unit test your analyzers very easily: you pass in your test scenario as a string, specify the resulting diagnostic you expect, optionally provide a transformed code snippet in case of a code fix and that’s it: you’re done.

I was very pleased by what MS provided but it left me with one annoying problem: that testing code will always stay the same unless I change it myself. Often this is an okay scenario but since Roslyn is under active development and the API can still change (and it does), this prevents me from upgrading. When you look at the version of the Roslyn binaries that are provided with that project template, you will notice that they are from Beta-1. At the time of writing, Roslyn has gone past that to Beta-2, RC1 and eventually RC2. Before I realized this, I took to the Roslyn issue tracker with a few issues that apparently couldn’t be reproduced. It was then that I realized that I might have an outdated installation.

When I upgraded from Beta-1 to RC2 (in intermediate stages) I noticed that some breaking changes were introduced: methods being renamed, types being removed, accessibility restricted, etc. This left me the choice between either diving in that code or sticking to an outdated API (with bugs). The choice wasn’t very hard and I managed to get everything working with the RC2 API. However because of the outdated project template I don’t want to have to manually update those files every time (and I wouldn’t want to force you to do it too either)!

Therefore I present to you: RoslynTester!

This small NuGet package is exactly what you think it is: those few classes cleaned up and put inside a NuGet package. Now I (and you) can simply remove the auto-generated test files and instead simply reference this package to get all the testing capabilities. I will try to keep this up-to-date with the most recent Roslyn NuGet package so none of this should be a problem anymore. If I come across scenarios where I can expand on it, I will do that too of course. In case you are interested in contributing something, feel free to take a look at the Github page!

Sidenote: if the NuGet package doesn’t show up in your NuGet browser, go to your settings and enable the NuGet v2 package feed. I’m still figuring out NuGet and for some reason it only shows up there.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this

Getting started with your first diagnostic

With the release of Visual Studio 2015 RC, we also received the pretty much final implementation of the Diagnostics implementation. This SDK allows us to create our own diagnostics to help us write proper code that’s being verified against those rules in real-time: you don’t have to perform the verification at a separate build-step. What’s more is that we can combine that with a code fix: a shortcut integrated in Visual Studio that provides us a solution to what we determine to be a problem.

This might sound a little abstract but if you’ve been using Visual Studio (and/or Resharper) then you know what I mean: have you ever written your classname as class rather than Class? This is a violation of the C# naming conventions and visual studio will warn you about it and provide you a quickfix to turn it into a proper capitalized word. This is exactly the behaviour we can create and which is integrated seemlessly in Visual Studio.

I gave this a go exactly 1 year ago but decided against continuing because there wasn’t a final version of it yet and it was really cumbersome to test. That combined with the fact that it was hardly usable (not many people had Visual Studio 2015 yet) made me wait until it had matured and was properly supported. Luckily, it seems that time has finally come.

The setup

In order to get started you need a few things installed:

You will notice that each of these downloads are specific for the RC version, which is what I’m using at the time of writing. Make sure that you don’t mix up CTP-X, RC and RTM versions since that is bound to create issues.

Creating an Analyzer

Even though the official template says “Diagnostic and CodeFix”, the term “Analyzer” is used equally, if not more, as “diagnostic”. I don’t believe there are hard conventions on this yet so use what you feel more natural. I personally prefer to append “Analyzer” to my.. diagnostics.

In Visual Studio, create a new project (and a solution if needed) using the “Diagnostic with Code Fix (NuGet + VSIX)” template, found under “Extensibility”. This immediately indicates a very useful feature: you will be able to distribute your analyzers using NuGet and/or you can choose to distribute them as an installable extension instead. This makes it very easy to deploy in your environment and share it with others should you want to.

Create the project
Create the project

Now on to the real work: we will create an analyzer that shows a warning when we throw an ArgumentException without passing a parameter to it. The use of this is that we will make sure that we’re never just going to throw such an exception without specifying what argument is being annoying in the first place.

After your template is created you will notice 3 projects in the solution: a portable class library which contains your analyzers and code fix providers, a test project and an extension project. You can ignore the latter one and we’ll focus on the first two.

When you look at your analyzer you see an entire example for you to start from. The nature of the diagnostic we will create however is such that we will analyze a syntax node, not a symbol. The code we implement is very straightforward:

I’ve disregarded globalization because it is an extra hurdle to readability and I don’t expect my project to ever become popular enough that it warrants different languages to be supported. Aside from that you’ll notice that I also used a lovely Expression Body for the SupportedDiagnostics method.

The first thing I did was register my analyzer on a a syntax node, a throw statement to be precise. This evidentely means that each time a throw statement is encountered when the tree is walked through, my analyzer will execute.

The actual implementation is very straightforward:

  • Verify the node is a throw statement
  • Verify the expression creates a new object
  • Verify the new object is of type ArgumentException
  • Verify there are no arguments passed to the constructor

And that’s it. If these 4 conditions are true, I believe there to be an empty ArgumentException call and I report a warning on that location.

Testing the analyzer

If you now set the Vsix project as your startup project and press the big green “Start” button, a new Visual Studio instance will be launched. Use it to create a new project and you will notice that your analyzer is included. You can now let yourself loose on all sorts of scenarios involving ArgumentExceptions!

However I wouldn’t be me if I didn’t look into unit testing instead. Luckily, this is very easily done with this release. In fact, it’s so easy that there’s really not much looking into: you create a test class that inherits from CodeFixVerifier, override the GetCSharpDiagnosticAnalyzer and GetCSharpCodeFixProvider as needed, you write source code in plain text and you use the helper functions VerifyCSharpDiagnostic and VerifyCSharpCodeFix to assert whether or not a diagnostic/code fix should occur at the given position. If nothing should occur you just pass in the source code as a string and if you do expect something, you pass in a DiagnosticResult.

In code:

That’s how easy it now is to create your own slim Resharper. Your code is evaluated against your rules as you type, you can write them yourself very easily and you can export them as needed. I will definitely port the few analyzers I created as a test last year and expand it with many others I can think of and I encourage you to do the same (or contribute).

For more information on how to get started with these analyzers I recommend a couple of resources:

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrShare on Google+Share on RedditFlattr the authorDigg this