How to create multiple themed release builds by using web deploy, gulp and PostCSS in Visual Studio 2015 update 3

 
 

Note

In this blogpost a “release build” is a folder containing all the files (html, css, JavaScript, images, dll’s etc.) needed in production to run a specific themed web application.

 
 

 
 

 
 

The publish / deployment process in Visual Studio is intended to create one “release build”, but I wanted this process to create 2 exactly the same “release builds”, just with different themes (different images and css files).

 
 

To accomplish this, I altered / added / removed the following files:

  • Added deploy.pub.xml (the publish profile)
  • Altered the csproj file of the web project
    • Added folder to the root “Themes”
      • Theme1
        • Images (contains the images for this theme, build type = “None”)
        • variables.cssn (contains all the css next variables for this theme, build type = “None”)
      • Theme2
        • Images (contains the images for this theme, build type = “None”)
        • variables.cssn (contains all the css next variables for this theme, build type = “None”)
  • Added package.json (npm configuration file, build type = “None”)
  • gulpfile.js (gulp configuration file, build type = “None”)
  • gulpfile.helper.js (custom JavaScript code, build type = “None”)
  • Renamed all *.css to *.cssn (css next) and set the build type = “None” (except the css files in the libraries folder)
  • Deleted all *.css files except the files in the libraries folder.
  • .gitignore

 
 

 
 

 
 

Deploy.pubxml

 
 

Create a publishing file “deploy.pubxml” by right clicking on your web application project > publish… > Custom

  • Enter “deploy” for the name, his will create a deploy.pubxml.
  • Choose publish method “File System”
  • Enter a target location, for example C:\Release\MyWebApp

 
 

 
 

 
 

<?xml
version=1.0
encoding=utf-8?>

<!–

This file is used by the publish/package process of your Web project. You can customize the behavior of this process

by editing this MSBuild file. In order to learn more about this please visit http://go.microsoft.com/fwlink/?LinkID=208121.

–>

<Project
ToolsVersion=4.0
xmlns=http://schemas.microsoft.com/developer/msbuild/2003>

<PropertyGroup>

<WebPublishMethod>FileSystem</WebPublishMethod>

<SiteUrlToLaunchAfterPublish />

<publishUrl>C:\Release\Theme1</publishUrl>

<DeleteExistingFiles>False</DeleteExistingFiles>

<LastUsedBuildConfiguration />

<LastUsedPlatform />

<LaunchSiteAfterPublish>False</LaunchSiteAfterPublish>

<ExcludeApp_Data>False</ExcludeApp_Data>

</PropertyGroup>

<!–

The target “GatherAllFilesToPublish” is the last target run by msbuild, before msdeploy starts copying files to the destination folder.

This is the last time we can alter the output, because there is no “after publish” target.

We have to use the property “AfterTargets”, because “DependsOnTargets” doesn’t work.

 

The target runs a gulp task which creates a release output folder per theme (by using PostCSS and copying images to correct location).

– themes: Is a “comma” seperated list of themed releases that should be created

– The first item should be the “default” theme

– projectFolder: The folder containing the *.csproj file.

This folder is needed, because among other things it contains:

– the *.cssn (css next) files that should be compiled to *.css

– the theme images that should be copied

– packageTempDir: The temp folder used by Visual Studio to create a release. This folder will be used as base for the other themed releases.

– publishFolder: Is set to the “publishUrl”,

– The publishing process of Visual Studio is intended to work for one “release build”.

– We are creating multiple “release builds”, one for each theme.

– Each “release build” will be placed inside the parent folder of the “publishFolder”

– Only the first theme (default theme) will be placed directly into the “publishFolder”

 

NOTE

– npm run “gulp”, will only work when the package.json contains scripts { “gulp”: “gulp” }.


–>

<Target
Name=AfterPublish
AfterTargets=GatherAllFilesToPublish>

