Browse Category: Visual Studio

Why Visual Studio 2015 has changed my life

I’ve been using Visual Studio on an almost daily basis since 2002. Before that, my development tool of choice was Visual Basic 6 (Visual Studio 6). The shift between those two versions felt like using a whole new product at the time. Since then, changes to Visual Studio have been incremental. Microsoft have released a new version every 2-3 years. Visual Studio 2015, however, feels like another significant paradigm shift.

The point of this post is not to outline all the shiny new features, there are official blog posts for that. No. I wanted to tell you how the changes to Visual Studio have directly changed the way I work on a day to day basis.

Visual Studio Tasks (Task Runner Explorer)

The wider web development community has been using task runners, GruntJS and more recently GulpJS, for at least the last few years.

On every project I work on these days, I use TypeScript and SASS. Web essentials previously was responsible for compiling my SASS files, as well as providing linting for both SASS and TypeScript. With the 2015 release, this functionality has been removed. There are a bunch of Mads Kristensen extensions on Visual Studio Gallery that you can install that will add this functionality back in.

However, why not cut out the middle man and set up these tasks yourself?

With tasks you can;
* Automatic SASS/SCSS compilation using Ruby gem (and a watcher that “listens” for changes to files as you make them)
* SCSS and TypeScript Linting, with your own linting configuration files directly in the project (perfect for sharing with team members)
* Better bundling and minification. You can use something like UglifyJS instead of the old ASP .NET bundler (which was horribly buggy!)
* But most importantly, the door is open to a world of possibility.

Tasks enable you to automate tedious repetitive tasks and share those efficiencies easily with your team, whilst not restricting you to a particular subset of tools.

Reduced dependence on ReSharper

I’ve been a fan of ReSharper for a long time and I’ve even blogged about why I can’t work without it. All this said, however, its truth time. I don’t want to have to depend on a third party tool to make my IDE more useful. I want Visual Studio to be awesome enough on its own that I don’t have to install any third party tools to make it usable.

ReSharper introduced the lightbulb menu several major versions ago. The lightbulb menu introduces many code refactorings, such as implement interface, refactor this, and so many I can hardly think. The newly introduced native lightbulb menu in Visual Studio 2015 adds some nice refactorings.

Unfortunately, Visual Studio 2015 doesn’t go quite far enough in this respect, hence why the section is named Reduced dependence on ReSharper. I do expect this feature to get a lot of attention during this release, assuming that the open source community can tap into it easily enough.

Lambda Expressions

Lambda expressions and LINQ were introduced in version 3.0 of the .NET Framework, roughly 8 years ago. Debugging support for lambda expressions was non existent in the first versions, and was incrementally improved over time.

To start off with, you couldn’t debug any method that contained a lambda expression. Not only that, but if any method in the call stack contained a lambda expression, even if your method did not contain a lambda expression, you couldn’t use edit and continue.

Then a subsequent release solved this problem, you could still not edit and continue a method that contained a lambda expression, but the call stack problem was gone.

Now with Visual Studio 2015, you get the full debugging experience. You can edit methods that contain lambda expressions, and you can edit lambda expressions directly, and edit & continue in the same way you could with any other code before. This is a major time-saver.

You’ve never been able to add watches or use the immediate window to debug lambda expressions. With Visual Studio 2015, this is no longer the case. Rejoice.

Summary

Visual Studio has introduced the task runner explorer, which can run tasks on various IDE events (Open, before/after build etc.). This really opens the door to “the rest of the web development world”, where sophisticated tooling exists to automate mundane tasks such as bundling, linting, pre/post processing and so much more. Developers are no longer tied to doing things the Visual Studio way. Other enhancements such as the lightbulb menu and better debugging will save developers time and reduce dependence on third party tooling.

Gulp in Visual Studio

This post walks through the basics of using Gulp in Visual Studio 2013. Specifically, we will add two compile time tasks; one for linting TypeScript files, and another for linting SCSS. You are not limited to using just linters with Gulp, in fact you can do just about anything.

Gulp is specifically good at running repetitive tasks and is widely used in the non-.NET world via the command line. Other common tasks include; minification, compilation and running unit tests. Fortunately for us, some unofficial tools have been developed by Microsoft (specifically, the awesome Mads Kristensen and his dedicated team) which enable us to use Gulp directly inside Visual Studio.

Gulp is JavaScript configuration based, meaning you configure Gulp via a special file called GulpFile.js, which you add to your project.

