post image

Getting started: TypeScript and MVC 6 from Visual Studio Code




Setting up a TypeScript – MVC 6 project in VS Code

Welcome to this tutorial where we’re taking a look at how to set up a TypeScript – ASP.NET 5/MVC 6 project in Microsoft’s new lightweight IDE – Visual Studio Code (VS Code)!

Disclaimer: Please note that this article was written using Visual Studio Code v0.7.10 using the beta-6 bits on a Windows 10 machine. So if you are using a different version/OS/setup, some of the information in this article might not be accurate.

Downloading VS Code

If you haven’t installed Visual Studio Code, you can get it at https://code.visualstudio.com/.

Creating an ASP.NET 5 project

In VS Code there is no File -> New Project option as Visual Studio users are used to seeing. The easiest way to start a new project is instead to use the Yeoman scaffolding tool to create one.

1. Installing Yeoman

If you haven’t got Yeoman already installed on your system, you need to install it. If you have Node.js already installed on your system, you can use npm install  to get Yeoman and the ASP.Net generator. Open a command window and type the following:

npm install -g yo grunt-cli generator-aspnet bower

2. Scaffolding an ASP.NET 5 web app

Start the scaffolding from the command window by placing in the folder where you want to create the project, then typing:

yo aspnet

  1. Select Empty Application
  2. Name your ASP.NET application
Command window showing scaffolding of ASP.NET project with Yeoman

Running the Yeoman ASP.NET generator

And the project is created…

3. Restore packages and build

Do as Yeoman says after scaffolding the project and update packages and build to make sure everything works ok, first move in to the folder where the project was created, then execute the following from the command prompt:

dnu restore

and

dnu build

“dnu” stands for DNX Utility where DNX stands for .NET Execution Environment and is the new runtime created for ASP.NET 5.

4. Running the project

If everything goes well with updating packages and building the project you can start it by typing:

dnx . web

This will start the web application at http://localhost:5000 so open a browser and enter this address to make sure your web application got started properly. The result will be a familiar response.

 

Microsoft edge showing the result of calling th eweb project

Running the application with dnx . web and testing it from edge

A small sidenote

If you are new to ASP.NET 5 and interested in where the applications endpoint is defined, you will not find any Web.config when looking in the project folder. Instead the “web” command that we ran is defined in project.json file and that in it’s turn is pointing towards the hosting.ini file for the information. If you open the project in VS Code by selecting File -> Open Folder and choosing the project folder, you will see the following:

VS Code showing project.json web command pointing at hosting.ini

project.json web command pointing at hosting.ini

Serving static files

To be able to deliver static files like Html and JavaScript files, we need to add a reference to Microsoft.AspNet.StaticFiles as a dependency in project.json, like this:

"dependencies": {
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta6", 
    "Kestrel": "1.0.0-beta6"
  },

Now we can add an Html page so we can test the setup so far.
Add a file named index.html under the wwwroot folder and copy the following code into it:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Index</title>
</head>
<body>



<h1>Hello TypeScript fans!</h1>



</body>
</html>

We also need to fix Startup.cs as it has a hard coded greeting message in the template, and we need to instruct it to use static files.

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace TS_Code
{
    public class Startup
    {
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
        }
    }
}

Now go back to your command line, build the app with
dnu build
and after that, run it with
dnx . web
Then open a browser and enter the url http://localhost:5000/index.html, now you should see the greeting from our index.html page.

An image of the edge browser showing the message Hello TypeScript Fans

Hello TypeScript Fans!

Setting up TypeScript

To get our TypeScript compiler up and running we need to add a few node modules to our project and also a task runner, I’ll use Gulp in this tutorial.
But first we’ll add a TypeScript file and the correct folder structure.

Adding a TypeScript file

Add a folder named TypeScript in the root of the project, it will hold our TypeScript files.
Then add a file named test.ts to the TypeScript folder, edit it and make it do something simple, like for example pop an alert with a greeting:

