ASP.NET Core: Unit testing with NUnit

In this post I reuse my sample project (ported to ASP.NET Core RC2)  but add a new Nunit test project to it.

Nunit has no testrunner ready yet that supports testing with dotNetCore. In fact, I didn’t find any testing framework that provides a GUI testrunner.  Even the Xunit  VS2015  integration that runs fine with RC1 appears to be broken for RC2.

NUnit has a lightweight testrunner NUnitLight. DotNet Core supports only two mode, ASP.NET MVC apps and Console apps.  So, what I did is use NunitLight inside a .Net Core console.

The code can be found here: https://github.com/geobarteam/myClub/tree/1-4.Add.NUnit.TestProject

  1. You should start by adding a new .Net Core Classlibrary project and addd the NUnit & NUnitLight dependencies.
    $ yo aspnet
    yeoman
  2. Modify the project.json file
    {
      "version": "1.0.0-*",
    
      "buildOptions": {
        "preserveCompilationContext": true,
        "emitEntryPoint": true
      },
    
      "dependencies": {
        "NUnit": "3.2.1",
        "NUnitLite": "3.2.1",
        "MyClub.Web": "1.0.0-*"
      },
    
      "frameworks": {
        "net461": { }
      },
    
      "tooling": {
        "defaultNamespace": "MyClub.Test"
      },
      "commands": {
        "test": "MyClub.Test"
      }
    }
  3. Modify the program.cs file
    public class Program
    {
        public static void Main(string[] args)
        {
            new AutoRun().Execute(args);
        }
    }
  4. Add a Nunit test file: SampleTest.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using NUnit.Framework;
    
    
    namespace MyClub.Test
    {
        [TestFixture]
        public class SampleTest
        {
           [Test]
            public void PassingTest()
            {
                Assert.AreEqual(4, Add(2, 2));
            }
    
            [Test]
            public void FailingTest()
            {
                Assert.AreEqual(5, Add(2, 2));
            }
    
            int Add(int x, int y)
            {
                return x + y;
            }
        }
    }
    
  5. Start the test session with “dotnet run” , you can also launch the test project and debug it through VS2015.
    nunitdotnetrun

ASP.NET CORE: Upgrade from RC1 to RC2

RC2 of .Net Core is out, so it’s time to upgrade your apps. The official documentation on how to upgrade can be found on: https://docs.asp.net/en/latest/migration/rc1-to-rc2.html

Here is the list of things I did to upgrade my existing ASP.NET CORE RC1 apps to RC2 :

Without VS2015:

  • Updated Yeoman: yo, choose Update Generators
  • With Yeoman create a new: yo aspnet, Web Application Basic.
  • Copy the content of the project.json to my existing application
  • From inside the project folder I run from the command line: dotnet restore
  • To test if everything work file: dotnet run

With VS20015:

  • Remove all VS2015 specific files: *.sln, .vs, *.xproj, *.xproj.user
  • Delete the existing package.json and copy an existing package.json inside the project (created with file, new project, web, ASP.NET Core Web Application).
  • Open the project with Visual Studio, here VS2015 crashed!
  • I needed to copy some parts of the xproj project file created with the template. Mainly the TargetFrameworkVersion part.
  • Re-open my solution, compile, run, it worked!

I had also to do minor adaptations in my code. I had to port from the namespace Microsoft.AspNet.* to Microsoft.AspNetCore.*

If you want to target the .Net framework you need to:

  1. Change the framework part of your project.json:
    “frameworks”: {
    “net461”: {}
    },
  2. Remove: “Microsoft.NETCore.App” from the dependencies.

Asp.Net Core: Building TypeScript with Gulp

In the preceding post I show how you can compile your TypeScript files with tsc. You can also simply use Visual Studio and enable the option: “Compile TypeScipt on Build” in the Build properties of your ASP.NET Core project.
While these are valid options I generally prefer to use Gulp to setup my own workflow.
In this post I’ll explain how you can use Gulp to setup and fine tune a Typescript build.

The code is available at: https://github.com/geobarteam/myClub/tree/1-3.Build.TypeScript.With.Gulp

$ git pull https://github.com/geobarteam/myClub.git 1-3.Build.TypeScript.With.Gulp

A) Pull the Gulp packages

First we’ll need to use npm to pull down some gulp packages that will help us in setting up our Typescript build.
The npm packages we need are:
“gulp-rimraf”: “^0.2.0”,

“gulp-sourcemaps”: “^1.6.0”,

“gulp-typescript”: “^2.13.4”,

“gulp-uglify”: “1.2.0”,

