30 July 2014

Sharing code between a Xamarin Forms/MVVMLight app and EF-code first backend using Shared Reference Project Manager

Disclaimer

I am in the very early early stages of toying with Xamarin and it may well be that whatever I am doing here, is not the smartest thing in the world. This is a much as a report of my learning (may ‘struggle’ is a better word) as how-to. But what I describe here works – more or less – although it was a mighty hassle to actually get it working.

The objective

While I was having my first trials with Xamarin stuff, I turned to Entity Framework Code First because, well, when setting up a backend I am lazy. Without much thinking I made the models, using data annotations, and soon found out I had painted myself into a corner with a model that (very simplified) looks like this

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DemoShared.Models
{
   [Table("Pictures")]
    public class Photo
    {
      public long ID { get; set; }
      
     [Required]
      public string Name { get; set; }
    }
}

imageGuess what - data annotations don't work in PCL. Now what? Make a shadow class library for use on the client? That kind of went against my principles. So I decided to use the Shared Reference Project Manager.  This is a Visual Studio extension that can make basically any project shared, in stead of only between Windows Phone 8.1 and Windows 8.1 You can get it here.

Setting up the initial application

Using this tutorial by Laurent Bugnion I did set up my first Xamarin MVVM application. I created an app "DemoShared" and used the tutorial it up to the point where he starts making a new new xaml page (“Creating a new XAML page”).

Try to build the project. If the Windows Phone project fails with “The 'ProductID' attribute is invalid.. “ (etc), manually open it’s Properties/WMAppManifest.xml, for instance with NotePad, find “ProductID and “PubisherID” and place the generate GUIDs between accolades. This is a bug the Xamarin project template that I already reported.image

Basic setup of the backend

  • File/New Project/Web/ASP.Net Web application (it’s the only choice you have)
  • Choose a name (I chose DemoShared.Backend) and hit OK
  • Choose “Web Api” and UNSELECT “Host in the cloud”
  • Go to the NuGet Package manager and update all the packages, because a lot of them will be horribly outdated. Hit “accept” or “yes” on any questions
  • Delete the all folders except “App_Data”, “App_Start” and “Controllers” because we don’t need them
  • Delete BundleConfig.cs from App_Start, and remove the reference to it from Global.asax.cs as well
  • Add a (.NET) class library DemoShared.DataAccess
  • Install NuGet Package “EntityFrameWork” in DemoShared.Backend and DemoShared.DataAccess
  • Create a project DemoShared.Models of type Shared Project (Empty) of type Visual C#:

image

  • Right-click the DemoShared (Portable) project, select Add, then “Add Shared Project reference”, then select “DemoShared.Models
  • Repeat this procedure for DemoShared.DataAccess.
  • Also add a reference to System.ComponentModel.DataAnnotations to DemoShared.DataAccess.
  • Add DemoShared.DataAccess as a reference to DemoShared.Backend

Re-defining the models

The key point of this whole exercise is to re-use models. For one model class this is quite some overkill, but if you have a large collection of models, things becomes quite different. So anyway. I redefined the model class as follows:

#if NET45
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
#endif

namespace DemoShared.Models
{
#if NET45
   [Table("Pictures")]
#endif

  public class Photo
  {
    public long ID { get; set; }

#if NET45     
     [Required]
#endif
    public string Name { get; set; }
  }
}

Now in order to make this compile work the way it is intended on server, you will need to add the conditional compilation symbol “NET45” to all configurations of DemoShared.DataAccess

image

And then it compiles both into PCL and into the DataAccess project – without the attributes in the first, but with the attributes the second. Remember, this is just a really nifty formalized way of ye olde way of file linking.

Kick starting the Entity Framework

Following this tutorial – more or less, I added the following class to the DataAccess project:

using System.Data.Entity;
using DemoShared.Models;

namespace DemoShared.DataAccess
{
  public class DemoContext : DbContext
  {
    public DemoContext()
      : base("DemoContext")
        {
        }

    public DbSet<Photo> Photos { get; set; }
  }
}

And then to the web.config I added this rather hopeless long connection string:

<connectionStrings>
  <add name="DemoContext" connectionString="Data Source=(localdb)\v11.0;AttachDbFilename=|DataDirectory|DemoDb.mdf;Initial Catalog=DemoDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Rebuild the project. Now go to the Backend Controller folder, right click Add/Controller, select “Web API 2 Controller with actions, using Entity Framework” and in the following dialog, select the Model and Data Context class as displayed to the right

