Build Service in Visual Studio Team Services

First time I have tried TFS Build feature a few years ago and that was on hosted TFS 2010 version. And I hated it. It all was confusing XML, to change a build template I had to create a Visual Studio Project. I barely managed to get NUnit tests to run, but could not do any other steps I needed. So I abandoned it. Overall I have spent about 3 days on TFS. Then I installed Team City and got the same result in about 3 hours. That is how good TeamCity was and how poor was TFS Build.

These days I’m looking for ways to remove all on-prem servers, including Source Control and Build server. (Yep, it is 2016 and some companies still host version control in house)

Visual Studio Team Services Build – now with NuGet feed

Recently I’ve been playing with Visual Studio Team Services Build (used to be Visual Studio Online). This is a hosted TFS server, provided by Microsoft. Good thing about it – it is free for teams under 5 people. At the end of 2015 Microsoft announced a new Package Management service. So I decided to take it for a spin. So today I’ll be talking about my experience with VSTS build, combined with Package Management.

Disclaimer

I’m not associated with Microsoft, nor paid for this post (that’s a shame!). All opinions are mine.
VSTS is moving fast with new features popping up every other week. So information in this post might become out-of date. Please leave a comment if things don’t work for you as expected here.

C# package in private NuGet feed

Today I actually need to create a C# library for internal use and publish it to a private NuGet feed. So I’ll write down my steps for future generations.
For the purposes of this guide, I presume you already have VSTS project and have some code in it. You also know what CI is and why you need a build server.

Continue reading

Targets that should be in you ASP.Net MVC *.csproj file

As far as I know next version of ASP.Net is going to abandon MSBuild and build projects differently. Can’t wait for this to happen!

But for now we are still stuck with horribleness of XML and MSBuild (did I tell you I hate MSBUILD with passion?).

When I start a new MVC project, I add extra bits of MSBuild script into *.csproj file.

Missing Content files

First element is to fail a build if some of *.js or *.css files are missing from the project folder. This happened before – somebody in a team forgets to check-in a new file site.css – build server is silent for this matter. Only until somebody gets latest version of the project, builds, looks on it in a web-browser and notices that styles are not right, then the digging starts happening.

So here is the snippet to add to your project:

<Target Name="ValidateContentFiles">
    <Error Condition="!Exists(%(Content.FullPath))" Text="Missing Content file [%(Content.FullPath)]" />
</Target>

Simples – issue error if some of the “Content” files not on the hard-drive.

*.cshtml files marked as “None” for Build Action

This happened to me a few times now: to create a new view you copy-paste existing file, rename the file and change the internals. This is much faster than having to ask Visual Studio to create a new View file for you. The problem starts that sometimes files created this way are marked as “None” in Build Action (Right click on the file, Properties -> Build Action). This is very subtle change and not discoverable on development stage. But when you deploy the application to a server, files marked as None are not packed into the package. And your server now missing these view files. And only when somebody navigates to that missing page – that’s when you get a nasty exception in your face (hopefully your face, not your customer’s).

To avoid this Stackoverflow actually provided me very good answer (for a change).
So to fail a build on *.cshtml file being marked as None, add this snippet to your .csproj file

<Target Name="EnsureContentOnViews" BeforeTargets="BeforeBuild">
    <ItemGroup>
        <Filtered Include="@(None)" Condition="'%(Extension)' == '.cshtml'" />
    </ItemGroup>
    <Error Condition="'@(Filtered)'!=''" Code="CSHTML" File="$(MSBuildProjectDirectory)\%(Filtered.Identity)" Text="View is not set to [BuildAction:Content]" />
</Target>

I wish these were the default settings in the project template.

Can’t find the valid AspnetCompilerPath

A note to myself, next time I try to do view compilation in msbulid and see exception

Can’t find the valid AspnetCompilerPath

I should either install VS2013 on my build server. Or choose a different version of msbuild.exe:
C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild.exe.