“rimraf”: “2.2.8”

gulpfiles1

To install these packages you can copy paste the list here above right under the “devDependencies” of the package.json file but I prefer to use npm.
To install these packages through npm, first navigate to the root of your project and use the command:
$ npm install [packagename] –save-dev
The –save-dev option is used to update our packages.json and put the new dependencies under the “devDependencies”.

B) Create the Gulp Tasks

Here we’ll use gulp-typescript to compile automate the typescript build. The documentation can be found here. Open the gulpfile.js and modify as follows:

  1. Require the packages
    var rimraf = require("rimraf"),
        gulpRimraf = require("gulp-rimraf"),
        concat = require("gulp-concat"),
        ts = require("gulp-typescript"),
        sourcemaps = require('gulp-sourcemaps');
  2. Add following path variables
    typescriptRoot: './scripts/',
    typescriptOut: webroot + 'js/',
    typescriptJs: './scripts/**/*.js',
    concatTsFileName: 'app.js'
  3. As we’ll use the tsconfig.json file to set the build properties we’ll create a project:
    var tsProject = ts.createProject(paths.typescriptRoot + 'tsConfig.json'); // use tsconfig.json
    
  4. Write the typescript build task
    gulp.task("tsbuild", function () {
        var tsResult = tsProject.src()
            .pipe(sourcemaps.init()) // needed to create sourcemaps
            .pipe(ts(tsProject)); // use tsconfig.json
    
        return tsResult.js
            .pipe(concat(paths.concatTsFileName)) // concat all output files into a sings js files
            .pipe(sourcemaps.write()) // write the sourcemap to be able to debug the ts files
            .pipe(gulp.dest(paths.typescriptOut)); // output the result on specific path
    });
  5. Write the clean tasks
    gulp.task("clean:tsout", function (cb) {
        rimraf(paths.typescriptOut + paths.concatTsFileName, cb); // rimraf is used to delete a folder
    });
    
    gulp.task("clean:scriptjs",
        function () {
            return gulp.src(paths.typescriptJs, { read: false })  // to clean up multiple files we need to use gulp-rimraf
              .pipe(gulpRimraf());
        });
    
  6. If you use VS2015 you can bind the gulp tasks with your VS build. The clean tasks should run before our build and after our build we should run first the ‘tsbuilld’ and then the ‘min’ task.
    gulpfiles2gulpfiles3
  7. Write a watch task if you want that the ts build is triggered when a ts file changes.
    gulp.task("watch:tsbuild", ['tsbuild'], function () {
        gulp.watch(paths.typescriptRoot + '**/*.ts', ['tbbuild']);
    });
  8. If needed, modify your angular script links. As the predefined min:js gulp task minifies all js files we can choose to use the minified app.js file in production.
     <environment names="Development">
            <script src="~/lib/jquery/dist/jquery.js"></script>
            <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
            <script src="~/lib/angular/angular.js"></script>
            <script src="~/js/app.js"></script>
        </environment>
        <environment names="Staging,Production">
            <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
                    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                    asp-fallback-test="window.jQuery">
    
            </script>
            <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/bootstrap.min.js"
                    asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                    asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
    
            </script>
            <script src="~/lib/angular/angular.min.js"></script>
            <script src="~/js/app.min.js"></script>
        </environment>

ASP.NET Core: Modify an Angular App to use Typescript

In this step we’ll modify our Angular 1.x app to use typescript.

Code can be found on: https://github.com/geobarteam/myClub

Branch: 1-2.Add.Typescript

Configure a Typescript Build

First install the latest Typescript compiler:

npm install -g typescript

Add a script folder to your project, this will be the home for your typescript files:

scriptfolder

Add a tsconfig.json file right under the scripts folder.

tsconfigs

The tsconfig.ts file contains the build options for the typescript compiler, it allows to run the Typescript compile process without specifying arguments.  To compile from the command line you should navigate inside the script folder and run: tsc

tsconfig.ts:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "compileOnSave": true
} 

Configure Typings

Typings allow to simply manage and install TypeScript definitions.

Install typings globally via npm:

npm install typings –global

To install typing definitions for angular 1.x, and Jquery use the command:

typings install angular jquery –ambient –save

 

Migrate the Angular scripts to use typescript

Move all your javascript angular scripts into the “scripts” directory and rename their suffix to “xxxxx.ts”.

tsconfigs

Add the “any” type to all your parameters and variables.
This is only required because we   used the “noImplicitAny”: false setting.  I like to use it as it makes clear that I should type all variables.

function myTeam($location:any) {
…
    }