This post specifically targets Visual Studio 2013, because at the time of writing Visual Studio 2015 hasn’t been released yet (its actually RC at this point). As Microsoft tooling is evolving rapidly at this time, i’ll avoid covering 2015 for now (however, I may revise this post after Visual Studio 2015 is released).

This post is a fork of the popular post Grunt In Visual Studio 2013.

Prerequisites

NodeJS and npm

Gulp is built on top NodeJS and is installed via the Node Package Manager (npm). Both of these tools need to be installed to use Gulp. Check that you already have NodeJS installed, and/or download the latest version. The installation is a trivial process, so I wont document it fully here, but please ensure that the “npm package manager” feature is installed. This feature is selected by default, and it is need to install Gulp (and indeed, any other package).

Gulp

Before we can use Gulp, we must install it globally.

Open a command prompt and type

npm install -g gulp

You might want to get reacquainted with running commands in this way because with the rapid state of change in the industry, development of visual tools is always going to lag behind (even with Microsoft’s new rapid development and deployment ethos, but that’s a whole other discussion).

Task Runner Explorer

This tool will run our Gulp tasks for us. It will parse our Gulp File (which we will create shortly), list our tasks, let us run our tasks individually, and let us bind our tasks to “IDE events” (pre-build, after build, clean & solution open).

To install Task Runner Explorer, go to Tools > Extensions and Updates and type Task Runner Explorer. The first result should by created by Microsoft Corp.

Task Runner Explorer

Task Runner Explorer

Local Gulp

Now that we have the necessary tooling installed, we need to add Gulp to our actual project (and any additional packages we want to use). Packages are controlled using a special file called package.json. This file contains metadata about your project, and the packages its dependent on (and potentially a bunch of other stuff that is out of the scope of this tutorial).

Create a file called package.json at the root of your project, and add the following code;

{
    "name": "Gulp101",
    "version": "1.0.0",
    "devDependencies": {
        "gulp": "~3.9.0",
        "gulp-scss-lint": "~0.2.1",
        "gulp-tslint": "~3.1.0-beta"
    }
}

The file is pretty self explanatory, but if you want a little more information with regards to versioning, see this useful post; Node and npm Version Numbering: Guide and Best Practices.

To save time later, I have also included the other development dependencies. In this case, our TypeScript linter (gulp-tslint) and SCSS linter (gulp-scss-lint). We will configure these shortly.

To install the dependencies, open a command prompt and change the directory to that which contains your newly created package.json and run the following command;

npm install

This will result in a new directory being created, called node_modules, which will contain each dependency.

GulpFile.js

As previously mentioned, Gulp is a JavaScript based task runner. Gulp is configured/controlled using a file called Gulpfile.js. This file is responsible for defining the configuration for each task. You can have many tasks and many aliased groups that run multiple tasks.

For this tutorial we are going to validate our TypeScript and SCSS code quality using linters. Specifically, Gulp has packages called Gulp-TSLint and Gulp-SCSS-Lint (you defined and installed these packages earlier).

Add the following configuration;

var gulp = require('gulp');

var scsslint = require('gulp-scss-lint');
gulp.task('scss-lint', function () {
    gulp.src('/stuff/*.scss')
      .pipe(scsslint());
});

var tslint = require('gulp-tslint');
gulp.task('tslint', function () {
    return gulp.src('stuff/*.ts')
      .pipe(tslint())
      .pipe(tslint.report('verbose'));
});

gulp.task('typescript', ['scss-lint', 'tslint']);

Again, the beauty of Node and Gulp especially is that its pretty simple to understand what’s going on, even for a beginner.

SCSS Lint Task

The minimum configuration required is the path to your SCSS files, using the src method. In the given example, we simply find all the files in a sub directory with the extension *.scss. You can make this more complicated, and recursive, as follows;

Content/**/*.scss

This will recursively find every SCSS file in all folders sitting below the Content folder.

There’s a comprehensive tutorial on how to further refine the configuration on the NPM website. The documentation on GitHub is also excellent.

TS Lint Task

Before you can lint a TypeScript file, you must define some rules that you want to enforce throughout your code-base. You can push this configuration to source control and share with your team for maximum consistency.

If you have Web Essentials installed (and I highly recommend all web developers install this excellent tool) then you can quickly generate a configuration file by clicking Web Essentials > Edit Global TSLint Settings (tslint.json). Clicking this drops a tslint.json file into your Documents folder and opens it directly in Visual Studio, where you can make edits. I highly recommend closing the file, moving it into your solution folder, and adding it as part of your project for easy access later.