<Exec
Command=npm run gulp — after-publish –options –themes Theme1,Theme2 –projectFolder $(MSBuildProjectDirectory) –packageFolder $(_PackageTempDir) –publishFolder $(publishUrl) />

</Target>

</Project> 

 
 

 
 

Alter csproj

Add a “before build” step (just before the “project” end tag), to apply theming whenever the project is build (even in development)

<Target
Name=BeforeBuild>

<Exec
Command=npm run gulp — apply-theming />

</Target>

</Project>

 
 

This will only run the theming and it will run the theming inside the current project folder.

 
 

 
 

 
 

Add or update package.json

After saving this file, Visual Studio will automatically run gulp install, to install all npm packages.

 
 

{

    “version”: “1.0.0”,

    “name”: “MyWebApp”,

    “private”: true,

“devDependencies”: {

“del”: “>=2.2.1”,

“gulp”: “>=3.9.1”,

“gulp-plumber”: “>=1.1.0”,

“gulp-postcss”: “>=6.1.1”,

“gulp-rename”: “>=1.2.2”,

“gulp-util”: “>=3.0.7”,

“postcss-import”: “>=8.1.2”,

“postcss-cssnext”: “>=2.7.0”

 
 

},

“scripts”: {

“gulp”: “gulp”

}

}

 
 

 
 

 
 

 
 

Add a gulpfile.js to the root of your web application

 
 

/**

* The version of gulp and all it’s dependencies are managed in the package.json file.

*/

‘use strict’;

 

// Dependencies

const fs = require(‘fs’);

const gulp = require(‘gulp’);

const debug = require(‘gulp-debug’); // Can be used to log all files in a gulp stream (gulp.src or gulp.dest).

const jshint = require(‘gulp-jshint’);

const livereload = require(‘gulp-livereload’);

const plumber = require(‘gulp-plumber’);

const util = require(‘gulp-util’);

const path = require(‘path’);

const helpers = require(‘./gulpfile-helpers.js’);

const log = helpers.log;

const defaultTheme = ‘Theme1’;

 

/**

* The default task.

*/

gulp.task(‘default’, function () {

 

});

 

/**

* This task will be called from the “Deploy.pubxml”.

*/

gulp.task(“after-publish”, function () {


const themes = (util.env.themes || ‘Theme1,Theme2’).trim().split(‘,’);


const projectFolder = (util.env.projectFolder || path.resolve(‘.’)).trim();


const packageFolder = path.resolve((util.env.packageFolder || “..\\bin\\Release\\Package\\PackageTmp”).trim());

 


// When this task is passed an environment variable “publishFolder”, we expect the “publishFolder” to be the path to the first “themed release build”.


// See the Deploy.pubxml for more explanation.


var publishFolder = “C:\\Release”;


if(util.env.publishFolder) {

publishFolder = path.dirname(util.env.publishFolder.trim());

}

 

log(`after-publish: themes – ${themes}`);

log(`after-publish: projectFolder – ${projectFolder}`);

log(`after-publish: packageFolder – ${packageFolder}`);

log(`after-publish: publishFolder – ${publishFolder}`);

 


// Publish each theme.

themes.map((theme) => {

helpers.publishTheme(theme.trim(), defaultTheme, projectFolder, packageFolder, publishFolder);

});

});

 

/**

* The “BeforeBuild” target in the ” csproj” will call this gulp task.

*

* If you want to generate a theme other than the default theme, use the command line:

* npm run gulp — apply-theming –options –theme Theme1

*/

gulp.task(‘apply-theming’, function () {


const theme = (util.env.theme || defaultTheme);

helpers.applyTheme(theme, path.resolve(‘.’), path.resolve(‘.’));

});

 
 

 
 

 
 

 
 

Add a gulpfile.helper.js to the root of your web application

 
 

const del = require(‘del’);

const gulp = require(‘gulp’);

const path = require(‘path’);

const postcss = require(‘gulp-postcss’);