You should now modify the tsconfig.ts to add the files to compile and set an output file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outFile": "../wwwroot/app/app.js"
  },
  "compileOnSave": true,
  "files": [
    "../typings/main.d.ts",
    "app.module.ts",
    "app.config.ts",
    "home.controller.ts",
    "myTeam.controller.ts"
  ]
} 

Inside _Layout.cshtml modify the angular scripts link to use the app.js script file:

…
<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="~/app/app.js"></script>    
</body>
</html>

When compiling the app in VS2015 or running tsc from the command line inside the script folder;  you should end up with a app.js file inside the wwwroot/app directory:

prscr

Test the app, it should still run exactly as before.

ASP.NET Core: Create an Angular App


aspnetcore

Here I’ll start a series of little tutorials on how to build from scratch a new Angular application with ASP.NET Core and MVC5.

The code used in these tutorials can be found under my git hub project: myClub

Every post has his own dedicated branch, so you can just use  “git checkout <branchname>” to find all the source code of the post you’re interesting in.

1) Create a new MVC core project

To generate a new project we’ll use Yeomen.  Open a commend prompt/bash shell or powershell shell on the location you want to put your new project =>

mkdir myClub

cd myClub

yo aspnet

yeomen

Choose Web Application Basic and provide a name.


 

2)          Add Angular to the MVC app

1)      Add Angular, from command line inside you project dir:
bower install angular angular-ui-router –save

Add angular to _layout.cshtml :

<script src=”~/lib/angular/angular.min.js”></script>


 

3) Create two js scripts under wwwroot:

app.config.js

(function () {
    'use strict';

    angular.module('myClub')
    .config(initrouter);

    function initrouter($stateProvider, $locationProvider, $urlRouterProvider) {
        $locationProvider.html5Mode(true);
        $urlRouterProvider.otherwise('/');
        $stateProvider
            .state(
                'home',
                {
                    url: '/',
                    templateUrl: 'app/home.html',
                    controller: "HomeController",
                    controllerAs: 'vm'
                }
            )
            .state(
                'myteam',
                {
                    url: '/myteam',
                    templateUrl: 'app/myTeam.html',
                    controller: "MyTeamController",
                    controllerAs: 'vm'
                }
            );
    }
})();

app.module.js

(function() {
    'use strict';

    angular.module('myClub', ['ui.router']);
})();

printscreenvscode


 

4) Add two controllers

myTeam.controller.js & home.controller.js

(function () {
    'use strict';

    angular
        .module('myClub')
        .controller('HomeController', myTeam);

    myTeam.$inject = ['$location'];

    function myTeam($location) {
        /* jshint validthis:true */
        var vm = this;
        vm.players = [];


        vm.title = 'Home';

        activate();

        function activate() {
           
        }
    }
})();

 

5) Add the two html pages inside the angular app

home.html

<div class="jumbotron">
    <div class="container">
        <h1>MyClub</h1>
        <p></p>
    </div>
</div>
<div>
    
</div>

myTeam.html

<div>
    <p>My Team</p>
</div>

 

6)  Reference the js scripts in _layout.cshtml

<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="~/app/app.module.js"></script>
<script src="~/app/app.config.js"></script>
<script src="~/app/home.controller.js"></script>
<script src="~/app/myTeam.controller.js"></script>

 

7)      Add the angular app inside idex.cshtml and move the navbar from _layout.html

index.cshtml

<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="~/app/app.module.js"></script>
<script src="~/app/app.config.js"></script>
<script src="~/app/home.controller.js"></script>
<script src="~/app/myTeam.controller.js"></script>

 

8)      Test the application

testpage

Asp.Net Core: How to configure your development environment on Linux

linuxVsCode

In this post I explain how to setup an ASP.NET 5 RC1 development environment on Linux Ubuntu 14.04 using vagrant.

Here you’ll find the vagrantfile and the provisioning script used to setup your vagrant box.

You can also use the provision.sh script to configure an Ubuntu 14.04 VM without using vagrant. Nevertheless I strongly recommend to use vagrant and to follow the steps depicted here.

Install Vagrant on your windows host

  • First download and install chocolatey: https://chocolatey.org/
  • Install Cygwin and add the openssh through cyg-get, open a command or powershell pompt and type following commands:

choco install Cygwin

choco install cyg-get

cyg-get openssh 

  • Setup Vagrant and virtualbox:

choco install virtualbox

choco install vagrant

  • Test vagrant is installed correctly, Open a Cygwin terminal and type:vagrant –v