The problem is caused by version mis-match. New msbuild is part of Visual Studio 2013 and not part of .Net framework itself. And by default your PATH variable points to .Net folders where older msbuild is found. So you in your scripts you need to explicitly specify what msbuild you need to use.

Resharper vs Visual Studio

Resharper is becoming more and more monstrous. Soon it will be an IDE in itself and won’t need Visual Studio at all!

When a new 8.1 version was out, I was overly excited with it. Even paid almost 100 quid for a licence out of my own pocket (for my personal use). After using it for 2-3 months, I’m not so happy with it.

Project I mostly work on has some sizeable amount of MVC controllers and views: 180K lines of code excluding code for views. On this codebase R# is choking badly.

Autocomplete

A lot of the times I get very random completion suggestions, even through I almost typed complete name for local variable that was defined a line above. Many times I get some random namespaces added to using block because R# thought I’m done with typing and concluded that I need some random namespace. I’ve disabled Resharper Intelisence and now using native Visual Studio functionality for that. VS does seem to do not a bad job there. Also it is not as automatic as R#, so I need to press Ctrl+Space to get the completion. Yes, extra 2 keystrokes, but that protects you from random crap that R# decides to add to your class.

Go Anywhere

Go Anywhere in Resharper 7 was useful. Most of the times it got me where I needed to. In v8 this is a VERY global search, and order of suggestions is nowhere near how it should be. When I type “web.cofnig” in Go Anywhere box, I expect to see web.config file in root of the project as first suggestion. Not some other auto-generated classes that have web and config in their name somewhere, like MyApp.Web.Infrastructure.AutomapperBootstrap.config. Most of the times the suggestion is bang on, but when it is not, it is so wrong – I don’t know where to start rant about it. Also, why does it offer me auto-generated classes as a first navigation option? (think T4MVC-generated controllers).

Turns out that Visual Studio has it’s own Navigate To option. Usually invoked by Ctrl+,, but probably R# have messed up the keyboard shortcuts for you, so you’ll need to re-assign the mapping again. And navigation in VS is not trying to be very smart, hence getting me to the places I’d like to go.

I’m dependant on Resharper so much, at the moment I can’t work without it. This is bad! I’ll keep adding here native replacements to R# functionality, as I discover them.

Here are the options I’d like to find replacements to:

  1. Renaming of classes and controller actions
  2. Creating of new classes from their name.
  3. Initialise fields from constructor parameters – for IoC injections
  4. … probably another infinite list of functions coming from R#

Run xUnit in hosted Team Foundation Service

Now, as promised my other project is hosted and built on hosted Team Foundation Service and it took me a bit of fiddling before I managed to run NUnit tests on it. However, there is an excellent walk-through how to do that: http://www.mytechfinds.com/articles/software-testing/6-test-automation/72-running-nunit-tests-from-team-foundation-server-2012-continuous-integration-build

Much in the same way you can do xUnit:

  1. Download xunit.runner.visualstudio-x.x.x.vsix from Codeplex.
  2. Change file extension from .vsix to .zip and open with zip archiver.
  3. Copy all xunit.*.dll files to a folder that is mapped to TFS and check them in. I prefer to have these files in /BuildFramework folder

xUnit_VS

  1. Now, pretty much the same as with NUnit set up (If you have not done that before), you need to update settings for Build Controller. In VS go to Team Explorer -> Builds -> Actions -> Manage Build Controllers. And set “Version Control path to custom assemblies” to the folder where you have saved adapters for xUnit:

Build_controller

And you are pretty much done. You can now check in and your xUnit tests will run on hosted TFS (Presuming TFS is set up correctly to run your tests).

Visual Studio 2013 *-package did not load correctly

Today for no reason I’ve faced a quirk from Visual studio: on attempt to connect to TFS I faced with strange error: Page not found.. And projects did load but with bunch of errors, like Microsoft.VisualStudio.Web.PasteJson package did not load correctly and many other saying that other packages did not load correctly.

Quick googling revealed that reinstall of VS helps, but I did not fancy that – too much hassle. Further googling also suggested that runnig as admin devenv /setup from your command line should fix the issue. And it did! Thanks to this answer on SO.