const postcssImport = require(‘postcss-import’);

const postcssNext = require(‘postcss-cssnext’);

const rename = require(‘gulp-rename’);

const util = require(‘gulp-util’);

 

/**

* Copy images and variables.cssn (cssnext) from the “theme” folder to the correct location.

* projectFolder = the folder containing the “*.csproj” file.

* destinationFolder = the folder where the theme files will be placed.

*/

function applyTheme(theme, projectFolder, publishFolder) {

 


// Copy image files to publish folder.

copyImages(theme, projectFolder, publishFolder)

.on(‘finish’, runCopyCssNextThemeFiles);

 


// Copy css next theme files inside publish folder to the “App/Styles” folder.


function runCopyCssNextThemeFiles() {

copyCssNextThemeFiles(theme, publishFolder)

.on(‘finish’, runGenerateCss);

}

 


// Generate css from css next files.


function runGenerateCss() {

generateCss(publishFolder);

}

}

 

/*

* Copy all css next files from the project folder to the specific theme publish folder.

*/

function copyCssNextFiles(projectFolder, publishThemeFolder) {


const src = path.join(projectFolder, ‘/**/*.cssn’);


const dest = publishThemeFolder;

 

log(`copyCssNextFiles: src – ${src}`);

log(`copyCssNextFiles: dest – ${dest}`);

 


return gulp.src(src)

.pipe(gulp.dest(publishThemeFolder));

}

 

/**

* Copy theme css next files (including variables.cssn) from the “theme” folder to the “App/Styles” folder.

*/

function copyCssNextThemeFiles(theme, publishFolder) {


const src = path.join(publishFolder, ‘Themes/’ + theme + ‘/**/*.cssn’);


const dest = path.join(publishFolder, “App/Styles”);

 

log(`copyCssNextThemeFiles: src – ${src}`);

log(`copyCssNextThemeFiles: dest – ${dest}`);

 


return gulp.src(src)

.pipe(gulp.dest(dest));

}

 

function copyImages(theme, projectFolder, destinationFolder) {


const src = path.join(projectFolder, ‘Themes/’ + theme + ‘/Images/**/*.*’);


const dest = path.join(destinationFolder, ‘App/Images’);

 

log(`copyImages: src – ${src}`);

log(`copyImages: dest – ${dest}`);

 


return gulp.src(src)

.pipe(gulp.dest(dest));

}

 

/*

* Copy all files from the Visual Studio package temp folder to the specific theme publish folder.

*/

function copyPackageFiles(packageFiles, publishThemeFolder) {


const src = packageFiles;


const dest = publishThemeFolder;

 

log(`copyPackageFiles: src – ${src}`);

log(`copyPackageFiles: dest – ${dest}`);

 


return gulp.src(packageFiles)

.pipe(gulp.dest(publishThemeFolder));

}

 

/**

* Compile cssn (cssnext) to css.

*/

function generateCss(publishFolder) {


const src = path.join(publishFolder, ‘App/**/*.cssn’);


const dest = path.join(publishFolder, ‘App’);

 

log(`generateCss: src – ${src}`);

log(`generateCss: dest – ${dest}`);

 


const plugins = [

postcssImport,

postcssNext

];

 


return gulp.src(src)

.pipe(postcss(plugins))

.pipe(rename({

extname: “.css”

}))

.on(‘error’, log)

.pipe(gulp.dest(dest));

}

 

/**

* Log message or an array of messages.

*/

function log(message) {


if (Array.isArray(message)) {


for (var i = 0, length = message.length; i < length; i++) {

util.log(message[i]);

}

}


else {

util.log(message);

}

}

 