//Using Visual Studio Code is fun!
alert("Hello from TS!");

Adding node modules

First add a package.json file in the root of of the project, edit it and add the following:

{
  "version": "1.0.0",
  "name": "TS_Code",
  "private": true,
  
  "devDependencies": {
    "typescript": "^1.5",
    "gulp": "^3.9.0",
    "gulp-typescript": "^2.8.0",
    "merge": "^1.2.0"
  }
}

Now open a command line window and position in the root of the project, to install the packages specified in the new package.json file execute the following command:
npm install

Adding Gulp

Add a new file in the root of the project, name it gulpfile.js and add the following content:

var gulp = require('gulp'),
    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/**/*.ts',
    tsOutput: "./" + project.webroot + '/scripts/',
    tsDef: "./TypeScript/definitions/"
};

var tsCompilerConfig = ts.createProject({
    declarationFiles: true,
    noExternalResolve: false,
    module: 'AMD',
    removeComments: true
});

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

    return merge([
        tsResult.dts.pipe(gulp.dest(paths.tsDef)),
        tsResult.js.pipe(gulp.dest(paths.tsOutput))
    ]);
});

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

Running Gulp tasks in VS Code

To run the tasks we just setup press Ctrl-Shift-P to open the Command Palette in VS Code. To run tasks type ‘run task’ and hit enter (or select the option from the Command Palette).

The Command Palette in Visual Studio Code showing Run Task

Command Palette: Run Task

Now you should get a list of tasks to open, it will show all the tasks we defined in the gulpfile, namely ts-compile and watch.

Side note

If you haven’t installed Gulp globally on your development machine previously, the output window will open up in the right split pane and tell you
'gulp' is not recognized as an internal or external command, operable program or batch file.
Running gulp --tasks-simple didn't list any tasks.
Did you run npm install?

This is fixed by installing Gulp globally on the machine by running the following from a command line
npm install --global gulp

Run TypeScript compilation in VS Code

To run the TS compiler, run the task ts-compile.
This should compile our test.ts file to a file named test.js and place it under the wwwwroot/scripts folder.
Make sure the file is in place and open it. Now the comment that we added in the test.ts file should be removed as well, due to the TypeScript compiler setup in the gulp-file specifying

removeComments: true

Automatic TypeScript compilation in VS Code

It is possible to setup a watch task that tracks any eventual saves to TypeScript files and then automatically compiles them. It is already configured in our gulp-file and it is the task tat’s named watch. So, run the watch task and all TypeScript files will be automatically compiled on every change and save.

Test the project

To test the entire setup and make sure the web server is delivering our newly compiled script, we will call it from our html-file.
Add a reference to the compiled test.js file in the HEADER-tag of the index.html document, like this:

<script src="scripts/test.js"></script>

Start the application by opening the Command Palette with Ctrl-Shift-P as before and start typing ‘dnx’ and run ‘dnx: web’, this will execute the web command specified in the project.json file and start the application for us. After this use your browser and go to http://localhost:5000/index.html yet again. The difference this time is that you should see an alert pop up and say “Hello from TS!”.

Image of Microsoft edge showing the end result of the TypeScript project

Hello From TS!

 

Get the Code!

You can find this project on my GitHub account.

More TypeScript projects

If you are interested in setting up a TypeScript – MVC 6 app in VS2015, check out this post: Getting started: TypeScript 1.5 in Visual Studio 2015
If you are interested in a more advanced setup of a TypeScript – MVC 6 app that uses RequireJS in VS2015, check out this post: Setting up a TypeScript – RequireJS – Gulp – MVC 6 Web Project in Visual Studio 2015 RC

Happy coding! :)

post image

Getting started: TypeScript 1.5 in Visual Studio 2015




How to use TypeScript 1.5 from Visual Studio 2015

The latest version of TypeScript has been in the works for quite some time and finally got released on July 20th, coinciding with the release of Visual Studio 2015.

