Caculate trendline datapoints in TypeScript

If you want to calculate trendline datapoints in TypeScript, you can use the following code:

 

 

 

Code

 

module helpers.math {
'use strict';
/**
 * Based off: https://github.com/Tom-Alexander/regression-js/blob/master/src/regression.js
 * @param known_y - Array of numbers representing the y-axis values, [1, 2, ...].
 * @param known_x - Optional array of numbers representing the x-axis values, when not supplied this parameter will be [1,2,..."y-axis values total count"].
 */

export function trend(known_y: Array<number>, known_x?: Array<number>): Array<number> {

const ylength = known_y.length;

// When "x-axis values" are not supplied, generate it as [1,2,..."y-axis values total count"].

if (!known_x) {
     known_x = [];

for (let xcounter = 0; xcounter < ylength; xcounter++) {
        known_x.push(xcounter + 1);
     }
 }

// The "data" should be in the format [[x[0], y[0]], [x[1], y[1]]], ...].

const data = [];

for (let ycounter = 0; ycounter < ylength; ycounter++) {
     data.push([known_x[ycounter], known_y[ycounter]]);
 }

let n = 0;

const results = [];
const sum = [0, 0, 0, 0, 0];
for (; n < data.length; n++) {
if (data[n][1] != null) {
         sum[0] += data[n][0];
         sum[1] += data[n][1];
         sum[2] += data[n][0] * data[n][0];
         sum[3] += data[n][0] * data[n][1];
         sum[4] += data[n][1] * data[n][1];
     }
 }

const gradient = (n * sum[3] - sum[0] * sum[1]) / (n * sum[2] - sum[0] * sum[0]);
const intercept = (sum[1] / n) - (gradient * sum[0]) / n;
for (let i = 0, len = data.length; i < len; i++) {
const trendY = data[i][0] * gradient + intercept;
     results.push(trendY);
 }

return results;
 }
}

 

 

 

Unit Test

 

const trend = helpers.math.trend;
'use strict';
describe('zvdz.helpers.calculate.trend', function () {
 it('given an array of points it should return an array of points representing the trendline of the given points.', function () {
    const known_y = [1,2,3,4,5,6];
     expect(trend(known_y)).toEqual([1, 2, 3, 4, 5, 6]);
 });
});

Shifting away from Windows PowerShell towards .NET Core

 

Now that .NET Core 1.0 is released I find myself coding more and more in .NET Core instead of Windows PowerShell scripts for every day automation. When you are developing you spend a portion of your time setting up environments, renaming, copying, processing files and folders, for that I used to write Windows PowerShell scripts.

 

 

With the release of .NET Core and its excellent command line and Visual Studio Code support, I’m writing plain old C#, but with dotnet run I can alter a C# file on the fly and run it immediately.

Plus the C# code is portable between my Windows Desktop, Mac Book Pro laptop and Linux servers, very nice!

 

 

 

Some examples

 

 

Deleting *.css files (excluding the libraries folder)

When you are writing your code in CSS Next you want to keep the CSS Next files in source control, but you don’t want to add the compiled css files in source control, to delete existing css files in a “App” folder, but not the css files in “App/Libraries” I wrote a little .NET Core code:

 

public
void DeleteCssFiles() {


string projectFolder = @”C:\Projects\MyWebApp”;


string appFolder = Path.Combine(projectFolder, “App”);


string librariesFolder = Path.Combine(appFolder, “Libraries”);


string csprojPath = Path.Combine(projectFolder, @” MyWebApp.csproj”);

 


int fileCounter = 0;


var files = FindFiles(new
DirectoryInfo(appFolder), “*.css”); // This will get *.css and *.cssn files on Windows, don’t know why.


foreach (FileInfo file in files)

{


if(

!file.FullName.StartsWith(librariesFolder) &&

!file.FullName.EndsWith(“.cssn”)

){

 

fileCounter++;


File.Delete(file.FullName);


Console.WriteLine($”Delete {file.FullName});

}

}

 


Console.WriteLine($”Total *.css files deleted = {fileCounter});

}

 

 