function publishTheme(theme, defaultTheme, projectFolder, packageFolder, publishFolder) {


const publishThemeFolder = path.join(publishFolder, theme);


const publishThemeFiles = path.join(publishThemeFolder, “**”);


const packageFiles = path.join(packageFolder, ‘**/*’);

 

log(`publishTheme: publishThemeFolder – ${publishThemeFolder}`);

log(`publishTheme: publishThemeFiles – ${publishThemeFiles}`);

log(`publishTheme: packageFiles – ${packageFiles}`);

 


// Remove publish folder.

del.sync([publishThemeFiles], { force: true });

 


// Copy package files to publish folder.

copyPackageFiles(packageFiles, publishThemeFolder)

.on(‘finish’, runCopyCssNextFiles);

 


// Copy css next files to publish folder.


function runCopyCssNextFiles() {

copyCssNextFiles(projectFolder, publishThemeFolder)

.on(‘finish’, runCopyImages);

}

 


function runCopyImages() {


// Copy image files to publish folder.

copyImages(theme, projectFolder, publishThemeFolder)

.on(‘finish’, runCopyCssNextThemeFiles);

}

 


// Copy css next theme files inside publish folder to the “App/Styles” folder.


function runCopyCssNextThemeFiles() {

copyCssNextThemeFiles(theme, publishThemeFolder)

.on(‘finish’, runGenerateCss);

}

 


// Generate css from css next files.


function runGenerateCss() {

generateCss(publishThemeFolder)

.on(‘finish’, runDeleteCssNextFiles);

}

 


// Delete all css next files in the publish folder.


function runDeleteCssNextFiles() {


const ccsNextFiles = path.join(publishThemeFolder, ‘**/*.cssn’);

log(`runDeleteCssNextFiles: ccsNextFiles – ${ccsNextFiles}`);

 

del.sync([ccsNextFiles], { force: true });

}

}

 

/**

* Log message to a log file, creating it, when it does not exist.

* The file will always be overwritten.

*/

function writeToLogFile(message) {

fs.writeFileSync(‘gulp.log.txt’, message);

}

 

exports.applyTheme = applyTheme;

exports.log = log;

exports.publishTheme = publishTheme;

 
 

 
 

Alter the .gitignore file

 
 

/App/Images/*.*

/App/Styles/variables.*

/App/**/*.css

!/App/Libraries/**/*.css

 
 

We excluded the copied “themed” images.

We excluded the copied “themed” variables.cssn.

We excluded all css, except the css in the libraries folder.

 
 

 
 

 
 

Now when you publish the project, the folder C:\Release\MyWebApp, should contain 2 “release builds” : Theme1 and Theme2.

Both containing the specific themed images and css.

  

Being forward compatible – Goodbye SASS hello CSSNext

Instead of being backwards compatible we want to be forward compatible.

But what do I mean with “forward compatible”?

Well that’s when we write our code against the next standard spec, but compile down to older specs to be backwards compatible, so for example:

 

TypeScript

 

We use TypeScript to write modern ES6, ES7, ES8 code, but we compile down to ES5 to be backwards compatible with older browsers.

 

CSSNext

 

The only reason we used SASS in the current project, was to re-use color variables in css.

Now the css next spec includes custom properties (variables), so to be forward compatible we decided to port our SASS to CSSNext.

 

CSSNext with PostCSS

 

PostCSS is a node package that can be installed by using NPM, it can be used to pre-process CSS by using JavaScript / TypeScript.

One of the many plugins of PostCSS is een CSSNext plugin, in the following example I will be using this plugin to convert CSSNext code into normal CSS3 code.

In this example I will be using Visual Studio 2015 update 3.

 

 

Create a new MVC web project

 

File > New > Project…
Installed > Templates > Visual C# > Web > ASP.NET Web Application (.NET Framework) > MVC

 

Add a package.json file to the root of the web application

 