imageimage

imageNow if you set “DemoShared.Backend” as start-up project, set it’s startup URL to “api/photos” and start the project, you will automatically get a database “DemoDb” in “App_Data”.Is EF code first cool or what? And my data annotations are used correctly – the Photo type is stored in the “Pictures” table, just as I wanted.

image

Now I manually entered some data in the tables to get something to show, but of course you can also write an initializer like the EF tutorial describes, or write a separate project that prefills the the database. This is what I usually do, and that’s why I have put the DemoContext in a separate assembly and not in the web project – to be able to reference it form another project.

And now finally, to the Xamarin app

Adding the view model

First of all – start the NuGet package manager and add Newtonsoft Json.NET to DemoShared (Portable).

Then, add a “ViewModels” folder to DemoShared (Portable) to hold this class:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using DemoShared.Models;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;

namespace DemoShared.ViewModels
{
  public class MainViewModel : ViewModelBase
  {
    public MainViewModel()
    {
      Photos = new ObservableCollection<Photo>();
    }

    public string DataUrl
    {
      get { return "http://169.254.80.80:28552/api/Photos"; }
    }

    public ObservableCollection<Photo> Photos { get; set; }

    private RelayCommand loadCommand;

    public RelayCommand LoadCommand
    {
      get
      {
        return loadCommand ?? (loadCommand = new RelayCommand(
            () =>
            {
              var httpReq = (HttpWebRequest)WebRequest.Create(new Uri(DataUrl));
              httpReq.BeginGetResponse((ar) =>
              {
                var request = (HttpWebRequest)ar.AsyncState;
                using (var response = (HttpWebResponse)request.EndGetResponse(ar))
                {
                  if (response.StatusCode == HttpStatusCode.OK)
                  {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                      string content = reader.ReadToEnd();
                      if (!string.IsNullOrWhiteSpace(content))
                      {
                        var result = JsonConvert.DeserializeObject<List<Photo>>(content);
                        foreach (var g in result)
                        {
                          Photos.Add(g);
                        }
                      }
                    }
                  }
                }
              }, httpReq);
            }));
      }
    }

    private static MainViewModel instance;
    public static MainViewModel Instance
    {
      get
      {
        CreateNew();
        return instance;
      }
      set { instance = value; }
    }

    public static MainViewModel CreateNew()
    {
      if (instance == null)
      {
        instance = new MainViewModel();
      }
      return instance;
    }
  }
}

A rather standard MVVMLight viewmodel I might say, with the usual singleton pattern I use (I am not a big fan of "Locators"). When the command is fired, data is loaded from the WebApi url, deserialized to the same model code as was used to create it on the server, and loaded into the ObservableCollection. Nothing much special here.

There's one fishy detail - in stead of a computer name or “localhost”, there is this hard coded IP adress. We will get to that later.

Adding the Forms XAML page

Add a new Forms XAML page like this

image

Be aware that you have to enter the name manually, that’s a bug in the Xamarin tools, like Laurent Bugnion already described in his tutorial

Now, go to the DemoPage.Xaml.cs and set up the data context by adding one line of code to the constructor of the page:

public DemoPage()
{
  InitializeComponent();
  BindingContext = MainViewModel.Instance;
}

This will of course require a “using DemoShared.ViewModels;” at the top. Then we add our “XAML” to start page

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
		x:Class="DemoShared.DemoPage">
  <StackLayout Orientation="Vertical" Spacing="0">
    <Button Text="Click here" Command="{Binding LoadCommand}" 
            VerticalOptions="Start" HorizontalOptions="Center"  />
    <ListView ItemsSource="{Binding Photos}"
           RowHeight="50">
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <ViewCell.View>
              <StackLayout Padding="5, 5, 0, 5"
                           Orientation="Vertical"
                           Spacing="2">
                <Label Text="{Binding ID}" Font="Bold, Large" 
                       TextColor="Red"/>
              </StackLayout>
            </ViewCell.View>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackLayout>
</ContentPage>

Now this looks kind of familiar, but also kind of - not really. Binding looks kind of you would expect, some controls have weird options, as some... well, have you ever seen a ViewCell before? Working with this stuff really makes you appreciate things like IntelliSense and Blend, for you have none of the above. Good old handcrafted XML. But - it does carry the magic of Xamarin Forms.

