post image

Setting up a TypeScript – RequireJS – Gulp – MVC 6 Web Project in Visual Studio 2015 RC

Setting up a new Web Project in Visual Studio 2015 is easy!
Setting up a project and making TypeScript and RequireJS work together – not all that easy.
Hopefully this step-by-step guide will help you get up to speed quickly. We’re taking it from an empty web project to setting up MVC 6, TypeScript compilation with Gulp, retrieving definition files and finishing off with a module load with RequireJS.

Disclaimer: Please note that this article was written using Visual Studio Enterprise 2015 RC using the beta-4 bits. So if you are using a different version, some of the information in this article will not be accurate.

1. Creating a new Web Project

Open Visual Studio and:

  • File-New-Project (Ctrl-Shift-N)
  • Select ASP.NET Web Application
  • Under ASP.NET Preview Templates select Empty

2. Add MVC to the project

First we need to add two more packages to the solution. Add the following to the dependencies section of project.json:

    "Microsoft.AspNet.Mvc": "6.0.0-beta4",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta4"

No we need to add some code to Startup.cs:

   public class Startup
        public void ConfigureServices(IServiceCollection services)

        public void Configure(IApplicationBuilder app)
            app.UseMvc(routes =>
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

If you are unfamiliar with ASP.Net 5, we’ve just enabled MVC, enabled use of static files and setup a route handler for incoming requests.

Setup of the MVC parts

Add a folder to the project root named Controllers and one named Views. Inside the Views folder, add a folder named Home.
Add a HomeController.cs file to the Home folder, add the following code:

using Microsoft.AspNet.Mvc;
namespace TS_require_Web.Controllers
    public class HomeController : Controller
        public IActionResult Index()
            return View();

Add a cshtml file named Index.cshtml to the Home folder and add some html markup, like for ex:

<!DOCTYPE html>
    <title>TypeScript Module loading with RequireJS</title>
    <h1>Setup project</h1>

Given everything is setup correctly now, it should be possible to run the project using the web command or with IIS Express.

3. Adding NPM packages

Now we need to add a a new file to retrieve some NPM packages needed. In the the project root create a file named: package.json (Ctrl-Shift-A -> NPM configuration file)
Open the file and under devDependencies add references to some needed packages, making the devDependencies section look like the following:

"devDependencies": {
    "gulp": "^3.9.0",
    "rimraf": "^2.4.0",
    "gulp-typescript": "^2.7.6",
    "gulp-sourcemaps": "^1.5.2",
    "merge": "^1.2.0",
    "requirejs": "^2.1.18"

In the Visual Studio solution expand the Dependencies node and make sure all packages are marked as installed (by showing a version number). If they aren’t – right click the NPM node and select “Restore Packages”.

4. Adding a Gulp file

Position in the projects root in solution explorer, press Ctrl-Shift-A and select “Gulp Configuration file”.
In the gulpfile, require in the following packages rimraf, gulp-typescript, merge, and fs.

Then we need to add a few gulp-tasks and configurations. For the TypeScript compilation we need to define a TypeScript Project Setting, some paths, a compile task and preferably also a watch task. Watch tasks enables automatic compilation of the TS files triggered by a save, something that makes the workflow much faster when iterating over small code changes.

The Gulpfile.js should look like follows:

var gulp = require('gulp'),
    rimraf = require('rimraf'),
    ts = require('gulp-typescript'),
    merge = require('merge'),
    fs = require("fs");

eval("var project = " + fs.readFileSync("./project.json"));

var paths = {
    npm: './node_modules/',
    lib: "./" + project.webroot + "/lib/",
    tsSource: './TypeScript/app/**/*.ts',
    tsOutput: "./" + project.webroot + '/scripts/app/',
    tsDef: "./TypeScript/definitions/"

gulp.task("clean", function (cb) {
    rimraf(paths.tsOutput, cb);

var tsProject = ts.createProject({
    declarationFiles: true,
    noExternalResolve: false,
    module: 'AMD',
    removeComments: true

gulp.task('ts-compile', function () {
    var tsResult = gulp.src(paths.tsSource)

    return merge([

gulp.task('watch', ['ts-compile'], function () {, ['ts-compile']);

gulp.task("copy", function () {
    var npm = {
        "requirejs": "requirejs/require.js"

    for (var destinationDir in npm) {
        gulp.src(paths.npm + npm[destinationDir])
          .pipe(gulp.dest(paths.lib + destinationDir));

5. Prepare script folders

Under wwwroot create two folders, one named lib and one named scripts.
Under the scripts folder, create a new folder named app.
Test to make sure the gulp copy-task is setup correct by running it from for ex Task Runner Explorer. After it’s executed and no errors occurred, check to see if a new folder containing the require.js file has been copied to the lib folder.

6. Add TypeScript folders

Create a new folder in the project root named TypeScript, under that create three new folders named: app, definitions and extdefinitions.
The plan here is to keep all code that will be written to contain app logic in the app folder. The TypeScript compiler will output definition files for your code and put those in the definitions folder. And then there is the extdefinitions folder that will hold all the definition files that you have downloaded, imported or maybe written but are for code that you are not responsible for.

Now – finally time to add some TypeScript files!

7. Add TypeScript files to setup RequireJS

Alert box saying Configure TypeScript Compilation
We need two TypeScript files, one named config.ts and one named main.ts, both under the TypeScript/app folder. (Position on the TypeScript/app folder and Ctrl-Shift-A as usual, but if you can’t see the TypeScript file type, expand the ASP.NET 5 tree node in the left hand column and select ASP.NET 5 Preview, this show the TypeScript File and it should be close to the JavaScript File)
When creating the first TS file, a popup will show, reminding you that you have to configure compilation with a task runner like Gulp or Grunt and offer to show instructions, just click “No” to continue.


/// <reference path="../extdefinitions/tsd.d.ts" />
    baseUrl: 'scripts/app',
    paths: {},
    shim: {}

// load AMD module main.ts (compiled to main.js)
require(['main'],(main) => {
    var app = new main();;


class Main {
    runString: string;

    constructor() {
        this.runString = 'hello from main';

    run() {
export = Main;

But there’s squiggly’s under ‘require‘ in config.ts, to remedy this we need a definition file for RequireJS.

8. Get a definition file for RequireJSAn image showing the Package Manager Console

There is a great project on GitHub named DefinitelyTyped. This project contains loads of definition files for different JavaScript libs and frameworks, see more info at The easiest way to work with them is to install TSD – the TypeScript Definition Manager.

To install TSD, run

npm install tsd -g

from the Package Manager Console.
In Package Manager Console, navigate to the root of the project and run:

tsd init

Edit the ‘tsd.json’ file that init generated. Set path and bundle to our previously defined paths.

  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "TypeScript/extdefinitions",
  "bundle": "TypeScript/extdefinitions/tsd.d.ts",
  "installed": {}

After it’s been installed it’s time to use it to get the definition file for RequireJS.
From the Package Manager Console (positioned in the root of the project) run:

tsd install require --save

This will now install the definition file for RequireJS and also add a reference to the ‘tsd.d.ts’ file. Now the easiest way way to reference the definition files in your project becomes a single use of the tsd.d.ts file. So to see the squiggly’s disappear and remove any compilation errors, just add this line above all code in the config.ts file:

/// <reference path="../extdefinitions/tsd.d.ts" />

9. Reference RequireJS and make it work

In the Index.cshtml file created when setting up the MVC parts, add a script to reference and init RequireJs. In the Head-tag add the following:

<script data-main="scripts/app/config.js" type="text/javascript" src="~/lib/requirejs/require.js"></script>

Make sure all your TypeScript files are compiled, and run the app via the web command or IIS Express.
You should now get an alert box from the browser of your choice saying “hello from main”!hello from main
So, that’s the main.ts code being executed sending it’s message out to the world.
The end result of all this is subtle, but it’s hopefully a solid base to build upon when creating a larger application.

All code can be found in my GitHub repository.


1. Try to keep all generated .js files in one folder, this way you can empty it and recompile in case anything get’s fudged (setup a clean task for the folder).
2. It’s ok to have static .js files in a project. Some developers in your team might not be comfortable with TS. Just try and keep their .js files separated from generated files.
3. If some team members insist on only using JavaScript, you can create definition files for those files, making it easier to work with them for you from TS.
4. If you need to use external js libraries, TSD is your friend!


/Happy coding!

post image

Polymer 0.5.4 Released

Polymer versions 0.5.3 and 0.5.4 released

Version 0.5.3 had a small dependency bug for Safari, this resulted in the rapid release of 0.5.4 to fix it.

Notable changes in the release are some paper-elements redesigned to adhere to the Material Design guideline.


  1. paper-toggle-button
  2. paper-checkbox

The patch also had some fixes for some ShadowDOM polyfill issues in webcomponents.js.

For more info read the full release doc.

post image

Visual Studio 2015, Web Components & Sass

Visual Studio 2015 & Sass  – Clean styling of Polymer elements

Just a few years ago, or even less, if some one would have said “I’m working with a Google framework and a lot of open source plugins – in Visual Studio“, the instant reply would probably have been slightly Pythonesque, like -“He’s a witch, burn him!!!”. But what once might have been considered an unholy trifecta is now not only doable, but it’s even enjoyable.

The last few days I have been thinking about how to set up the styling of my Polymer elements in an easy way that would help me keep the CSS dry, preferably by use of variables, linked files and mixins. At the same time the tooling had to produce my desired file/folder structure and be usable from VS2015. The solution also had to be generic enough, install and setup once with no need for changes when adding new elements and stylesheets.

What I came up with was Sass run with Grunt, and here is the steps needed to set it up in Visual Studio.

Install Ruby and Sass

chocolatey logoFirst off, to be able to run Sass you need to install Ruby, as Sass is a Ruby gem.

The easiest way to install Ruby and Sass is to use Chocolatey (if you aren’t running Chocolatey yet you must check it out, just follow the link). When you have Chocolatey installed, just type the following two lines in your command window to install SASS and Ruby

choco install ruby


choco install sass

However, when installing Sass I got an error saying:

ERROR: Could not find a valid gem 'sass' (= 3.2.10), here is why:
 Unable to download data from - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (

A workaround to this is to add the unsecured source for rubygems, enter the following in PowerShell

gem sources -a

This is a hack so don’t use this as a constant solution! But after this, installing Sass with Chocolatey worked fine.

Then remove the unsecured source after you installed Sass by executing the following

gem sources -r

Install Grunt-Contrib-Sass in VS2015


NPM – Restore Packages

Now it’s time to set up the tooling in Visual Studio.

1. Add “grunt-contrib-sass” to package.json, right click the NPM folder under Dependencies and choose “Restore Packages”. Expand thumbnail for visual description.

2. Configure Grunt by editing the gruntfile.js.

2.1 Enable Sass by adding this line of Javascript at the end of the file


2.2 Enter the Sass task configuration you want to use, for example

 sass: {
            default: {
                files: [{
                    expand: true,
                    src: ['wwwroot/components/*/*.scss'],
                    dest: '<%= src %>',
                    ext: '.css',

This is all the setup needed in Visual Studio 2015 to enable you to run Sass from the Task Runner Explorer.

Path error – “You need to have Ruby and Sass installed and in your PATH for this task to work”

To be able to use the Sass task from VS2015, it needs Sass and Ruby not only to be installed but to be on the PATH as well. If you haven’t got Sass and Ruby on your path you will get this error message

Running "sass:default" (sass) task
Process terminated with code 6.
You need to have Ruby and Sass installed and in your PATH for this task to work.
More info:
 Use --force to continue.

Aborted due to warnings.

You can check what’s on your path from PowerShell by typing


Adding Ruby to your path from PowerShell permanently can be done with this PowerShell command

[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\ruby215\bin", "Machine")

In my case “C:\ruby215″ is where Ruby was installed, this needs to be changed if your path is different!

Making sure Ruby and Sass are in the machines PATH

Use the following two commands in PowerShell to make sure that Ruby and Sass now are reachable from your path

ruby -v
sass -v

Both lines should report the current installed version, if everything is setup correctly.

Trying to run the task again

Trying to re-run the Sass task from Visual Studio now will result in the same problem as before, it’s telling us that Ruby and Sass needs to be on the path. But that’s because it’s keeping the state of the path since it was loaded, so just restart VS2015 and it will pick up the new path. Running the task after restart will now result in a successful run, given everything is setup properly.

A few words about the Sass config and presumed folder structure

The folder and file structure I’m using looks like something below

|- components
   |- my-element
   |   |- my-element.html
   |   |- my-element.scss
   |- another-element
   |   |- another-element.html
   |   |- another-element.scss
   |- styling
   |   |- _includes.scss
   |   |- _variables.scss
   |   |- misc-styling.html

What I wanted was to:

  1. Traverse my component tree
  2. Get all relevant linked scss files
  3. Output each compiled CSS file in to the respective components folder

Dissecting the Sass task configuration

The task configuration I used was:

 sass: {
            default: {
                files: [{
                    expand: true,
                    src: ['wwwroot/components/*/*.scss'],
                    dest: '<%= src %>',
                    ext: '.css',

The detailed explanation of the options

  • expand: true – needed to enable a dynamic file object
  • src: [‘wwwroot/components/*/*.scss’] – look for all sources that matches this pattern
  • dest: ‘<%= src %>’ – dynamically sets the destination path using a template, this will output the css file under the same directory as the source file
  • ext: ‘.css’ – replaces existing file endings on generated destination paths (in our case switching .scss to .css)

For more information about how to setup grunt tasks with dynamic file objects – see the documentation for Grunt.


Happy coding! :)

post image

Polymer in Visual Studio 2015 – Grunt-Vulcanize

Setting up a Vulcanize Grunt task in Visual Studio 2015

Developing Web Components from the new Visual Studio 2015 is a great experience with the added tooling. One problem with Web Components can be the large number of html-imports a big app will trigger. Even though an app might not be that large in actual code base size, it might be performing badly due to the sheer amount of loads needed to for all sub components.

The best way to reduce the amount of calls is to use Vulcanize, a tool that will concatenate your web components into one file.

Prerequisites and notes

First off, this solution builds upon the assumptions that all your html-imports are gathered in one file and one file only. This would be the file referred to as elements.html.
In my projects I have no html-imports in any of my Polymer elements. Any new imports I need I just add to the elements.html file instead, and I make sure I load that first thing in the apps life cycle. I am importing the polyfill library webcomponents.js and Polymer.html prior to my own components. I am keeping Polymer outside my own elements file to reduce time slightly, but mostly just because I had some initial problems when including it and in lack of having time to tinker with it so I just kept it out. You can see this exclusion under the configuration section, and you can expand on this to exclude other elements should you feel like it.

Secondly, a folder named built needs to exist under your wwwroot to accept the output from the vulcanization.

Install the grunt-vulcanize task

First install the grunt-vulcanize task by adding it to package.json:

    "version": "0.0.0",
    "name": "app_name",
    "devDependencies": {
        "grunt": "^0.4.5",
        "grunt-bower-task": "^0.4.0",

        //add the row below (version number might of course vary depending on point in time)
        "grunt-vulcanize": "^0.6.1"

Configure the vulcanize task

Setup the vulcanize task in gruntfile.js by adding the section below to the grunt.initConfig method:

  vulcanize: {
            default: {
                options: {
                    strip: true,
                    excludes: {
                        imports: [
                files: {
                    'wwwroot/built/elements.html': 'wwwroot/pages/elements.html'

In the task you can see how it is setup to exclude the polymer.html file, and also how removing comments and blocks of white-space by setting strip to true (it’s default is false). For all the options refer to the Grunt-Vulcanize ReadMe.
Under the files setup, do notice that the first parameter is the destination file and that the second parameter is the original file that should be vulcanized.

If you want it you can add a task alias for your vulcanize setup with:

grunt.registerTask("main_vulcanize", ["vulcanize:default"]);

And then don’t forget load the grunt-vulcanize plugin at the end of your file:


Running Vulcanize from Task Runner Explorer

First open the Task Runner Explorer in Visual Studio 2015 by expanding View>Other Windows and click Task Runner Explorer. Expand image to the right to see location of the Task Runner Explorer in the menu. TaskRunnerExplorer_menu

In the Task Runner Explorer window you can then see your vulcanize task as well as any Alias you setup for it, see image below.

Running your vulcanize task is now as simple as:

  1. Double clicking your alias name or the task name
  2. Right clicking alias name or task name and selecting “Run” from the context menu
  3. Binding the task or alias in the context menu to one of the build steps, below I choose to bind it to “After Build” which means my vulcanization will be run automatically after every time I build my project. Very nice since ctrl-shift-b is inprinted in muscle memory by now 😉

Grunt Tasks in Task Runner Explorer


post image

Rookie mistakes developing Web Components in Polymer

Developing Web Components is both fun as well as frustrating at times. Maybe it’s the fact that I’m so used to coding typed languages (C# & Java) with loads of compiler help, or maybe it’s the fact that debugging web pages aren’t always a breeze combined with that Web Components are still fairly raw. But I often found myself scratching my chin thinking “What the …?”. Here’s a short list of three confounding issues you might run in to when starting to develop Web Components and using Polymer.

1. Nothing is being rendered on screen, nothing!

Q: I just added a new component and now nothing is being rendered on my screen. I’m not kidding, NOTHING! My entire site is just white, there seems to be elements there when I mouse over but they are all just withe?!?!

A: This is done by declaring a new Polymer element that hasn’t got a noscript attribute, has a script tag but it lacks a call to the Polymer method. See code snippet below.

<polymer-element name="demo-element">
        some awesome html code

        //scary empty script tag!!

2. My new element isn’t just lacking style, it’s refusing all styling!

Q: I have this cool new Polymer element that I just made and it’s not being styled by the CSS I defined in it, what gives?

A: This is probably due to a slightly misplaced style tag. It’s easy to miss that the style tag must be located within the template tag and that it can’t be located just below the Polymer element declaration. See code snippet below.

<polymer-element name="demo-element">
        /*this is a misplaced style tag, it should be within the template tag below!*/

        some awesome html code

        //scary empty script tag!!

3. Console keeps nagging: Uncaught Already registered (Polymer) prototype for element my-element

Q: I have this great app written all in web components, but I see a lot of errors in the console saying “Uncaught Already registered (Polymer) prototype for element new-list”, what gives?

A: This is what happens if you forget to remove the noscript attribute as you later register the element with the Polymer method. I often start first draft of my elements by defining noscript on them and all too often I forget to remove the attribute as the elements evolve. :( See code snippet below.

<polymer-element name="demo-element" noscript>
            /*this is a correctly placed style tag!*/

        some awesome html code

            //some rad JavaScript code!!
post image

Deploy ASP.Net 5 apps in IIS

Deploying an ASP.Net 5 web application in IIS

The preview of Visual Studio 2015 contains no built in tooling to directly deploy web apps to an IIS, this post describes a way of doing it without tooling.

Prepare project for IIS deploying using command line tools

Running commands can be done from any prompt that has the K tools in the current path. The Package Manager Console from within VS2015 works fine if you have installed the K toolset already.

First off, pack the site you intend to publish by:

1. Make sure you are located in the project root, the folder containing the project.json file.

2. Execute the following ‘kpm pack –out outputDirectory –runtime choosenRuntime‘, for ex ‘kpm pack –out C:\tmp\WebApp –runtime KRE-CLR-amd64.1.0.0-beta1′.

(If you are going to host this on an IIS locally or on a server, use a CLR version of the runtime. If you plan on deploying the package to Azure, use a Core version of the runtime.)

3. Create a new Website in IIS pointing to the chosen outputDirectory/wwwroot. (In our ex above C:\tmp\WebApp\wwwroot)

Happy Hacking! :)

Disclamier – This was written for beta-3, some parts have been renamed for beta-4 and onwards!

post image

Polymer Bower packages in Visual Studio 2015

Working with Polymer in Visual Studio 2015 (Preview)

In the new VS2015, there is built in Bower and npm support. This is great if you want to use Visual Studio to build Polymer components and apps. Importing the basic Polymer packages in to VS2015 is not completely straight forward unfortunately, as the autocomplete for the Bower packages doesn’t seem to work a 100% just yet.

Importing the Polymer packages with Bower in to VS2015

To import the packages polymer, polymer/core-elements and polymer/paper-elements you first edit the bower.json file in your VS2015 web project. The way to insert them is under the dependencies tag, see code snippet.

"dependencies": {
     "polymer": "^0.5.4",
	"core-elements": "Polymer/core-elements#^0.5.4",
	"paper-elements": "Polymer/paper-elements#^0.5.4"

After the bower.json file is edited, you will see the packages pop up under your Bower dependencies. Then you need to right click the Bower packages header and select Restore Packages to actually download the packages from Bower. See picture.

Then check your Output Window and select Package Manager Log to see what’s being imported from Bower and make sure there are no errors!

Happy Coding! :)

PowerShell – Working with JSon

Manipulating JSon with PowerShell

A few tips about working with JSon in PowerShell. (more…)

post image

Windows 8.1 Command Binding in a DataTemplate

DataTemplate and Bindings

In Windows 8 there are a few controls that rely on a DataTemplate to show item collections.

The DataTemplate is used to define visual layout for each item that will be rendered in an ItemsControl, it data binds nicely to collections of objects. It then iterates through the collection and uses each item as context for every new Template that is created.

Binding to Commands in the DataTemplate

When binding Commands to controls we usually bind them to Commands in the ViewModel, set as datacontext.

But if you, for example, have a button defined in the DataTemplate and bind that to a Command defined in your ViewModel, set as the datacontext for the page, it won’t work.

Why doesn’t Binding to Commands work in the DataTemplate?

The reason that the Command isn’t executed is that the Command can’t be found.

Since it’s an item in the collection that’s actually the current DataContext for the item being created, the command can’t be found if it’s defined globally in your ViewModel.

The solution is to refer the Command binding to look further up the object tree to find the Command.

In WPF it was solved using FindAncestor, but that’s removed now in WinRT.

The easiest way to solve it is to actually give the view/page an x:Name. Then refer to the Command in the binding as DataContext.MyCommandName, and set ElementName to the name of the view/page. See code snippets below, how the Command is defined, the x:Name set in Page and the Command defined in the ViewModel.

Code Snippets

ViewModel snippet:

        private RelayCommand headerClickedCommand;
        public RelayCommand HeaderClickedCommand
            get { return headerClickedCommand ?? (headerClickedCommand = new RelayCommand(ExecuteHeaderClickedCommand)); }

        private void ExecuteHeaderClickedCommand()

XAML PageRoot snippet:

<Page xmlns=""

XAML DataTemplate snippet:

  <Grid Margin="0,0,0,2">
    <Button Foreground="{ThemeResource ApplicationHeaderForegroundThemeBrush}"
				    AutomationProperties.Name="Group Title"
                                    Command="{Binding DataContext.HeaderClickedCommand, ElementName=MyView}"
                                    Style="{StaticResource TextBlockButtonStyle}">
     <StackPanel Orientation="Horizontal">
       <TextBlock Text="{Binding Category}" Margin="0,-11,10,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
        <TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-11,0,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />

Happy Coding :)

Tests not running in Visual Studio 2013 with ReSharper 8

Unit tests not executing from ReSharper’s Unit Test Sessions

Pressing Ctrl+U,L resulting in nothing but spinning bars? I had this problem trying to run my unit tests from Visual studio 2013 using ReSharper 8.

The test indicators would keep spinning but nothing happened, setting breakpoints on the first row on the code showed that the unit tests actually never even started executing. No matter how long time that passed (ok I stopped waiting after 3 minutes to be honest) the bars just kept spinning and no error shows up.

After searching the web it turns out this is a known issue, stated to be solved in several ReSharper releases. Not sure if it’s the case and the bug has just resurfaced in the new ReSharper 8 version.

The easy solution

Turns out this problem is avoidable just by starting Visual Studio 2013 as an administrator.

If you got VS2013 pinned ot the taskbar in Windows 8/8.1, this is the easiest way to make it always start in admin mode:

1. Right click the pinned Vs2013 icon and select properties.

Pinned VS2013 Properties2. Click the “Advanced” button in the properties window.

3. Check the “Run as Administrator” checkbox.

Advanced Properties

After this your Visual Studio will always be run as Administrator.


Happy Testing :)