If you don’t use Web Essentials are you insane? you can grab a sample configuration file directly from the GitHub source code repository and again I recommend that you add it as part of your project. I won’t go into the ins and outs of each of the TypeScript linting rules, that’s for another time. Just know that you can change them to your hearts content.

As with the SCSS linter, you specify the path of your TypeScript files using the src method. You pass in a string that represents the path of your TypeScript files.

gulp.src('stuff/*.ts')

Final Steps

Add some code

There is just one more step we need to take before running our tasks, we need some code to test!

Add a new SCSS file to your project, and a new TypeScript file. Add the following beautifully written ugly code to the TypeScript file;

module SomeModule {

    export class SomeClass {

        str: string;

        constructor() {
            this["str"] = "Hello, World"
        }
    }
}

The main issues with this code are trailing whitespace, no "use strict", missing semi-colons and access to a property via a string literal. We will let Gulp tell us about these shortly.

Open the task runner

Open the task runner by going to View > Other Windows > Task Runner Explorer.

Select your project (if it is not selected by default) and click the refresh button. Your Gulpfile.js configuration file should be loaded and the alias tasks and individual tasks should be displayed.

You can manually run a task (or set of tasks) by right clicking and selecting Run. If all went well, you should see the following output;

c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp> cmd.exe /c gulp -b "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp" --color --gulpfile "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js" typescript
[13:48:21] Using gulpfile c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js
[13:48:21] Starting 'scss-lint'...
[13:48:21] Finished 'scss-lint' after 5.33 ms
[13:48:21] Starting 'tslint'...
[13:48:21] [gulp-tslint] error (no-string-literal) helloworld.ts[8, 18]: object access via string literals is disallowed
[13:48:21] [gulp-tslint] error (semicolon) helloworld.ts[8, 41]: missing semicolon
[13:48:21] [gulp-tslint] error (use-strict) helloworld.ts[1, 1]: missing 'use strict'
[13:48:21] 'tslint' errored after 68 ms
[13:48:21] Error in plugin 'gulp-tslint'
Message:
    Failed to lint: helloworld.ts[8, 18]: object access via string literals is disallowed, helloworld.ts[8, 41]: missing semicolon, helloworld.ts[1, 1]: missing 'use strict'.
Process terminated with code 1.

Success! Wait what? Oh yes, the task has failed because our TypeScript file has lots of linting errors. Open up the TypeScript file and use the output message to fix each problem. Once done re-run the task again by right clicking and clicking run. Once all issues are resolved, you should get the following;

c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp> cmd.exe /c gulp -b "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp" --color --gulpfile "c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js" typescript
[13:49:12] Using gulpfile c:\Users\jon.preece\Documents\Visual Studio 2013\Projects\gulp\gulp\gulpfile.js
[13:49:12] Starting 'scss-lint'...
[13:49:12] Finished 'scss-lint' after 5.36 ms
[13:49:12] Starting 'tslint'...
[13:49:12] Finished 'tslint' after 64 ms
[13:49:12] Starting 'typescript'...
[13:49:12] Finished 'typescript' after 7.33 μs
Process terminated with code 0.

Bindings

Right clicking and clicking run is a little too manual for my liking, this is an automation tool isn’t it? Alas, the Task Runner Explorer provides you with Bindings. Basically you can hook in to events in the IDE and run your tasks automatically when one of events happens.

Available bindings;

  • Before Build
  • After Build
  • Clean
  • Solution Open

To bind a task to a binding, right click the task (or again, the aliased task) and select Bindings > {An IDE Event of your choice}. In my case, I have chosen Before Build. So when I press Ctrl+Shift+B the tasks are ran automatically.

Note that as far as I know, you can’t fail the build if a task fails at this point. No doubt this is an upcoming feature.

Summary

Gulp is a brave new world for most .NET developers. Tooling is certainly in its infancy (within Visual Studio) at this point, but the awesome power of NodeJS, npm and Gulp can be harnessed with some useful extensions.

Grunt in Visual Studio

This post walks through the basics of using Grunt in Visual Studio 2013.  Specifically, we will add two compile time tasks; one for linting TypeScript files, and another for linting SCSS.  You are not limited to using just linters with Grunt, in fact you can do just about anything.

Grunt is specifically good at running repetitive tasks and is widely used in the non-.NET world via the command line.  Other common tasks include; minification, compilation and running unit tests.  Fortunately for us, some unofficial tools have been developed by Microsoft (specifically, the awesome Mads Kristensen and his dedicated team) which enable us to use Grunt directly inside Visual Studio.