Finally, we make our start page the start page of the app. Go to App.cs in DemoShared (Portable) and change the GetMainPage method to:

public static Page GetMainPage()
{
  return new DemoPage();
}

imageimageThen I set a multiple startup project, setting both the Windows Phone project as well as the backend project as startup.

And sure enough, there’s the Windows Phone startup screen with one button. And if I click it…

 

I get an error.

And now for the fishy detail

So your backend is a website - running under IISExpress. By default, that’s not accessible by anything else but localhost, and not by IP adress. What you have to do is explained mostly here. First, find your applicationhost.config. It’s usually in

  • C:\Users\%USERNAME%\Documents\IISExpress\config or
  • D:\Users\%USERNAME%\Documents\IISExpress\config

In my case it’s the second one. Now before you start messing around in it, you might want to make a backup. Then open the file, and search for the text "*:28552”. This should yield you the following line:

<binding protocol="http" bindingInformation="*:28552:localhost" />

Make a copy of this line, directly below it. Replace localhost by the IP adress you found earlier using "ping -t –4 <hostname>". Net result, in my case:

<binding protocol="http" bindingInformation="*:28552:localhost" />
<binding protocol="http" bindingInformation="*:28552:169.254.80.80" />

Then – very important – close Visual Studio and restart as Administrator. For then and only then IISExpress will be allowed to bind to something else than localhost. That crucial bit of information is unfortunately hard to find.

And then, sure enough:

imageimage

It runs on Windows Phone and Android. And I am sure, on Apple stuff too but lacking Apple hardware and developer account I could not test it.

BTW – and alternative to messing around with IIS Express settings is of course host the website in IIS. But that requires apparently the database being hosted in SQL*Server Express, so it can’t be in App_Data like this. Or something like that. I found this made a quick test easier.

One more thing

If you want to test this from outside your computer, on a phone, you might want to open the port for TCP traffic:

image

Conclusion

Using Xamarin allowed us to shared code over multiple platform, but the Shared Reference Project Manager we could also share with the server. And the ease with which you can get a database powered backend up and running using EF code first was also quite impressive to me. Now tiny details, like security and upgrades, I leave as exercise to the reader.

Code can be found here.

Post scriptum

My fellow MVP Corrado Cavelli pointed out to me that the LoadCommand method in the MainViewModel can be made considerably less complex by using the Microsoft ASP.NET Web API 2.2 Client NuGet Package. He turns out to be quite right. When you add this to the portable class library you can rewrite the command to a relatively simple

public RelayCommand LoadCommand
{
  get
  {
    return loadCommand ?? (loadCommand = new RelayCommand(
        async () =>
              {
                var client = new HttpClient { 
                   BaseAddress = new Uri("http://169.254.80.80:28552") };
                var response = await client.GetAsync("api/Photos");
                var result = await response.Content.ReadAsAsync<List<Group>>();
                foreach (var g in result)
                {
                  Groups.Add(g);
                }
              }));
  }
}
This requires "using System.Net.Http;" and "using System.Threading.Tasks;" to be added to the file, but it's a lot less cluttered than my original - copied somewhere from the interwebz - code. Thanks Corrado!

28 July 2014

AngularJS + TypeScript – how to setup a watch (and 2 ways to do it wrong)

Introduction

After setting up my initial application as described in my previous post, I went about to set up a watch. For those who don’t know what that is – it’s basically a function that gets triggered when a scope object or part of that changes. I have found 3 ways to set it up, and only one seems to be (completely) right.

In JavaScript, you would set up a watch like this sample I nicked from Stack Overflow:

function MyController($scope) {
   $scope.myVar = 1;

   $scope.$watch('myVar', function() {
       alert('hey, myVar has changed!');
   });
   $scope.buttonClicked = function() {
      $scope.myVar = 2; // This will trigger $watch expression to kick in
   };
}

So how would you go about in TypeScript? Turns out there are a couple of ways that compile but don’t work, partially work, or have unexpected side effects.

For my demonstration, I am going to use the DemoController that I made in my previous post.

Incorrect method #1 – 1:1 translation.

/// <reference path="../scope/idemoscope.ts" />
/// <reference path="../scope/person.ts" />
module App.Controllers {
    "use strict";
    export class DemoController {

        static $inject = ["$scope"];