Rename all *.css files in the *.csproj file to *.cssn files (excluding the libraries folder) and make them build action “None”

 

Public async
Task RenameCssToCssnInCsProj() {


string projectFolder = @”C:\Projects\MyWebApp “;


string appFolder = Path.Combine(projectFolder, “App”);


string librariesFolder = Path.Combine(appFolder, “Libraries”);


string csprojPath = Path.Combine(projectFolder, @” MyWebApp.csproj”);


string csprojContent = File.ReadAllText(csprojPath);


int fileCounter = 0;

 


var files = FindFiles(new
DirectoryInfo(appFolder), “*.css”); // This will get *.css and *.cssn files on Windows, don’t know why.


foreach (FileInfo file in files)

{


var cssnPath = Path.ChangeExtension(file.FullName, “.cssn”);


if(

!file.FullName.StartsWith(librariesFolder)

){

 

fileCounter++;

 


string relativePath = file.FullName.Replace(projectFolder + @”\”, string.Empty);


string relativePathCssn = Path.ChangeExtension(relativePath, “.cssn”);


string find = $”<Content Include=\”{relativePath}\” />”;


if(csprojContent.Contains(find))

{


string replace = $”<None Include=\”{relativePathCssn}\” />”;


Console.WriteLine($”find {find});


Console.WriteLine($”replace {replace});

csprojContent = csprojContent.Replace(find, replace);

}

 


await CreateOrUpdateFile(csprojPath, csprojContent);

}

}

 


Console.WriteLine($”Total *.css files = {fileCounter});

}

 

 

 

Converting all css files in a Web Application to CSS Next files (where each CSS Next file depends on a shared “variables.cssn” file.

 

 

public
async
Task RenameCssToCssnOnDisk() {


string projectFolder = @”C:\Projects\ZvdZ\zvdzonline\Source\ZvdZOnline\ZvdZOnline.Web”;


string appFolder = Path.Combine(projectFolder, “App”);


string librariesFolder = Path.Combine(appFolder, “Libraries”);


int fileCounter = 0;

 


var files = FindFiles(new
DirectoryInfo(projectFolder), “*.css”); // This will get *.css and *.cssn files, don’t know why.


foreach (FileInfo file in files)

{


var cssnPath = Path.ChangeExtension(file.FullName, “.cssn”);


if(

!file.FullName.StartsWith(librariesFolder) &&

!File.Exists(cssnPath)

){

 

fileCounter++;

 


string relativePath = file.FullName.Replace(projectFolder, string.Empty);


Console.WriteLine($”relativePath {relativePath});


int seperatorCounter = relativePath.Split(@”\”.ToCharArray()).Length – 1;


Console.WriteLine($”seperatorCounter {seperatorCounter});

 


// Determine the “import” variables line, that should be added to each CSS Next file.


string relativePrefix = string.Empty;


for(var i = 0; i< seperatorCounter; i++) {

relativePrefix += “../”;

}


string importText = $”@import \”{relativePrefix}App/Styles/variables.cssn\”;”;


Console.WriteLine($”importText {importText});

 


string content = File.ReadAllText(file.FullName);


await CreateOrUpdateFile(cssnPath, importText + Environment.NewLine + Environment.NewLine + content );

}

}

 


Console.WriteLine($”Total *.css files renamed = {fileCounter});

}

 

 

 

Some Generic function used in the examples above

 

public
async
Task CreateOrUpdateFile(string path, string content)

{


byte[] result = Encoding.UTF8.GetBytes(content);


using (var stream = new
FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write, bufferSize: 4096, useAsync: true))

{


await stream.WriteAsync(result, 0, result.Length);

}

}

 


public
IEnumerable<FileInfo> FindFiles(DirectoryInfo folder, string pattern)

{


// Note: using EnumerateFiles is faster then using “GetFiles”.


return folder.EnumerateFiles(pattern, SearchOption.AllDirectories);

}


 

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