5 application showed a blank page instead of an error page?

The reason is because you did not enable showing Error Page

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    // ...

    // Add the following to the request pipeline only in development environment.
    if (env.IsDevelopment())
        // Add Error handling middleware which catches all application specific errors and
        // send the request to the following path or controller action.

    // ...

With thanks to Tugberk!

PInvoke on CoreCLR on OS X

I spent a little time exploring how well CoreCLR works on OS X, and seeing what it’ll take to run MonoMac on the CoreCLR. Unfortunately, I didn’t have enough time to do everything I wanted to do, but here’s a summary of what I’ve found.

1. CoreCLR is relatively easy to set up, but figuring out what versions of DLLs to link to can be hard work.

Setting up CoreCLR is straightforward

$ dnvm install 1.0.0-beta8-15564 -r coreclr -a x64

This downloads the runtime and places it in ~/.dnx/runtimes/dnx-coreclr-darwin-x64.1.0.0-beta8-15564.

The dnvm use 1.0.0-beta8-15564 -r coreclr -a x64 command sets the current path to the bin directory under the runtime, which has its own copy of dnx.

On the CoreCLR you need to spell out every assembly your program depends on.

Take this working example


    "version": "1.0.0",
    "dependencies": {
    "frameworks": {
        "dnxcore50": {
            "dependencies": {
                "System.Runtime": "4.0.0-beta-*"


    "version": "1.0.0",
    "dependencies": {
    "frameworks": {
        "dnxcore50": {
            "dependencies": {
                "System.Runtime": "4.0.20-beta-*"

Will blow up the compilation with the following cryptic message:

(1,29): DNXCore,Version=v5.0 error CS0234: The type or namespace name 'AssemblyFileVersionAttribute' does not exist in the namespace 'System.Reflection' (are you missing an assembly reference?)
(2,29): DNXCore,Version=v5.0 error CS0234: The type or namespace name 'AssemblyVersionAttribute' does not exist in the namespace 'System.Reflection' (are you missing an assembly reference?)
(3,29): DNXCore,Version=v5.0 error CS0234: The type or namespace name 'AssemblyInformationalVersionAttribute' does not exist in the namespace 'System.Reflection' (are you missing an assembly reference?)
(1,58): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.String' is not defined or imported
(2,54): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.String' is not defined or imported
(3,67): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.String' is not defined or imported
/Users/Chui/Toyapps/CoreClrTest/ConsoleTest/Program.cs(7,18): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Object' is not defined or imported
/Users/Chui/Toyapps/CoreClrTest/ConsoleTest/Program.cs(13,23): DNXCore,Version=v5.0 error CS0518: Predefined type 'System.Void' is not defined or imported
/Users/Chui/Toyapps/CoreClrTest/ConsoleTest/Program.cs(21,32): DNXCore,Version=v5.0 error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

So somehow System.Runtime 4.0.20 isn’t good enough, and there’s a reference to a signed assembly for version But actually it means that I’d forgotten to run dnu restore on the project.

2. mscorlib (as of Beta 8) is still missing important properties like [System.Type]::Assembly. This means no NancyFX and no Autofac.

3. However, PInvoke works. Which is good, since MonoMac uses a lot of it.

Here’s an example

// file: ffi_test.c
int ffi_test()
    return 42;

$ gcc -dynamiclib -o ffi_test.dylib ffi_test.c
namespace ConsoleTest
    using System;
    using System.Runtime.InteropServices;

    public class Program

        private static extern int ffi_test();

        public static void Main()
            var answer = ffi_test();
            System.Console.Out.WriteLine("The answer is of course: " + answer);

Powershell your way to backing up SQL database to Azure

The script below shrinks the database and then backs it up to azure.

Azure storage accounts have an account name, and two passwords (known as primary and secondary access keys).

The storage account name forms a unique path for your storage. Say your storage accountname is joebloggs, then the path to your storage is

Files are not stored directly under the storage url. Instead they must be stored in containers which are a little bit like directories. The reason we don’t call these directories is because an Azure storage account can also hold table storage for tabular data.

Firstly, you’d probably want to shrink your database


# Use the logical name, i.e. excludes directory and file extensions
Invoke-SqlCmd -Query 'USE sampledb'
Invoke-SqlCmd -Query 'DBCC SHRINKFILE (''sampledb'')'
Invoke-SqlCmd -Query 'DBCC SHRINKFILE (''sampledb_log'')'

Invoke-SqlCmd -Query 'ALTER DATABASE sampledb SET RECOVERY FULL'

Then you’ll need to save the login and access key to the Azure storage in SQL Server. This is known as a credential

New-SqlCredential -Name azure-joebloggs -Identity joebloggs -Secret 'Your-Very-Long-Access-Key'

Warning: the following operation will fail if the file already exists in the storage container

Backup-SqlDatabase -ServerInstance $Env:COMPUTERNAME -SqlCredential azure-joebloggs `
    -BackupFile '' `
    -Database 'sampledb'

# this will overwrite the original back up file
Backup-SqlDatabase -ServerInstance $Env:COMPUTERNAME -SqlCredential azure-joebloggs `
    -BackupFile '' `
    -Database 'sampledb' -ReplaceDatabase

# this will create a new backup file named automatically by SQL Server
Backup-SqlDatabase -ServerInstance $Env:COMPUTERNAME -SqlCredential azure-joebloggs `
    -BackupContainer '' `
    -Database 'sampledb'

To restore the database, just change “Backup-SqlDatabase” to “Restore-SqlDatabase”

Restore-SqlDatabase -ServerInstance $Env:COMPUTERNAME -SqlCredential azure-joebloggs `
    -BackupFile '' `
    -Database 'sampledb'

It is not obvious how one can change the SQL Server authentication mode on PowerShell. This one works:

# Enable SQL Authentication
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') <serverName>
$s.Settings.LoginMode = [Microsoft.SqlServer.Management.SMO.ServerLoginMode]::Mixed
Stop-Service -ServiceName MSSQLServer
Start-Service -ServiceName MSSQLServer

Alternately, you can do this using PowerShell Paths. It is somewhat prettier.

Import-Module sqlps -DisableNameChecking
$s = (Get-Item SQLSerer:\SQL\<serverName>\<InstanceName>)
$.Settings.LoginMode = [Microsoft.SqlServer.Management.SMO.ServerLoginMode]::Mixed
Stop-Service -ServiceName MSSQLServer
Start-Service -ServiceName MSSQLServer

Enabling ngrok to connect to IIS Express


ngrok http -host-header=rewrite localhost:19301

Why you might need this

If you want to test what your mobile site looks like using a real device, and the site is running locally on your PC using IIS Express and only accessible via localhost. ngrok is a 1 minute solution to make it accessible.

If you want to test a webhook while you are still developing. For instance, SendGrid will call webhooks that notify you when an email bounces.

Step 1: Download ngrok, and unzip into


Step 2: Run your web app and note what port it runs on

Step 3: start


run the command below, replacing 19301 with the port your web app is running on

C:\Users\Chui> cd \bin
C:\bin> ngrok.exe http -host-header=rewrite localhost:19301

Step 4: Note the URL that ngrok shows on the command prompt, it typically looks like, and you can visit either the http or https url from your mobile device. Note that there is no security. Your app is publicly accessible, and you should secure it appropriately.

Forwarding           -> localhost:19301
Forwarding           -> localhost:19301


What is ngrok, and how does this work?

ngrok has a server that is publicly accessible. When you run ngrok locally, it connects to the publicly accessible server listening for commands. When a browser visits the url on the public website, ngrok.exe calls the website running on your computer and forwards the page back to the browser.

What about url reservation using netsh http add urlacl url= user=Everyone? Or changing IISExpress application.config ?

This isn’t necessary because the command aboves gets ngrok to rewrite the Host header so that the request appears as if it is meant for localhost.


Creating a Message Only window using WPF

Classic Win32 applications use a Window as basic unit of abstraction, including using it for Inter Process Communication. For example, a message only window is hidden, and we only listen to to for messages that are posted from elsewhere. To create a message only window, it must have its parent HWND set to HWND_MESSAGE (i.e. IntPtr(-3)). Then custom messages can be sent as long as the message id falls within the bounds specified here.

While WPF does away with Windows, the interop library provides the basic building blocks for us to create Win32 windows.

/// <summary>
///     Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
    private readonly IntPtr _sourceHandle;

    // Valid ranges here:
    private const uint CustomMessage = 0x8801; 

    public MainWindow()

        _sourceHandle = CreateMessageOnlyWindow();
        Button1.Click += SendMessageToMessageOnlyWindow;

    private IntPtr CreateMessageOnlyWindow()
        IntPtr HWND_MESSAGE = new IntPtr(-3);
        var source =
            new HwndSource(new HwndSourceParameters() { ParentWindow = HWND_MESSAGE});
        return source.Handle;

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
        if (msg == CustomMessage)
                new Action(delegate { Button1.Content = lparam.ToInt32().ToString(); }));
            handled = true;

            return new IntPtr(20);
        return IntPtr.Zero;

    private void SendMessageToMessageOnlyWindow(object sender, RoutedEventArgs e)
        var result = SendMessage(_sourceHandle, CustomMessage, IntPtr.Zero, new IntPtr(DateTime.Now.Second));
        Contract.Assert(result.ToInt32() == 20);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

Managed Metadata in Sharepoint 2013 DisplayTemplate

Applicability: Sharepoint 2013, Sharepoint Online

Display Templates in Sharepoint allow individual content types to be displayed differently in Sharepoint Content Search results (template files are here _catalogs/masterpage/Display Templates/Content Web Parts. In addition, since each content type can have different columns, the display templates allow properties to be remapped to rendered fields as well.

Display templates are by default deactivated, and requires a manual activation step in the Site Settings, under Publishing Infrastructure.

Each display template has an ugly looking metadata segment that makes it looks like MS Word-generated HTML.

<mso:ManagedPropertyMapping msdt:dt="string">
  'RenderPropertyName'{Web Part Label}:'PublishingImage;RefinableText01;...',
  'Link URL'{Link URL}:'Path',
  'Line 1'{Line 1}:'Title',
  'Line 2'{Line 2}:'Description',
  'Line 3'{Line 3}:'',

The key take away here are:

  • when rendering in the display templates, use RenderPropertyName;
  • when presenting the property to be customised in the Web Part – use Web Part Label;
  • to set the default properties, set them in the final segment.

The actual rendering appears to be done on the client-side using a custom Javascript templating language that is reminiscent of PHP.

var propertyValue = $getItemValue(ctx, "RenderPropertyName");
_#= propertyValue =#_

Hat tip to @cann0nf0dder for working this out!

Clean Code with AngularJS on Windows – Part 2

This is Part 2 of a series on AngularJS testing.

Our basic test case is a user registration service.

using a TDD philosophy, we start with our failing test.

// file: tests/userReg.js
describe('Test Suite', function() {

  var scope;

  // before each test is run, load the userReg module

  // before each test is run, sets the scope
  beforeEach(angular.mock.inject(function($rootScope, $controller) {
     scope = $rootScope.$new();

  // single asynchronous unit test
  // by including 'done' argument, the test will not complete
  // until done() is called.
  it('service should asynchronously return true', function(done) {

    // inject() is kind of like a DI constructor
    // note that userRegistrationService is registered as a 
    // factory in the userRegApp module
    angular.mock.inject(function($q, userRegistrationService) {

        // mock the userRegistrationService.usernameExists()
        var deferred = $q.defer();
        spyOn(userRegistrationService, 'usernameExists').and.returnValue(deferred.promise);

            .then(function(result) {




We also need to configure karma.conf.js to load angular.js, angular-mocks.js, our source files and test files.

// Karma configuration

  // list of files / patterns to load in the browser
  files: [

Launch karma to test

$ node_modules/karma/bin/karma start karma.conf.js

Karma should spit out long error messages such as this:

 Error: [$injector:modulerr] Failed to instantiate module userRegApp due to:
 Error: [$injector:nomod] Module 'userRegApp' is not available! You either misspelled the module name or forgot to load it.

Create a new file called app/userRegistration.js

angular.module('userRegApp', [])
.factory('userRegistrationService', ['$http', '$q', function($http, $q) {
  return {
    usernameExists: function(userName) {

      // .NET developers may recognize deferred as
      // being the equivalent of TaskCompletionSource
      var deferred = $q.defer();
      $http.get('/webapi/v1/usernameExists/' + userName)
        .success(function(payload) { deferred.resolve(; })
      return deferred.promise;

Karma should report that the unit test passed.

INFO [watcher]: Added file "...../ngtest/app/userRegistration.js".
Chrome 39.0.2171 (Windows 8.1): Executed 1 of 1 SUCCESS (0.036 secs / 0.032 secs)