{

“dependencies”: {
“angular”: “1.2.29”,

“es5-shim”: “>=4.5.9”,

“es6-shim”: “>=0.35.1”,

“spin.js”: “>=2.3.2”

},
“devDependencies”: {

“del”: “>=2.2.1”,

“gulp”: “>=3.9.1”,

“gulp-debug”: “>=2.1.2”,

“gulp-postcss”: “>=6.1.1”,

“gulp-rename”: “>=1.2.2”,

“gulp-util”: “>=3.0.7”,

“postcss-import”: “>=8.1.2”,

“postcss-cssnext”: “>=2.7.0”

},
“name”: “WebApplication1”,

“private”: true,

“scripts”: {

“gulp”: “gulp”

},
“version”: “1.0.1”

}

 

Add a gulpfile.js to the root of the web application

 

/**

* The version of gulp and all it’s dependencies are managed in the package.json file.

*/

‘use strict’;

// Dependencies

const gulp = require(‘gulp’);

const postcss = require(‘gulp-postcss’);

const postcssImport = require(‘postcss-import’);

const postcssNext = require(‘postcss-cssnext’);

const rename = require(‘gulp-rename’);

const defaultTheme = ‘Stigas’;

/**

* The default task.

*/

gulp.task(‘default’, function () {

});

gulp.task(‘apply-theming’, function () {


var plugins = [

postcssImport,

postcssNext

];


return gulp.src(‘./Content/Site.cssnext’)

.pipe(postcss(plugins))

.pipe(rename({

extname: “.css”

}))

.pipe(gulp.dest(‘./Content’));

});

Add a “Content/variables.cssnext” file

 

:root {


–mainColor: rgb(255, 0, 0);

}

 

Rename the existing Site.css to Site.cssnext

 

At the following text at the top of the Site.cssnext file: @import
“./variables.cssnext”;

And at the following css rule at the end of this script:

p {


color: var(–mainColor);

}

Now run the gulp task “apply-theming” by using the Task Runner Explorer or on the command line: npm run gulp — apply-theming

 


 

 

Now when you run the web application you should see the text in red:


 

 


Communicate between controllers in Angular by using a simple pubsub service in TypeScript.

 

I created a really simple angular PubSubService in TypeScript, to allow communication between controllers or directives or services.

 

In the example below, controller 1, fires an event and controller 2 reacts to the firing of the event.

 

 

module dev {
    "use strict";

    var appModule = angular.module("myApp", []);

    appModule.controller("MyController1", ["$scope", "pubSubService", ($scope, pubSubService)

    => new dev.MyController1($scope, pubSubService)]);

    appModule.controller("MyController2", ["$scope", "pubSubService", ($scope, pubSubService)
    => new dev.MyController2($scope, pubSubService)]);

    

 

    export class MyController1 {
        constructor(public $scope: ng.IScope, public pubSubService: PubSubService) {
            // Fire an an event
            pubSubService.publish("my-custom-event", "some publisher data");
            }
    }

    export class MyController2 {
        constructor(public $scope: ng.IScope, public pubSubService: PubSubService) {
            this.handleMyCustomEvent = this.handleMyCustomEvent.bind(this);

            // Subscribe to be notified, when "my-custom-event" is fired.
            pubSubService.subscribe("my-custom-event", this.handleMyCustomEvent);
        }
   
        handleMyCustomEvent(data: any) {
        // Do something, when an event is fired from MyController1.
        }
    }

 

    /**
     * This service can be used to share data between controllers by using a pub sub mechanism.
     */
    export class PubSubService {
        private nextListenerIndex: number;
        private listeners: Array<IListener>;

        constructor() {
            this.listeners = [];
            this.nextListenerIndex = 0; // The first subscription will be located at index 0;

            this.publish = this.publish.bind(this);
            this.subscribe = this.subscribe.bind(this);
            this.unsubscribe = this.unsubscribe.bind(this);
        }

        /**
         * Publish an event.
         * All subscribers will be notified.
         * @param name, is the name of the event and is case insensitive.
         */
        publish(name: string, data?: any) {
            for (var i = 0, length = this.listeners.length; i < length; i++) {
                const listener = this.listeners[i];
                if (listener && listener.name.toLowerCase() === name.toLowerCase()) {
                    listener.handler.call(null, data, listener.subData);
                }
            }
        }