Version 1.5 of TypeScript contains quite a few Changes, many aligning with the latest ECMAScript(ES) 6 spec. Among other cool features support for ES6 Modules, for..of, Computed Properties, let & const, Decorators (an ES 7 proposal), and much more.

This article is a basic tutorial that will show you how to get started with TypeScript in Visual Studio 2015 RTM.

What we are going to do is setup an ASP.NET 5 web Project in Visual Studio 2015, create a compile tasks in Gulp and use Task Runner Explorer to execute those tasks. This will be the basis for a good workflow when working with TypeScript.

Start an ASP.NET 5 Project in Visual Studio 2015

1. Select File->New->Project. Select the ASP.NET Web Application.

Dialogue showing New ASP.NET Web Application

Fig 1 – New ASP.NET Web Application

 

 

2. Select ASP.NET 5 Empty Project.

Dialogue showing the Empty ASP.NET 5 Preview Template

Fig 2 – Select Empty ASP.NET 5 Template

Getting the TypeScript compiler

Create a package.json file in the solution. Make sure you’re positioned in the project in the solution Explorer, press Ctrl-Shift-A, select DNX-Client-Side-NPM configuration file.

Dialogue showing Add New Item - DNX - Client-side- NPM configuration file

Fig 3 – Add an NPM configuration file

Under the devDependencies section in the package.json file, add a reference to TypeScript, see code snippet. We’re also going to need Gulp, the plugin to run TypeScript compilation from Gulp and some other plugin, so we’re also adding references for those as well.

"devDependencies": {
    "typescript": "^1.5",
    "gulp": "^3.9.0",
    "gulp-typescript": "^2.8.0",
    "merge": "^1.2.0"
  }

After saving the package.json file there is a notification in the status bar (bottom bar of VS) saying “Installing packages”, after that verify that the package got installed properly by expanding Dependencies-NPM and see that TypeScript got installed.

Image showing NPM Dependencies in Visual Studio 2015

Fig 4 – Verify NPM Dependencies in the Solution Explorer

Add static file serving

Change the Startup class in Startup.cs to:

 public class Startup
    {
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services) { }

        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
        }
    }

Add static content

If it’s not already in the directory folder structure, add a directory named wwwroot under your projects root folder. When it’s added in the correct folder and has the correct name, you will see it in the Solution Explorer having a special icon resembling a very abstract earth globe (or is it a ball with four lines on it)?

Add a simple index.html file so that we can make sure everything is working. Use the shortcut (ctrl – shift – a) to add files quickly in Visual Studio 2015.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Index</title>
</head>
<body>



<h1>Hello TypeScript fans!</h1>



</body>
</html>

Run the app using the web command and open your browser of choice and redirect it to http://localhost:5000/index.html
You should now see a the text saying “Hello TypeScript fans!”, given everything is working.

Add a TypeScript file

First add a new folder in the Project root and name it TypeScript, this is where we’ll put our TypeScript code.
Add a file under the TypeScript folder, name the file test.ts. Practice using (ctrl – shift – a) if you’re not already doing it by instinct. The TypeScript file type is in the templates under Installed -> DNX -> Client-side.

Dialogue for  adding a TypeScript file in Visual Studio 2015

Fig 5 – Adding a TypeScript File

Add the following code to your TypeScript file:

//a comment
console.log("Hello from TS!");

Simple code, just enough to make sure the process is working correctly.

Setting up TypeScript compilation with Gulp

To compile our TypeScript files we’re going to setup gulp tasks. Then we can use Task Runner Explorer to run our build tasks.
First add a gulp-file to the solution, in the root of the solution add a Gulp Configuration File.

Dialogue to add a  Gulp Configuration File in Visual Studio 2015

Fig 6 – Adding a Gulp configuration file

Create a compile task in gulp

To setup a compile task, add the following code to the Gulp config:

var gulp = require('gulp'),
    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/**/*.ts',
    tsOutput: "./" + project.webroot + '/scripts/',
    tsDef: "./TypeScript/definitions/"
};

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

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

    return merge([
        tsResult.dts.pipe(gulp.dest(paths.tsDef)),
        tsResult.js.pipe(gulp.dest(paths.tsOutput))
    ]);
});

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

This sets up a Gulp tasks that compiles your TypeScript code and produces a definition file. As to where the TypeScript source files are searched for, the placement of the compiled .js files and the definition files, see the declarations in the paths block.

Run TypeScript compilation with Task Runner Explorer

Hit (ctrl – alt -backspace) to open the Task Runner Explorer window in Visual Studio 2015.
If the Gulp-file contents was correct the following will appear

The Task Runner Explorer windows in Visual Studio 2015

Fig 7 – Task Runner Explorer showing Gulp tasks

Double click the ts-compile task to run the TypeScript compilation.
Make sure there is a file named test.js output in the wwwroot/scripts folder. Verify that the comment have been removed in the test.js file according to the compiler setup in the Gulp file (see tsProject in the gulp-file).

Adding the script to the HTML file

Add a reference to the script file at the bottom of the header tag of the HTML file we created earlier (index.html).

<script src="scripts/test.js"></script>

Testing the application

Now run the application and open it from your browser (http://localhost:5000/index.html). Open the F12 devTools in your browser, open the console and verify that the print “Hello from TS!” is displayed.

Image showing the result of the tutorial

Fig 8 – The result and the console print

Get the Code!

The entire Visual Studio Solution with the code can be found on my GitHub account.

More TypeScript projects

If you are interested in setting up a TypeScript – MVC 6 app that uses RequireJS in VS2015, check out this post: Setting up a TypeScript – RequireJS – Gulp – MVC 6 Web Project in Visual Studio 2015 RC

 

Happy coding! :)

post image

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




Setting up a TypeScript – RequireJS – MVC 6 web app in VS2015

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)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    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>
<html>
<head>
    <title>TypeScript Module loading with RequireJS</title>
</head>
<body>

<h1>Setup project</h1>

</body>
</html>

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)
					.pipe(ts(tsProject));

    return merge([
		tsResult.dts.pipe(gulp.dest(paths.tsDef)),
		tsResult.js.pipe(gulp.dest(paths.tsOutput))
    ]);
});

gulp.task('watch', ['ts-compile'], function () {
    gulp.watch(paths.tsDef, ['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.

config.ts

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

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

main.ts

class Main {
    runString: string;

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

    run() {
        alert(this.runString);
    }
}
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 definitelytyped.org. 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.

Protip

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.

Namely:

  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

and

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 https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)

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

gem sources -a http://rubygems.org

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 http://rubygems.org

Install Grunt-Contrib-Sass in VS2015

NPM-Restore_Packages

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

grunt.loadNpmTasks('grunt-contrib-sass');

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.
Warning:
You need to have Ruby and Sass installed and in your PATH for this task to work.
More info: https://github.com/gruntjs/grunt-contrib-sass
 Use --force to continue.

Aborted due to warnings.

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

$env:path

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

wwwroot
|- 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: [
                          "polymer.html"
                        ]
                    }
                },
                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:

grunt.loadNpmTasks("grunt-vulcanize");

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">
    <template>
        some awesome html code
    </template>

    <script>
        //scary empty script tag!!
    </script>
</polymer-element>

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">
    <style>
        /*this is a misplaced style tag, it should be within the template tag below!*/
    </style>

    <template>
        some awesome html code
    </template>

    <script>
        //scary empty script tag!!
    </script>
</polymer-element>

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>
    <template>
        <style>
            /*this is a correctly placed style tag!*/
        </style>

        some awesome html code
    </template>

    <script>
        Polymer({
            //some rad JavaScript code!!
        });
    </script>
</polymer-element>

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.
VS2015BowerRestore

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…)