Grunt is JavaScript configuration based, meaning you configure Grunt via a special file called GruntFile.js, which you add to your project.

This post specifically targets Visual Studio, because at the time of writing Visual Studio hasn’t been released yet (its actually RC at this point).  As Microsoft tooling is evolving rapidly at this time, i’ll avoid covering 2015 for now (however, I may revise this post after Visual Studio 2015 is released).

Prerequisites

NodeJS and npm

Grunt is built on top NodeJS and is installed via the Node Package Manager (npm).  Both of these tools need to be installed to use Grunt.  Check that you already have NodeJS installed, and/or download the latest version.  The installation is a trivial process, so I wont document it fully here, but please ensure that the “npm package manager” feature is installed.  This feature is selected by default, and it is need to install Grunt (and indeed, any other package).

 

Grunt

Before we can use Grunt, we must install it globally.

Open a command prompt and type

npm update -g npm

As advised by the product documentation, this ensures that you’ve got the latest version of npm before continuing.  Now, run the following command;

npm install -g grunt-cli

You might want to get reacquainted with running commands in this way because with the rapid state of change in the industry, development of visual tools is always going to lag behind (even with Microsoft’s new rapid development and deployment ethos, but that’s a whole other discussion).

 

Task Runner Explorer

This tool will run our Grunt tasks for us.  It will parse our Grunt File (which we will create shortly), list our tasks, let us run our tasks individually, and let us bind our tasks to “IDE events” (pre-build, after build, clean & solution open).

To install Task Runner Explorer, go to Tools > Extensions and Updates and type Task Runner Explorer.  The first result should by created by Microsoft Corp.

Task Runner Explorer
Task Runner Explorer

Local Grunt

Now that we have the necessary tooling installed, we need to add Grunt to our actual project (and any additional packages we want to use).  Packages are controlled using a special file called package.json.  This file contains metadata about your project, and the packages its dependent on (and potentially a bunch of other stuff that is out of the scope of this tutorial).

Create a file called package.json at the root of your project, and add the following code;

{
    "name": "Grunt101",
    "version": "1.0.0",
    "description": "Grunt101",
    "author": "Jon Preece",
    "devDependencies": {
        "grunt": "~0.4.5",
        "grunt-tslint": "~2.3.1-beta",
        "grunt-scss-lint": "~0.3.6"
    }
}

The file is pretty self explanatory, but if you want a little more information with regards to versioning, see this useful post; Node and npm Version Numbering: Guide and Best Practices.

To save time later, I’ve also included the other development dependencies.  In this case, our TypeScript linter (TSLint) and SCSS linter (scss-lint).  We will configure these shortly.

To install the dependencies, open a command prompt and change the directory to that which contains your newly created package.json and run the following command;

npm install

This will result in a new directory being created, called node_modules, which will contain each dependency.

npm install
npm install

Gruntfile.js

As previously mentioned, Grunt is a JavaScript based task runner.  Grunt is configured/controlled using a file called Gruntfile.js.  This file is responsible for defining the configuration for each task, loading the npm tasks, and registering the tasks.  You can have many tasks and many aliased groups that run multiple tasks.

For this tutorial we are going to validate our TypeScript and SCSS code quality using linters.  Specifically, Grunt has packages called Grunt-TSLint and Grunt-SCSS-Lint (you defined and installed these packages earlier).

Add the following configuration;

module.exports = function (grunt) {
    'use strict';

    grunt.initConfig({
        scsslint: {
            allFiles: [
              '*.scss'
            ]
        },
        tslint: {
            options: {
                configuration: grunt.file.readJSON("tslint.json")
            },
            files: {
                src: ['*.ts']
            }
        }
    });

    grunt.loadNpmTasks('grunt-scss-lint');
    grunt.loadNpmTasks('grunt-tslint');

    grunt.registerTask('default', ['scsslint', 'tslint']);
};

Again, the beauty of Node and Grunt especially is that its pretty simple to understand what’s going on, even for a beginner.

SCSS Lint Task

The minimum configuration required is the path to your SCSS files, using the property allFiles.  In the given file, we just look at the root directory of our application for SCSS files, but you can make this more complicated, and recursive, as follows;

Content/**/*.scss

There’s a comprehensive tutorial on how to customize this further to meet your needs over on GruntJS.com.

TS Lint Task

Before you can lint a TypeScript file, you must define some rules that you want to enforce throughout your code-base.  You can push this configuration to source control and share with your team for maximum consistency.