        constructor(private $scope: Scope.IDemoScope) {
            if (this.$scope.person === null || this.$scope.person === undefined) {
                this.$scope.person = new Scope.Person();
            }
            this.$scope.$watch(this.$scope.person.firstName, () => {
                alert("person.firstName changed to " +
                    this.$scope.person.firstName);
            });
        }

        public clear(): void {
            this.$scope.person.firstName = "";
            this.$scope.person.lastName = "";
        }
    }
} 

The new part is in red. Very cool – we even use the inline ‘delegate-like’ notation do define the handler inline. This seems plausible, but does not work. What it does is, on startup, give the message “person.firstName changed to undefined” and then it never, ever does anything again. I have spent quite some time looking at this. Don’t do the same – read on.

Incorrect method #2 – not catching the first call

To fix the problem above, you need to use the delegate notation at the start as well:

this.$scope.$watch(() => this.$scope.person.firstName, () => {
    alert("person.firstName changed to " +
        this.$scope.person.firstName);
});

See the difference? As you now type a “J” in the top text box, you immediately get a “person.firstName changed to J” alert. Making it almost impossible to type. But you get the drift.

But then we arrive at the next problem – this is still not correct: it goes off initially, when nothing has changed yet. This is undesirable in most occasions.

The correct way

It appears the callback actually has a few overloads with a couple of parameters, of which I usually only use oldValue and newValue to detect a real change. Kinda like you do in an INotifyPropertyChanged property:

this.$scope.$watch(() => this.$scope.person.firstName, 
                         (newValue: string, oldValue: string) => {
    if (oldValue !== newValue) {
        alert("person.firstName changed to " +
            this.$scope.person.firstName);
    }
});

Now it only goes off when there’s a real change in the watched property.

…and possibly an even better way

I am not really a fan of a lambda calling a lambda in a method call, so I would most probably refactor this to

constructor(private $scope: Scope.IDemoScope) {
    if (this.$scope.person === null || this.$scope.person === undefined) {
        this.$scope.person = new Scope.Person();
    }
    this.$scope.$watch(() => this.$scope.person.firstName, 
                            (newValue: string, oldValue: string) => {
        this.tellmeItChanged(oldValue, newValue);
    });
}

private tellmeItChanged(oldValue: string, newValue: string) {
    if (oldValue !== newValue) {
        alert("person.firstName changed to " +
            this.$scope.person.firstName);
    }
}

as I think this is just a bit more readable, especially if you are going to do more complex things in the callback.

Demo solution can be found here

Update 27-02-2015: in the original post I swapped oldValue and newValue. No-one apparently even caught that, until my colleague Adrian Tudorache actually tried to follow this post. Thanks Adrian!

27 July 2014

Angularjs + TypeScript – setting up a basic application with Visual Studio 2013

Preface

No, I have not abandoned Windows (Phone) Development, and am not planning to do that. But apart from being Windows Platform MVP (as it is called since a few weeks) I actually have a day job as an employee building web applications. A few years ago I brought in the SPA concept in the company, first based on Knockout, later Angular, and after the 2014 Dutch TechDays and actually having dinner with Erich Gamma I decided it was time to take on TypeScript. And the overall team lead agreed. Provided I would give some good feedback on my experiences. Well, how about this? ;)

Although I have ascertained the combination actually works very well, I really found myself in unchartered territory and it took some time to get off the ground. I started my blog in 2007 because there were not enough complete samples in the .NET world – well, in the web world this apparently goes squared and with a few VERY notable exceptions people are quite terse when it comes to giving help. I even got told off on Stack Overflow for commenting on an answer containing typos and suggested some calls were synchronous while in fact they were not. This is a apparently a whole different world than the helpful #wpdev community. Still, I soldiered on, and decided to do this blog post – or actually series of blog posts, that’s forged from the same fire as this blog itself: of frustration about lack of helpful samples.

I am not saying this the definitive guide to AngularJS and TypeScript – but it’s how I got stuff working, how I got to understand it, or at least I think I understand it. I hereby invite anyone thinking I do things wrong to provide corrections, or write better blog posts with better samples themselves. I will gladly link to you for credits.:)

I am not going to have a discussion about why to use TypeScript. I am going to assume you want to use it, that you know that in order to use it you will need files that type JavaScript types, and that you know the basics of creating a module, class or interface. This is mostly a how-to, with some explanations on the side. This article learns you:

  • The initial setup of the solution
  • What initial NuGet packages to get
  • How to create the base application
  • How to set up your first scope, view, controller and route

