This blog attempts to be a collection of how-to examples in the Microsoft software stack - things that may take forever to find out, especially for the beginner. I see it as my way to return something to the Microsoft community in exchange for what I learned from it.

30 July 2014

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

Guess 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.

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

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:

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

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:

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

Now 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.

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:

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.

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();
}

Then 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:

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:

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:

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.

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

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.

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:

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:

27 July 2014

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

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.

Creating 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:

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:

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.

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,"

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”

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:

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.

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:

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.

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 controllerin the router, in code. Almost all the samples I found where controller definitions in html, e.g.

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 :

And we’re done… for now

If 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

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:

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:

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:

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:

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.

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.

For 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.

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.

Feedback, comments and tokens of appreciation

If you spot things that are incorrect, or if you don't understand what I mean, please drop a comment on the offending article and I will help you ASAP. You can e-mail me at joostvanschaik at outlook dot com or contact me via twitter.

If you find the information on this blog useful (and apparently some 600+ people per day do on average) please let me know as well, that encourages me to keep doing this. Or do tell others - that made me an MVP; who knows what more it might bring ;-P

Disclaimer and legal stuff

Although I take great care in providing quality samples, all postings, articles and/or files on this site are provided "AS IS" with no warranties, and confer no rights. The views expressed on this blog are strictly my own and do not necessarily reflect the views of my employer, or anyone else on the planet for that matter.

I usually make original content, sometimes building upon other people's work. Sometimes I explain things that can be found elsewhere because I felt what I read was not clear enough for my limited mind so I explain it the way it finally clicked with me. In all cases I take great pains to be sure to link to people or articles who deserve the credit. If you think I have shortchanged you on the credits please let me know.

Please note, I do not work for Microsoft and while I proudly wear the title of "Microsoft Most Valueable Professional", my opinions, files offered, etc. do not represent, are approved of, endorsed by or paid for by Microsoft. The only power behind it is me and my sometimes runaway passion for parts of Microsoft's technology.