If you have Web Essentials installed (and I highly recommend all web developers install this excellent tool) then you can quickly generate a configuration file by clicking Web Essentials > Edit Global TSLint Settings (tslint.json).  Clicking this drops a tslint.json file into your Documents folder and opens it directly in Visual Studio, where you can make edits.  I highly recommend closing the file, moving it into your solution folder, and adding it as part of your project for easy access later.

If you don’t use Web Essentials are you insane? you can grab a sample configuration file directly from the GitHub source code repository and again I recommend that you add it as part of your project.  I won’t go into the ins and outs of each of the TypeScript linting rules, that’s for another time.  Just know that you can change them to your hearts content.

The files property works exactly the same as for the SCSS linter.  You pass in a string that represents the path of your TypeScript files.

 

Final Steps

Add some code

There’s just one more step we need to take before running our tasks, we need some code to test!

Add a new SCSS file to your project, and a new TypeScript file.  Add the following beautifully written ugly code to the TypeScript file;

module SomeModule {

    export class SomeClass {

        str: string;

        constructor() {
            this["str"] = "Hello, World"
        }
    }
}

The main issues with this code are trailing whitespace, no "use strict", missing semi-colons and access to a property via a string literal.  We will let Grunt tell us about these shortly.

Open the task runner

Open the task runner by going to View > Other Windows > Task Runner Explorer.

Select your project (if it isn’t selected by default) and click the refresh button.  Your Gruntfile.js configuration file should be loaded and the alias tasks and individual tasks should be displayed.

You can manually run a task (or set of tasks) by right clicking and selecting Run.  If all went well, you should see the following output;

C:\Users\Jon\Documents\Visual Studio 2013\Projects\Grunt101> cmd.exe /c grunt -b "C:\Users\Jon\Documents\Visual Studio 2013\Projects\Grunt101" --gruntfile "C:\Users\Jon\Documents\Visual Studio 2013\Projects\Grunt101\gruntfile.js" default
Running "scsslint:allFiles" (scsslint) task
Running scss-lint on allFiles
>> 1 file is lint free
Running "tslint:files" (tslint) task
>> app.ts[14, 3]: file should end with a newline
>> app.ts[9, 19]: object access via string literals is disallowed
>> app.ts[1, 1]: trailing whitespace
>> app.ts[3, 1]: trailing whitespace
>> app.ts[5, 1]: trailing whitespace
>> app.ts[9, 42]: missing semicolon
>> app.ts[2, 2]: missing 'use strict'
>> 7 errors in 1 file
Warning: Task "tslint:files" failed. Use --force to continue.
Aborted due to warnings.
Process terminated with code 3.

Success! Wait what? Oh yes, the task has failed because our TypeScript file has lots of linting errors.  Open up the TypeScript file and use the output message to fix each problem.  Once done re-run the task again by right clicking and clicking run.  Once all issues are resolved, you should get the following;

C:\Users\Jon\Documents\Visual Studio 2013\Projects\Grunt101> cmd.exe /c grunt -b "C:\Users\Jon\Documents\Visual Studio 2013\Projects\Grunt101" --gruntfile "C:\Users\Jon\Documents\Visual Studio 2013\Projects\Grunt101\gruntfile.js" default
Running "scsslint:allFiles" (scsslint) task
Running scss-lint on allFiles
>> 1 file is lint free
Running "tslint:files" (tslint) task
>> 1 file lint free.
Done, without errors.
Process terminated with code 0.

Bindings

Right clicking and clicking run is a little too manual for my liking, this is an automation tool isn’t it? Alas, the Task Runner Explorer provides you with Bindings.  Basically you can hook in to events in the IDE and run your tasks automatically when one of events happens.

Available bindings;

  • Before Build
  • After Build
  • Clean
  • Solution Open

To bind a task to a binding, right click the task (or again, the aliased task) and select Bindings > {An IDE Event of your choice}.  In my case, I’ve chosen Before Build.  So when I press Ctrl+Shift+B the tasks are ran automatically.

Note that as far as I know, you can’t fail the build if a task fails at this point.  No doubt this is an upcoming feature.

Summary

Grunt is a brave new world for most .NET developers.  Tooling is certainly in its infancy (within Visual Studio) at this point, but the awesome power of NodeJS, npm and Grunt can be harnessed with some useful extensions.

Publish your website to an IIS staging environment using Microsoft Web Deploy