Prerequisites

I used

The last one is optional, but recommended. It gives a few extra options, as generating JavaScript classes from C# and (when you are typing TypeScript) seeing your code converted to JavaScript on the fly.

imageCreating a new project

  • File/New Project/Web/ASP.Net Web application (it’s the only choice you have)
  • Choose a name (I chose AtsDemo) and hit OK
  • Choose “Web Api” and UNSELECT “Host is the cloud”
  • Go to the NuGet Package manager and update all the packages, because a lot of them will be horribly outdated. Hit “accept” or “yes” on any questions
  • Delete the “Areas” and “Fonts” folder cause we won’t need them

Getting the additional NuGet packages

This is quite a list. Maybe it is too much for just a basic start, but I decided to load it all.

  • Angularjs
  • Angularjs.Animate
  • AngularJS.Cookies
  • AngularJS.Route
  • AngularJS.Sanatize
  • Angularjs.TypeScript.DefinitelyTyped
  • Jquery.TypeScript.DefinitelyTyped

Note that this will also pull in Angularjs.Core.

The TypeScript.DefinitelyTyped--files are definitions that make it possible to use typed versions of Angular and Jquery from TypeScript.

Set up the initial application

  • Add a folder “app” to the root folder of your web project
  • Add a file AppBuilder.ts to the app folder with the following contents:
module App {
    "use strict";
    export class AppBuilder {


        app: ng.IModule;

        constructor(name: string) {
            this.app = angular.module(name, [
            // Angular modules 
                "ngAnimate",
                "ngRoute",
                "ngSanitize",
                "ngResource"
            ]);
        }

        public start() {
            $(document).ready(() =>
            {
                console.log("booting " + this.app.name);
                angular.bootstrap(document, [this.app.name]);
            });
        }
    }
}

This is the basic setup for a class I use to ‘construct’ my app. I don’t like to do this in the global namespace. So I create a basic ‘module’ – which I tend to think of as a .NET namespace – in the “AppBuilder” in the namespace “App”.

Then add another file to app, called “start.ts”, to create an AppBuilder instance and call “start” to bootstrap your Angular app:

/// <reference path="appbuilder.ts" />
new App.AppBuilder('atsDemo').start();

By the way, the first line indicates this uses a type defined in appbuilder.ts. It’s good practice to add these references, although mostly (but certainly not always) the compiler seems to find the references itself. You can make these references easily by dropping one file on top of the other form the solution explorer (so in this case, I dropped AppBuilder.ts on top of start.js).

Then

  • right-click your web project,
  • select properties,
  • go to the “TypeScript Build” tab,
  • select “combine Javascript into output file”
  • Enter “app/app.js” in the text box

Net result: see below.

image

Build your project, and verify that in the app folder the files “app.js” and “app.js.map” appear. Don’t include them in your project – when working with TypeScript it’s best to think of the created JavaScript as binaries. I use this options mainly to prevent loading order issues with regards to the resulting JavaScript, but it also makes the loading of JavaScript faster – now there’s only one file to load, in stead of more – and when you use TypeScript, it becomes quite a lot of files soon. Of course, you might also go for something like AMD with requirejs but for the somewhat smaller sites I tend to write, this works pretty well.

Then, open App_Start/Bundleconfig.cs and add the following lines just before the comment line "//Set EnableOptimizations to false for debugging. For more information,"

bundles.Add(new ScriptBundle("~/bundles/angular").Include(
    "~/Scripts/angular.js",
    "~/Scripts/angular-animate.js",
    "~/Scripts/angular-cookies.js",
    "~/Scripts/angular-route.js",
    "~/Scripts/angular-sanitize.js",
    "~/Scripts/angular-resource.js"
    ));

bundles.Add(new ScriptBundle("~/bundles/app").Include(
"~/app/app.js"));

This will include Angular files, as well as the JavaScript generated from the TypeScript. Finally, the last code line says

BundleTable.EnableOptimizations = true;

Change "true" to “false”. Then go to the Views/Shared/_Layout.cshtml. Change it’s contents to this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />
  <title>@ViewBag.Title</title>
  @Styles.Render("~/Content/css")
  @Scripts.Render("~/bundles/modernizr")
</head>
<body>
  <div class="container body-content">
    @RenderBody()
  </div>
  @Scripts.Render("~/bundles/jquery", "~/bundles/angular", "~/bundles/app")
  @RenderSection("scripts", required: false)