The console should output your vagrant version.  If this isn’t working check your path variable, the bin directory of vagrant should be added, if this is not found, add the vagrant bin dir to your Path.  (It’s usually: C:\HashiCorp\Vagrant\bin)

 

Download and setup your Linux base box with Vagrant

  1. Open a Cygwin terminal and type:

$ mkdir data

$ mkdir netCoreRC1

$ cd netCoreRC1

 

  1. Configure and launch your vagrant box
    Copy the ”Vagrantfile” and “provision.sh” into the directory netCoreRC1 – you’ll find these files here: https://github.com/geobarteam/vagrant/tree/master/netCoreRC1

Now run:

$ vagrant up

This will start your vm and start the provisioning process.

To stop or reboot your vm:

$vagrant halt

To login into your box through ssh:

$ vagrant ssh

If you need to reconfigure your keyboard for your country type:

sudo dpkg-reconfigure keyboard-configuration

It’s also recommended to create your own user with:
sudo adduser [your user name]
and add it to the sudo group:
sudo adduser [your user name] sudo

You can login in the gui interface with user: vagrant and password: vagrant.

To complete the install you’ll need to reboot your vm: vagrant reload
To test that .net core and mono are installed open a terminal or ssh session and type:

dnvm list

You should see something like:
Active Version              Runtime Architecture OperatingSystem Alias

—— ——-              ——- ———— ————— —–

1.0.0-rc1-update1    coreclr x64          linux             *

1.0.0-rc1-update1    mono                 linux/osx       default

If something went wrong or you want to use another user than vagrant, open an ssh session under the new user account:

ssh -p 2222 [username]@localhost

Copy paste following commands into the ssh window:

curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh

dnvm upgrade -r coreclr

dnvm upgrade -r mono

This should install .net core & mono and fix your box, if you still encounter errors you can find the detailed install procedure of .net core under:
https://docs.asp.net/en/latest/getting-started/installing-on-linux.html

Install Visual Studio Code

Go to: https://code.visualstudio.com/ and download Vs Code.
You’ll find the install instructions under: https://code.visualstudio.com/

Once you’ve rebooted your dev box you can start experimenting with asp.net 5.

A good point to get started is to use yo men (it was already installed through the provisioning step) to create an empty Asp.Net 5 app as explained here: https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-app-using-vscode/

Have fun!

 

Setup, develop and deploy your ASP.NET MVC Umbraco website on Azure

To run Umbraco on Azure you can choose to use the build in Azure template.

pic1

 

For simple websites this could do the job but if you want to extend the portal with your own code or if you want to version control your site you’re better of starting with a blank MVC website.

 

Umbraco development lifecycle

Managing the lifecycle of an Umbraco application is somewhat challenging as Umbraco is one platform made out of several components (code/DB/content) and it’s not always clear what you need to deploy to promote content or features.  Especially deploying database changes can be cumbersome.  I personally chooses to avoid to have to stage DB changes by running all my environments (local/integration/production…) on a single DB hosted on Azure.

Because Umbraco already has a notion of staging you can for most cases work safely on the production database from your local machine without fearing to impact production.   Nevertheless when I need to make risky changes to my application or when I need to test a major Umbraco upgrade then I setup a clone of my production DB and do the development and testing on the clone.

For most of the changes my development cycle goes as follow:

  1. All my changes are made locally through the local umbraco portal (running on my local machine) or for Extensions through Visual Studio.
  2. When new content is added to the site I make sure these are included in my local Visual Studio project.
  3. I make sure that everything run nice locally.
  4. I check-in all the changes
  5. Publish the changes to Azure through the publish wizard.
  6. Test that everything runs fine in production.
  7. Promote the content once everything is tested

Umbraco first deployment

In this part I explain the steps to take to deploy the skeleton of an empty ASP.NET MVC Umbraco website.

Through the Azure portal:

  • Create a SQL server DB, don’t forget to note your password!
  • Create a new web app

Open VS: Start new project, Web, Asp.Net web application

Manage Nuget packages, umbracoCms

 

pic2

 

Click RUN in VisualStudio and launch the website locally.

Enter you Name, email & password and click Customize.

As Database type choose Microsoft SQL Azure.

You can find your connection details from the Azure portal (via old portal): select your DB, dashboard, Show Connection strings.
Use the ADO.NET connectionstring, copy each relevant part in the textboxes, for the server you need to provide the “server” part but without the leading “tcp”.
Click next.

Before publishing your website to Azure you first need to include files/folders to your project:

  • App_browsers
  • App_Plugins
  • umbraco
  • umbraco_client
  • config\splashes
  • css
  • js
  • media
  • scripts
    If you used a template also include the cshtml files under the Views folder.

 