One of the simplest and quickest ways to publish your website to a staging environment is, at least in my opinion, using Microsoft Web Deploy.  This post is about how you approach this, a future article will discuss why you probably shouldn’t do this.

Key points;

  1. The remote server should be running Internet Information Services (IIS) 7.0 or later.
  2. You can use the Microsoft Web Platform Installer to install all the extra bits you need to make this work.
  3. You need to set appropriate permissions to allow remote publishing.

Windows Server 2012 R2

On my local machine, for testing purposes, I have a Windows Server 2012 R2 virtual machine which is bare bones configured.

The first thing you need to do is install IIS.  You can do this using the Server Manager;

Open the Server Manager > click Add roles and features > select Role-based or feature-based installation > select the target server > and finally, select Web Server (IIS) and Windows Deployment Services.  Feel free to drill into each item and ensure you have the following selected (as well as whatever the defaults are);

  • Basic Authentication (very important)
  • ASP .NET 3.5 / 4.5
  • .NET Extensibility 3.5 / 4.5
  • IIS Management Console and Management Service (very important)

Once installed, you should be able to open IIS Manager by opening the Start menu, type inetmgr and press enter.

When IIS Manager opens (referred to herein as IIS), you should be prompted to download Microsoft Web Platform installer.  Ensure you do this.  Use the Web Platform installer to ensure you have all the following installed;

  • IIS 7 Recommended Configuration
  • IIS Management Service (should already be installed)
  • IIS Basic Authentication (should already be installed)
  • Web Deployment Tool (The current version is 3.5 at the time of writing, I also like to install Web Deploy for Hosting Servers as well)
  • Current version of the Microsoft .NET Framework
  • ASP .NET MVC 3 (as we will be publishing an ASP .NET MVC website)

I like to do a restart at this point, just to ensure that everything is tidied up (although I don’t think its 100% necessary, just ensure you restart IIS at the very least).

Enabling web deployment

The next step is to “switch on” the web management service.  This will allow remote users to connect up and deploy the website.

For the sake of simplicity, we will use basic authentication.  There are other means of authenticating users, but that is out of the scope of this tutorial.

AuthenticationIn IIS, select the server level node and then select the Authentication module (under the IIS grouping).

Simply right click on Basic Authentication, and the click Enable.

Next we need to configure the web management service to accept incoming connections.  Again, select the server level node, and select Management Service.

If the management service is already running, you need to stop it before continuing.  To do this, go to the Start Menu and type services.msc.  This will open the Services manager.  Search for Web Management Service, right click, and click Stop.  I ran through this process twice from scratch and the first time the service wasn’t running and the second time it was.  I not sure what triggers it to run.

Tick Enable Remote Connections and feel free to accept the default settings for now.  You could always revisit this later.  Click Start on the right hand side to start the service.

Configure your website

I’m sure you’ve done this many times before, so I will not regurgitate the details here.

Add a new website, give it a host name if you like, and specify the physical path (remember this).  Please ensure that you set the application pool to .NET CLR Version 4.0.30319 to avoid errors running the website further down the line.

Set the appropriate permissions for IIS_IUSRS

IIS requires read permissions to access the files that make up your website.  The simplest way is to head over to the physical folder for your website (that path you’re remembering from earlier), right click the folder, click Properties > Security > Edit > Add.  Type IIS_IUSRS then click Check Names.  Click OK, then OK to close the properties windows.

Create a Web Deploy Publish Profile

Finally, you can create a web deploy publish profile (simply an XML file with a few basic settings)  which you can import into Visual Studio to save you the hassle of having to type anything.

imageHead back over to IIS, right click on your website, click Deploy > Configure Web Deploy Publishing.

You can (and definitely should) create a restricted user account and grant permission to publish to that account (either an IIS account of a Windows authentication based account).

Once you have selected a user, click Setup.  A message should appear in the Results text area;

Publish enabled for 'WIN-DLICU73MRD0Jon'
Granted 'WIN-DLICU73MRD0Jon' full control on 'C:inetpubwwwroottestwebsite'
Successfully created settings file 'C:UsersJonDesktopWIN-DLICU73MRD0_Jon_TestWebsite.PublishSettings'

Success! This is your publish profile that you can import into Visual Studio.

Import your publish profile into Visual Studio

To import your publish profile, open your web solution and from the Build menu select Publish [your website].

PublishWebOn the Profile tab, click Import… and browse to the publish profile you just created.  Once imported, switch to the Connection tab and type the password for the account you selected earlier on the Configure Web Deploy Publishing dialog you saw earlier.