</body>
</html>

This will load the all the necessary scripts. Finally visit the Views/Home/Index.cshtml file. Delete it’s contents and replace it by just this:

@{
  ViewBag.Title = "Home Page";
}
 angulartest={{1+1}}
<div data-ng-view=""></div>

The “angulartest={{1+1}}“ line is just to see if Angular works. The div below it is the place where we will inject our views (see later).

Test the setup

Run the application from Visual Studio in your browser of choice. Hit F12 as soon as the browser starts. In your console it should say “booting atsDemo”, an in your browser window it should say “angulartest=2”

image

If you see this, then a) Angular is correctly loaded and activated (or else your browser window most likely displays “angulartest={{1+1}}”, meaning the expression is not evaluated and replaced and b) your application written in TypeScript actually has booted. Now it does nothing yet, but that’s the next step. For people who want to reference this stage, you can download the solution for this stage here. It may be useful if you just want a starter point.

Defining a scope object and a scope

The thing about TypeScript is typing, and you can also type your scope. Now the same caveats apply as to ‘normal’ Angular – if you go into a child scope or sub scope, or whatever they may be called, you can access but not change the parent scope – unless you specifically access it. That is quite of a hassle,  so it’s good practice to create an object to put on the scope, and manipulate that object – and not the scope itself. That’s basically Angular, and has nothing to do with TypeScript per se.

So I first added a folder “scope” to my app folder, and created the following object to hold person data:

module App.Scope {
    "use strict";
    export class Person {
        public firstName: string
        public lastName: string
    }
}
And then, to use it in the scope, I define and interface telling TypeScript that my scope, apart from the usual things that Angular provides, should at least contain a person of type Person:
/// <reference path="person.ts" />
module App.Scope {
    "use strict";
    export interface IDemoScope extends ng.IScope {
        person : Person
    }
}

Important to remember is that an interface is purely aTypeScript construct. It does not exist in JavaScript. If you look into the resulting app.js file, you won't find an IDemoScope. You won't find any interface. It's just a scaffold to help you not make typos in addressing this particular scope again. It needs to extend ng.IScope, a predefined interface from the DefinitelyTyped file.

Defining a controller

Add a folder “controller” to your app folder, and add a simple controller that allows you to enter the fields but also clear them again. 

/// <reference path="../scope/idemoscope.ts" />
/// <reference path="../scope/person.ts" />
module App.Controllers {
    "use strict";
    export class DemoController {
        static $inject = ["$scope"];

        constructor(private $scope: Scope.IDemoScope) {
            if (this.$scope.person === null || this.$scope.person === undefined) {
                this.$scope.person = new Scope.Person();
            }
        }
        public clear(): void {
            this.$scope.person.firstName = "";
            this.$scope.person.lastName = "";
        }
    }
}

As you can see, a controller is just a plain old class not extending anything special, with a pubic method to clear the fields of a person. It has a few things to note.

  • It’s the first class I show with an actual constructor. In that constructor it makes sure the person in the scope is initialized if necessary.
  • Note that putting “private” in front of a constructor parameter automatically creates a private class member which can be henceforth referenced by this.$scope
  • There is a static $inject variable. Although you are supposed to create the controller in the AppBuilder (see later) and only then inject the scope into in, apparently to prevent minification issues you have to provide this array too.

Defining a view

Create a folder “views” in you “app” folder, then add a file “PersonView.html” with the following very complex HTML in it:

<div>
  <div>
    <input type="text" data-ng-model="person.firstName" />
  </div>
  <div>
    <input type="text" data-ng-model="person.lastName" />
  </div>
  <div>{{person.firstName}}</div>
  <div>{{person.lastName}}</div>
  <button data-ng-click="myController.clear()">Clear</button>
</div>
This will give you a text box to enter the fields in, some feedback text below it to show data binding actually works, and a button to clear the fields again to see we can also actually can call bind to the controller - in this case a method.

Defining the controller in the AppBuilder

Just before the closing accolade } of the constructor, add this code:
this.app.controller("personController", [
    "$scope", ($scope)
        => new App.Controllers.DemoController($scope)
]);
or  if you want to super safe, explicitly type the scope explicitly so the controller get's the exact type of scope it expects.
this.app.controller("personController", [
    "$scope", ($scope : Scope.IDemoScope)
        => new App.Controllers.DemoController($scope)
]);