Also there was a suggestion to run devenv /resetuserdata if the above fails. But I have not tried that, because the first option worked for me.

And since I’m talking about devenv, here is the list of all the switches applicable to Visual Studio 2013.

You can see there options like /build or /clean or /rebuild – these do not start up Visual Studio, but rather work as Msbuild – build/clean/rebuild solutions. The more useful flags are

  • /safemode – start VS in Safe Mode. In case one of the extensions messes up big time.
  • /ResetSettings – resets user settings to default
  • /setupForces Visual Studio to merge the resource metadata that describes menus, toolbars, and command groups, from all available VSPackages. Whatever it means, but it fixes problems I’ve described above with loading packages.

Speed up Editing of Cshtml Razor files in Visual Studio: Resharper vs Web Essentials

Lately I’ve experienced a very slow editing on Razor pages in Visual Studio 2013. I had a set of extensions installed, but nothing special: Resharper 8.1, Web Essentials and VSCommands. When I was editing Razor .cshtml file, every keystroke was painfully slow, especially when I was trying to edit C# code there: we have a lot of helpers and html generation tools, our view are almost html-free, only control builders.

Long story short, by disabling extension one by one, I’ve narrowed down the performance issue to Web Essentials setting that tries to auto-format HTML.

To fix that in Visual Studio 2013 go to Tools -> Options; select Web Essentials section and HTML sub-section; and disable Auto-format HTML on Enter:

web_essentials

Test project per production project vs. Single project for all tests

For the last 7-8 months we have rolled a test project per production project. And it worked just fine when we started it. But over this weekend I have collapsed all test projects into one because many test project became a headache. And here are my reasons:

  1. The more projects you have in your Visual Studio solution, the slower VS is. I don’t know why that is, but for half-day I have tried excluding all extra projects and trying working with VS and it was much more snappier and happier. And we had 13 projects in our solution with total number of lines just above 133K (not including JS and HTML). And VS memory consumption have reduced in half when I went from 13 to 5 projects – that also made my PC happier.
  2. Package management on one test project takes 10 times less than on 6 projects. Every time you get new version of Moq, you need to update all your test projects. Or just one.
  3. Every time your production project gets a new dependency, you need to add that to your test projects. Or just one project.
  4. Did I tell you, dependency management gets 10 times easier with single test project?
  5. Less projects => less maintenance costs. And you don’t want to maintain test projects.

And what is the point of having a test project per project? Please somebody tell me! I have started that because I read that in books. Well, the books are wrong! There is no benefit of having test-project-per-project. Only headaches and slow Visual Studio.

NUnit test method snippet

As I develop, I write quite a few unit tests. And to speed up the development I’m using code snippets. One of them most useful snippets for testing is to create test method. So I’ve came up with ntest snippet that will give you decorated public method.

Type ntest

ntest snippet for NUnit test method

and hit TAB. And you get ready test method:

Test method decorated and ready to go

Then you’ll need to type the test name and hit enter – your cursor will be placed inside of the curly braces. Here is the snippet file: ntest.snippet

To install the snippet in Visual Studio, you’ll need to go Tools -> Code Snippets Manager. Pick a folder where you would like new snippet to be stored. Click “Import..” button and point to the unzipped ntest.snippet file. Done. Profit!

More about creating your own snippets read on Microsoft Walkthrough: Creating a Code Snippet
Code Snippets Schema Reference

Remove empty comments in VS2012

To remove empty comments form Visual Studio 2012 use this regular expression:

^(?([^\r\n])\s)*//\r?$

and replace all the matches with nothing. Just make sure you are only searching in *.cs files. Because this can mess up other files, like JavaScript

Apparently whitespace is matched by (?([^\r\n])\s) in VS search and replace tool. While \s is a white space including new line and carriage return character

Reference to Visual Studio 2012 regular expression search is here: http://msdn.microsoft.com/en-us/library/2k3te2cs.aspx