If you’re feeling lucky, hit the Validate Connection button.  All should validate properly.  If not, please refer to this little hidden gem from the IIS team to help troubleshoot any error messages you might be receiving.

Browse to your website using the host name you specified earlier (don’t forget to update your hosts file if you are “just testing”) and congratulations, after the initial feels like a lifetime compilation period, all should be good.

Next time you’re ready to publish, simply open the Publish dialog in Visual Studio, go straight to the Preview tab and hit Publish.  No more manual deployment for you my friend!

Summary

The Microsoft Web Deployment tool is a quick and convenient way to publish your website to a staging area for further testing.  You use the web deployment tool to generate a publish profile which can be imported into Visual Studio (saving you the hassle of having to type all that connection info)  and then call that service and pass it a package which will automatically deploy your site to the appropriate folders.

Redefine where NuGet packages get installed

If, like me, you are working on multiple projects that reference the same packages (StructureMap is a great example) you may have noticed that each project has its own version of each package.

In this bite sized post, we will look at how to redefine where your packages get installed.

Root source control folder

Here was my root source control folder before making any changes.

TFS Root Folder

When I dive into each folder, I see a packages folder, which contains each of my packages. Generally I use the same packages across multiple projects. What I would like is to be able to create a folder at the root level, called Library and place all my packages in there.

Achieving this takes a bit of effort at first, but will pay off in no time. Go ahead and create the Library folder at the root level. Then for each project, go into the project folder and add a new file called NuGet.config.

The contents of NuGet.config should match as follows;

<?xml version="1.0" encoding="utf-8"?>
<settings>
  <repositoryPath>..Library</repositoryPath>
</settings>

Your project folder should now look like this;

NuGet Config File

The painful bit

Now to finish the job, you must do the following for each project;

  1. Open the project
  2. Uninstall all the packages (ensuring all the references are removed)
  3. Delete the bin directory
  4. Delete the original packages folder
  5. Re-add each package
  6. Save and build

I hope you find this useful, doing this has certainly tidied up my Team Foundation Server (TFS).

Making NuGet work for your company

NuGet is a package manager tool for the .NET Framework.  NuGet is free, open source, and is supported by Microsoft Visual Studio, as well as several other environments.

NuGet allows you to add packages to your projects, either from the public package gallery or from your own private package gallery.  The latter is, in my opinion at least, somewhat under-utilised and misunderstood in the business world.  This post aims to try to shed some light on how NuGet can work for your company.

Public Gallery

If you haven’t used NuGet before, you really are missing a trick.  NuGet allows you to extend the functionality of your application by adding third party code/tools to your projects.  Most of the projects hosted on the NuGet public gallery are free (and yes, commercial free!), and open source.

You can access NuGet in two ways, either visually using the Library Package Manager or through the Package Manager Console window.

To open the Library Package Manager, click Tools > Library Package Manager > Manage NuGet Packages for Solution…

NuGet Package Manager

To install a package, simply click it and click Install.  You can easily search for packages using the search field (top right).  There are literally thousands of free packages.

Private Galleries (A.K.A Private Repositories)

So what is a private NuGet gallery? A private NuGet gallery is a gallery which you host yourself. The gallery sits either on your local machine, or somewhere on your company network. There’s actually nothing stopping you from hosting your own public gallery either.

So what is the benefit of hosting your own private gallery?  Well this is best answered with a scenario.  Imagine you are developing multiple websites for various clients whereby they have a lot of common code.  You don’t want to duplicate your code, so you create a library and put the shared code inside the library.  Each project would then have a reference back to the library.  This is a very common scenario and is widespread.  But what if your common code lives in another branch in your source code repository?  What if each website has its own branch?  Then every time you update your library you would need to manually merge the assembly into the other branches.  NuGet greatly simplifies this process, as you would simply have to publish and update to your gallery and each website can choose weather or not to update.  Some websites might not want to update, perhaps due to breaking changes.  Each project can decide if it wants to update or not.

Creating a NuGet package

Every good package starts with a good library.  You probably already have a good idea of which libraries you want to turn into packages.  For the sake of this demo, we will be working with a shared library called JPreeceDev.Shared.dll.  This shared library consists of one class, called Repository, and one interface, called IRepository;

public interface IRepository
{
    bool Save();
}

public class Repository : IRepository
{
    public bool Save()
    {
        return true;
    }
}

To create your package, first you’ll need a little command line tool called NuGet Command Line bootstrapper. Once downloaded, you can either add an environment variable for it, or simply point to the full path when inside a command prompt window.