I find two things odd about this:

  • The fact that the first code works as well, while I would expect it would not – anything that is not typed explicitly is type “any” but clearly that does not fit into the constructor
  • This compiles without making a reference to the files containing IDemoScope and DemoController.

Anyway, for good measure I always add these references just to make sure. I have been running into some odd problems where references suddenly could not be found anymore.

Creating the route definition

Once again, just before the last accolade of the AppBuilder constructor, add this code:

this.app.config([
    "$routeProvider",
    ($routeProvider: ng.route.IRouteProvider) => { 
        $routeProvider
            .when("/person",
            {
                controller: "personController",
                controllerAs: "myController",
                templateUrl: "app/views/personView.html"
            })
            .otherwise({
                redirectTo: "/person"
            });
    }
]);
This defines a single route "person", which is also the default route, for which it will use the personController, the view personView.html, and what is very important and had me searching for quite some time - it defines a binding alias for the controller in the router, in code. Almost all the samples I found where controller definitions in html, e.g.
<div data-ng-controller="personController as myController">
...
</div>
but it took me quite some time to find out how to do it from code. Which I had to be able  to do, as I sometimes have use a different controller on the same view. Well, this is how you do that: use "controllerAs" in your router definition.

Kick start the router

Finally, to get the router working and started, add once again a piece of code just before the last accolade of the AppBuilder constructor :

this.app.run([
    "$route", $route => {
        // Include $route to kick start the router.
    }
]);

And we’re done… for now

imageIf you run the code, you should see the url in the browser go from http://localhost:3987/ to http://localhost:3987/#/person, indicating your router is now in control, and it should show the beautiful *cough* UI on the right. I typed “Joost” in the first box and “van Schaik” in the second and as you type, the line below it should change with it, indicating data binding works to the scope. And the “Clear” clears both the boxes and the display lines, showing binding to the controller works as well.

Conclusion

Setting up an Angular + TypeScript application in Visual Studio 2013 is not that hard to do, once you know how to do it. I hope this post will save other developers from the stumbling around I did. I am, by far, not finished, but what I now have are more small gotcha’s, things you need to know and things that are apparently common knowledge, self-explanatory, blindingly obviously or buried deep inside documentation everyone seems to know by heart as no-one explains or mentions them to mere mortal (web) developers such as myself ;) 

The full solution, as always, can be downloaded here, so you can see for yourself how things work in it’s totality, in stead of having to hunt it down piecemal from Stack Overflow.

Thanks

Special thanks to a few of the “notable exceptions” who helped me along the way to get here (and further)

16 July 2014

Cross-platform behavior for making screenshots in Windows (Phone) 8.1

Currently I am developing an app that should be able to share or save whatever is on the screen. I came upon this article by Loek van den Ouweland about RenderTargetBitmap and wondered if I could a) make this more generally (re)usable and b) make it play nice with MVVM.

The answer was – you guessed it – a behavior. The fun thing is, you can drag it onto any UI element, and it will create a screenshot of whatever what’s inside that element ( and that’s not necessary the whole screen!) and save it to storage. Two dependency properties, Target and Prefix, determine what message the behavior listens to, and what the file prefix is.

The main code of the functionality – which still looks a lot like Loek’s original sample – is in the behavior itself. To invoke it from the viewmodel, I call in the help of the MVVMLight messenger. So I start with the message that the viewmodel and the behavior use to communicate:

using GalaSoft.MvvmLight.Messaging;

namespace WpWinNl.Behaviors
{
  public class ScreenshotMessage : MessageBase
  {
    public ScreenshotMessage(object sender = null, object target = null, 
      ScreenshotCallback callback = null) : base(sender, target)
    {
      Callback = callback;
    }

    public ScreenshotCallback Callback { get; set; }
  }

  public delegate void ScreenshotCallback(string fileName);
}

This is a standard MVVMLight message, with the added extra that it can carry an optional payload of a callback. The behavior I created saves the file to a KnownFolder, but it can send the name of the file that’s been created back to the calling object by calling said callback.

The basics of the behavior – implemented once again as a SafeBehavior – is actually pretty simple:

using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
using GalaSoft.MvvmLight.Messaging;

namespace WpWinNl.Behaviors
{
  public class ScreenshotBehavior : SafeBehavior<FrameworkElement>
  {
    protected override void OnSetup()
    {
      Messenger.Default.Register<ScreenshotMessage>(this, ProcessMessage );
      base.OnSetup();
    }