pic3

Also set the build actions of the following web.config files to “none”.

– \umbraco\install\web.config

– \umbraco\Xslt\Web.config

 

pic4

Now publish the website: right-click your web project, choose publish.
Select your Azure Web App, the connectionstring should be retrieved by VS from your project.

 

If you followed everything in the exact order you should see your website running on Azure!

Links to learn Kodu

Here a couple of links in dutch, french and English with info on how to learn Kodu to kids:

In het Nederlands:

http://www.bs-windekind.be/Computerhuisje/Afbeeldingen_downloads/Programmeren%20met%20KODU.pdf

Vidéos

Les1: Basis

https://www.youtube.com/watch?v=NpY6-qIJMUg

Les2: Uitgebreid

https://www.youtube.com/watch?v=qCFxZU-1dqo

Les3: Vijand

https://www.youtube.com/watch?v=ZRF7cgOQHwM

Les4: Padden

https://www.youtube.com/watch?v=qe8pEuvKKEo

Les5 : Race Game

https://www.youtube.com/watch?v=gwQG-BcWZhs

Getting started with Kodu Game Lab

http://www.cs.unb.ca/~wdu/gamecamp/kodu-manual-2010.pdf

Tutorial pdf:

http://resources.hkedcity.net/downloadResource.php?rid=1356004239&pid=1142185599

Videos

Basics :

https://www.youtube.com/watch?v=XXhJ1_ijE7k

Football :

https://www.youtube.com/watch?v=zRZp27K6dUc

Racing Game :

https://www.youtube.com/watch?v=eRJuEm0-vSA

Kodu en français

Installer : http://jdolle.simdif.com/programmation_jeux.html

Initiation :

http://edutechwiki.unige.ch/fr/Kodu

Vidéos

Leçon 1:

https://www.youtube.com/watch?v=xdxztxjJu98

Partie2 :

https://www.youtube.com/watch?v=gfePm7VpK4A

Partie3 :

https://www.youtube.com/watch?v=71GDXPp8Ez4

Learning Arduino for kids (or beginners)

ArduinosKids

Through this link you can download my course for Arduino beginners. This course is one of the many I use to entertain kids during our coding-dojos sessions.  Yesterday it was the first time in Brussels we gave an Arduino session. We got kids going from 10 to 14 years. The session was a success. Despite the fact that none of them had any electronic or c-like programming background most of them managed to build one or several projects and present it to their colleagues.

Each project is intended to be built in two steps.  First the students can simply follow the schematic and can copy/paste the code they’ll find by following the provided link.  Then they need to complete a simple assignment consisting in extending what they build in the first step.  To complete the second step they need to make simple changes on the board and in the code.  Hints are provided to help them, so no real coding or electronic know-how is required.

The first project is simply making a led blink, the students should all start with this one.  Once the first assignment done they can choose between three different projects: a love-o-meter, music instrument and a lazer-tag.

Download link

Setting up continuous deployment for a Web app on Azure with a Visual Studio Online build

 

In this post I’ll create a continuous integration build with Visual Studio Online that deploys a Web App on an Azure Website.

Inside your VSO project click on the Build menu.

Click on plus sign and choose Visual Studio.

step1

 

Here we’ll configure our build to  produce and save the Web Deploy Package package file inside the staging directory.  This package will be used to deploy our Web App inside an Azure WebSite.

Copy paste the  following MSBuild arguments into the MSBuild Arguments:
/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation=”$(build.stagingDirectory)”

step2

Now we’ll add a “Azure Web App Deployment” step.  Click “Add, build step” and choose in the category “Deploy” => “Azure Web Site Deployment”, click “Add”

step3

If you don’t have a Subscription configured click on: manage

step4

Click on: Configure service endpoint

step5

Choose certificate and click on publishsettings xml file

step55

Once your settings downloaded, open the file with notepad and copy the: Subscription id, Subscription name and certificate.

step6

Click OK.

Go back to the Azure build and click on refresh.

step7

Provide the “Web App Name” of your Azure Web App.

Choose your region.

Under “Web Deploy Package” you need to provide the path of your Web Deploy Package .This relates to the package location provided as an MSBuild argument in your build step (see here above).  As we published the package under the staging directory and because the package is a zip file, the following search path will do the work:
$(build.stagingDirectory)\**\*.zip

step8

Click on Save and provide a name for your new build.

You can now test your build by right-clicking on it and choose “queue build”.

step9

step10

If you want your build to become a continuous deployment build (runs at every check-in or after some time after the check-in): Edit you build definition and look for Triggers:

step11