At this stage, there are a few routes you could take, and this really depends on your preferences, internal processes, or source control set up. For the sake of simplicity, I will create a new directory at the same level as my project folder, called “NuGet Packages”. Inside this folder I will create a sub folder called JPreeceDev.Shared, and inside there will live all the components for my NuGet package. You might want to; create a dedicated NuGet packages branch in your source control or add a new folder to your development branch specifically for NuGet packages.

Open a command prompt, switch the working directory to the NuGet packages/your project folder and run the following command;

nuget spec

This will output a very generic Package.nuspec file, which consists of some simple XML. Open the file in your favourite text editor, and edit the XML with some appropriate information. Here is mine as an example;

<?xml version="1.0"?>
<package>
  <metadata>
    <id>JPreeceDev.Shared</id>
    <version>1.0.0</version>
    <authors>Jon Preece</authors>
    <owners>Jon Preece</owners>
    <licenseUrl>http://www.codeproject.com/info/cpol10.aspx</licenseUrl>
    <projectUrl>http://www.developerhandbook.com</projectUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>developerhandbook.com Shared Code Library</description>
    <releaseNotes>First release.</releaseNotes>
    <copyright>Copyright Jon Preece 2013</copyright>
    <tags>jpreece shared</tags>
  </metadata>
</package>

I also like to rename the file so that it is more meaningful to my project. I will rename Package.nuspec to JPreeceDev.Shared.nuspec;

NuSpec

Now you need to bring in your library file. Start by creating a new folder called ‘lib’ at the same level as your nuspec file. Inside there you need to create another folder, which tells NuGet which version of the .NET Framework your library targets. In this case, the .NET Framework 4.5 is targeted by adding a folder called NET4.5;

NET 4.5 Folder

Go ahead and drop your library into that folder.

Next, return to the command prompt and run the following command;

nuget pack

This will output your NuGet package, with the file extension .nupkg. Your simple NuGet package is now complete and you are ready to tell NuGet about your private gallery.

Adding your private gallery to the available package sources list

The next step is to tell NuGet about the private gallery you have just created. That way, when you later come to search for NuGet packages to add to your project, NuGet will know where to look.

Open up Visual Studio, click Tools > Options > Package Manager > Package Tools. Click the “Add” button (top right), give your Package Source a name (in this case, Local NuGet Packages) and set the path back to the NuGet Packages folder you created earlier;

Package Sources

Click Update, then Ok to save the changes. Now fire up the project in which you want to consume the library, open up the Library Package Manager, and notice that your private gallery is now available under the ‘Online’ tab;

Local Packages

To add the package to your project, simply click Install, and accept the license agreement.

Notice that the reference has now been added to your project, and the code within the library can be consumed as normal.

Added Reference

 

Updating

So if you have been following along in Visual Studio, you may be thinking something along the lines of “this is a lot of effort, I’ll just stick with my current process as this is what I am familiar with and I know it works”. Well stick with me, because this is where NuGet really comes into its own… when updating packages.

So lets say its been a while, and you have made some changes to your shared library. You’re happy with your changes and are confident that your library is relatively bug free, so its time to push out an update to all the projects that consume the library.

Fire up the NuSpec file (in this case, JPreeceDev.Shared.nuspec) and increment the build minor version number, and add some release comments. Now copy over your shared library DLL (JPreeceDev.Shared.dll) and fire up the command prompt. Run the NuGet pack command again;

NuGet pack

NuGet creates a new package, which is appended with the new version number;

Updated Package

Fire up your project again, and if you are not automatically prompted to update the package, open up the Library Package Manager and click on the ‘Updates’ tab.

NuGet Showing Update

As you can see, the update is now available for your project. Go ahead and click the Update button to complete the update. The updated assembly has now been added to your project. Easy eh?

Advanced Topics

In this tutorial, we only visited how to create a simple NuGet package. There are more advanced features you can utilise to add additional functionality to your package;

  • Run powershell scripts on both install/uninstall operations
  • Add dependencies to the target project (for example, assembly references)

…and much more.

Summary

NuGet is a package manager tools that allows us to easily add third part assemblies/tools to our projects. NuGet can also automatically or manually update those tools for us so that we always have the latest (or most appropriate) version added to our project. We can host our own NuGet packages in a private gallery and NuGet can serve them up to us in the way we would expect. This is particularly helpful in cases where we have code shared across multiple projects/branches where we don’t want the pain of having to manually update the references to our shared code every time we make a change.