        /**
         * Subscribe to be notified, when an event is published.
         * @param name, is the name of the event and is case insensitive.
         * @returns A token, that can be used to unsubscribe.
         */
        subscribe(name: string, handler: (data?: any, subData?: any) => void, data?: any): number {
            var token = this.nextListenerIndex;
           
            this.listeners[token] = {
                handler: handler,
                name: name,
                subData: data
            };
            this.nextListenerIndex += 1;

            return token;
        }

        /**
         * Remove the event listener subscription.
         * @param token received on subscribing to an event listener.
         */
        unsubscribe(token: number) {

            // This will create holes in the array, but for now we do not care.
            this.listeners[token] = null; 
        }
    }

    export interface IListener {
        // This function will be called when an event is published.
        // Data is the data from the publisher, subData is the data from the subscriber.
        handler: (data?: any, subData?: any) => void;
        name: string;
        subData?: any; // Data from the subscriber.
    }

    angular.service("pubSubService", () => new PubSubService());
}

Autofill issues: This is the first time, Chrome disappoints me

When I set the attribute “autocomplete” to the value “off” on a form element, I expect Chrome, to NOT autofill fields in the form, but that’s not the case.

 

Even if you also add the autocomplete attribute to the input element with value “off”, this is not the case.

 

To get it working I had to add autocomplete=”off” to the form tag and add autocomplete=”new-password” to the <input type=”password” /> field.

How to use angular in a fancybox dynamically shown by jquery

In a brownfield application I encountered a old fancybox jquery plugin. This plugin was used throughout the whole application. This fancybox is just a modal dialog.

I wanted the content of the fancybox to be handled by angular.

 

To accomplish this, I used the following code:

 

image

 

 

You can find the code at:

 

https://github.com/roelvanlisdonk/Research/tree/master/Base/Web/src/Web/wwwroot/blog/fancybox

Fix: Visual Studio doesn’t use or can’t find TypeScript typings (*.d.ts) in a .net core project

 

I added some TypeScripts typings to a .net core project in Visual Studio 2015  (version 14.0.25123.00 Update 2), by using the NPM package “typings”, but the added *.d.ts files, were not picked up by Visual Studio, this was caused by excluding the “wwwroot” folder in the tsconfig.json,

 

after removing the wwwroot folder from the exclude array, the typings were correctly found and used.

 

 

 

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "system",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es6"
  },
  "exclude": [
    "node_modules",

     "wwwroot" <========================= Remove the wwwroot
  ]
}

Yes, Yes–Integrated Terminal in Visual Studio Code

 

The killer feature I was missing in Visual Studio Code was a integrated terminal.

 

More and more I use the command line for all kinds of tasks, but I don’t want to leave my editor, so I’m very glad that the visual studio code team decided to create a integrated terminal, currently it can only by found in the insiders builds, but a stable release containing the integrated terminal is on it’ s way.

 

To open the integrated terminal hit CTRL + `.

 

Event the shortcut is convenient Smile.

 

So to install all the npm packages in your project just hit CTRL + ` and enter npm install:

 

image

Some nice new features are coming to TypeScript

 

npm for type definition files

One of the things that annoyed me was the tsd tool for installing type definition files.

Why can’t I just use npm, for installing type definition files. I use npm for installing external libraries en tooling so why not type definition files.

 

Well they are working on just that, kudos to the TypeScript thing.

 

Non nullable types

An other thing is non nullable types, I certainly want to have that in TypeScript.

It will be possible to tell the compiler, a certain variable is a string and not null or undefined. But you can also write: const x : string | null which means, x is a string or null but not undefined.

 

Down level async await support

TypeScript code which uses async await can target ES5

 

http://video.ch9.ms/ch9/4ae3/062c336d-9cf0-498f-ae9a-582b87954ae3/B881_mid.mp4