    protected override void OnCleanup()
    {
      Messenger.Default.Unregister(this);
      base.OnCleanup();
    }

    private async void ProcessMessage(ScreenshotMessage m)
    {
      if (m.Target != null && Target != null)
      {
        if (m.Target.Equals(Target))
        {
          await DoRender(m.Callback);
        }
      }
      else
      {
        await DoRender(m.Callback);       
      }
    }
  }
}

So it listens to a ScreenshotMessage coming by. When Target (a dependency property in this behavior) is equal to the target specified in the message, the rendering is done. Think of Target as a shared key – this enables a viewmodel to fire a specific behavior using – usually - a string. This I show in the sample solution. If both the behavior’s target and the message’s target are null, it fires as well. You can use this if you only have one behavior and one call. If, however, the behavior is used on multiple places I strongly recommend specifying Target, or else you might get very interesting race conditions.

The actual rendering method is nearly all Loek’s code with some little adaptions:

private async Task DoRender(ScreenshotCallback callback)
{
  var renderTargetBitmap = new RenderTargetBitmap();
  await renderTargetBitmap.RenderAsync(AssociatedObject);
  var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

  var storageFile = 
    await KnownFolders.SavedPictures.CreateFileAsync(
      string.Concat(Prefix, ".png"),
      CreationCollisionOption.GenerateUniqueName);
  using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
  {
    var encoder = 
await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) renderTargetBitmap.PixelWidth, (uint) renderTargetBitmap.PixelHeight, 96d, 96d, pixelBuffer.ToArray()); await encoder.FlushAsync(); if (callback != null) { callback(storageFile.Name); } } }

It creates an unique file based on the Prefix dependency property in the “SavedPictures” known folder, renders the screen as a png file, saves it, and if so desired calls a callback transmitting the name back to that callback – most likely a method of the viewmodel, which can then act on it.

The rest of the behavior are the two dependency properties that I leave out for brevity's sake.You don’t need to use them at all – if you don’t set Prefix, it will use “Screenshot”

To use it: as stated earlier, drag it on top of the UI element you want to make screenshots of, then add for instance the following code to your viewmodel:

public ICommand ScreenshotCommand
{
  get
  {
    return new RelayCommand(() =>
    {
      var m = new ScreenshotMessage(this, 
        "screenshot", MyCallback);
      Messenger.Default.Send((m));
    });
  }
}

private void MyCallback(string name)
{
  Debug.WriteLine(name);
}
In the message I have set the target to "screenshot", so in the XAML it should now says
<Behaviors:ScreenshotBehavior Target="screenshot" Prefix="MyScreenshot"/>

or else the behavior won’t respond to the message. When it’s done, it writes the name of the created file to the console – not very useful in production scenario’s, but it shows it’s working. In this callback you can for instance inform the user the file has been saved, activate a share contract or whatever you feel is neccesary.

The fun thing is, of course, that in this awesome world we live today behaviors can actually be cross-platform and be defined in a PCL and run both on Windows Phone 8.1 as on “big Windows” 8.1 :).

MyScreenshotMyScreenshot (2)

In the demo solution, that contains both a Windows Phone App, a Windows App, and a shared project you will see I have once again dragged the Main.Xaml to the shared project just for the fun of it. Don’t forget to set access to the pictures library in both the app manifests. I always forget that.

MyScreenshotFor Windows, the pictures end up in my “USERPROFILE%\Picures” folder, in Windows Phone they end up in “Pictures\Saved Pictures”.

Interesting detail – I have set the application’s root grid background to gray. If I don’t set a color, the background of the picture on Windows is not black, but cropped to 1297x1080 in stead of 1920x1080 as is my native resolution. I have not been able to determine yet why this is.

I built this behavior on top of my WpWinNl 2.0.3 package, but you can easily adapt it to get it to work as a normal behavior just using the procedure I described here.

Oh and the picture? It’s just an old picture of my wife’s Mercedes truck back in 2004, when she and a colleague joined a Guinness Book of records attempt to create the longest truck convoy ever. This is a short stop at dyke road shoulder before the actual 9.5 km long convoy was assembled. Interesting detail: all 416 drivers were women. The convoy drove 22 km without any problems, and as my wife so aptly said – it was the first time she joined a traffic jam for fun.