When developing applications in Visual Studio I work with the keyboard most of the time. Throughout the years I learned a lot of short cuts to a lot of features. I’m sure most of you know and use these, too. But there are some features or actions that do not work well with the keyboard. For example closing all open tabs or opening the TFS source control explorer. For actions like this I had to use the mouse, just because it was faster than the keyboard. Until I learned about this feature a while ago.

A couple of versions of Visual Studio ago there was a search box inside the toolbar. This search box can double as a command line. If you are using one of the latest versions of VS the search box is still there, but you’ll have to add it to your toolbar yourself. You can do this by clicking on the little triangle at the end of the ‘standard’ toolbar. Then click ‘Add or Remove Buttons’ and select ‘Find’.

Now the search box is back on the toolbar.

Normally when you type in this box and hit enter you’ll search for the text you’ve typed. But… When you hit ‘Ctrl+/’ on your keyboard the search box gets focus and a ‘ > ‘ is placed in there. Now you can enter commands to Visual Studio. For example, ‘>Window.CloseAllDocuments’ to close all open documents. When typing in this box you’ll notice you can a dropdownlist with completions for the command you’re typing. Because all of these commands a bit long to type you can add aliases for them. So in case of ‘Window.CloseAllDocuments’, I’d rather type ‘wca’. To accomplish this hit ‘Ctrl+/’ and type ‘alias wca window.CloseAllDocuments’. From now on you can type ‘wca’ to close all open documents.

Another command I use regularly is ‘tfs’ to access the TFS source control explorer. You can create this alias with ‘alias tfs Team.TfsSourceControl’.

One more thing I want to mention is that you can add ‘External Tools’ to the command aliases as well. One that I use is ‘cmd’ to open a command prompt at the root of my current selected project. I did this by first creating the ‘external tool’. You can open the window below by going to the tools menu and selecting external tools.

The values I entered are:

  • Title: cmd
  • Command: %windir%\system32\cmd.exe
  • Arguments: “C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat”
  • Initial directory: $(ProjectDir)

There are commands for 24 external tools that can be called in the search box. Mine happened to be the 6th. So I created an alias by typing ‘alias cmd Tools.ExternalCommand6´. From this moment on I can hit ‘Ctrl+/’ and type ‘cmd’ to open a command prompt at the root of my current project. Which I find very useful when working with NPM and Bower.

Let me know in the comments below what commands you are using in this command line.

 

 

Slide3

Today I’m adding an AngularJS service to the Windows Store project in Visual Studio. This service is making a call to an external webservice which returns some JSON data. This controller uses a promise to handle the call to the service and when it’s fulfilled the data is shown on the screen.

You can find the code: https://github.com/sorskoot/AngularWinjsDemo

winjs-logo2

WinJS provides you with a way to create namespaces and work with classes in your code. It provides functionality to create derivatives of your classes and combine them using mixins.

Class and Namespace

There are many frameworks that give JavaScript the feeling of working with OO. So does WinJS. WinJS uses the WinJS.Class.define function to define a class. The function takes 3 parameters. The first parameter is a constructor that is called when the object is instantiated. You can provide parameters to the constructor that can be used when instantiating the object. For example, in the code below a ‘name’ can be provided to the constructor of the ‘Human’ class. If your class doesn’t need a constructor, you can provide an empty function or use ‘null’ (which tells WinJS to create an empty function).

Often your class needs to do a little bit more than just being constructed. After providing the WinJS.Class.define function a constructor, you can give it an object containing functions or fields for the class to work with. These will be available when the class is instantiated. In the example below I added a function called ‘sayHello’ which uses the ‘name’ variable created in the constructor and displays it in a message.

Optionally you can add a third parameter to the constructor which will define static fields and functions. These can be called before the class is instantiated.

In a larger application you probably wrap you code in functions to create scope. In these cases you want your classes to be separated into different files, but possibly available to others too. That’s when Namespaces become handy. You might know namespaces from other languages like C#. They are easy to define with WinJS. Just make a call to the WinJS.Namespace.define function giving it the name of your namespace and an object with the classes. If the namespace already exists, the new members are added to it. In the example I added the ‘Human’ class to the ‘Species’ namespace. I also wrapped the code defining the class and the namespace in a function to create a scope around it. You can try for yourself and see what happens if you try to instantiate the ‘Human’ class without the namespace.

Inheritance

One of the powerful features of Object Oriented programming is Inheritance, with which you can reuse classes by deriving functionality from one to the next. WinJS provides functionality to achieve this in JavaScript. To create a derivative of a class you can use the WinJS.Class.derive function. The function is very similar to the define function described earlier. It takes one extra parameter, the class you want to derive from. It also takes a function as a constructor, an object with instance fields and an optional object with static fields and functions. I extended the previous example a bit and added the new derived class, ‘SuperHuman’. I gave the constructor of this class a second parameter and a new function. Then I added it to the ‘Species’ namespace. At the end you can see the instantiation of the object and calling of the two functions. In the Result window you can see the result of these functions.

Mixins

Other than languages like C#, WinJS can add multiple inheritance to your applications. This means you can have your class inherit from more than one class and reuse code in more different ways. Creating a mixin is not complicated. In the example below I added an object ‘Job’ with a field and a function. By calling the WinJS.Class.mix function with both the original class, ‘Human’ and the new ‘Job’ object, you can have WinJS mix the two together. And thus use the ‘job’ field and the ‘work’ function from ‘Human’ class. Which is inherited by the ‘SuperHuman’ class, giving that access to these too. There are many ways in which this can be useful when using this in your projects.

WinJS provides a couple of handy mixins for you to use in your project. The WinJS.Utilities.eventMixin and the WinJS.Utilities.DOMEventMixin add event functionality your class. I’ve demonstrated the WinJS.Utilities.eventMixin mixin in the example below. One of the things this mixin adds to your class is the addEventListener function and the dispatchEvent function. To make an event work you also have to mix in the WinJS.Utilities.createEventProperties mixin. In the example below I used this to create the ‘laugh’ event. At the end of the example I added the eventlistener and called the ‘tickle’ function on ‘Superman’ to have it fire the event.

wrap-up

Please use the jsfiddles to experiment with the different functions and use them to create classes of your own. I hope the use of the fiddles helps explaining these functions of WinJS a bit. Please let me know if they do, or if I never should use these again in case they don’t :)

Subscribe to the RSS feed or follow me on Twitter. I also added links to my FlipBoard magazines to the left sidebar of my blog.

Angular JS

I was trying to use Angular JS in a Windows store app and had some issues with Angular being “unsafe”.

Using Angular JS in a JavaScript Windows Store app turned out to be pretty easy. Here’s how to do it:

First create a new app.

Install Angular JS though NuGet.

Add a scripts tag to your default.html.

<script src="Scripts/angular.js"></script>

Running the app at this point will result in the following error:

The trick to get around this error is to enable CSP (Content Security Policy) and the most convenient part is that Angular has a directive to set that. All you have to do is add the “ng-csp” attribute to your html tag.

Which results in:

<!DOCTYPE html>
<html ng-csp ng-app>
<head>
    <meta charset="utf-8" />
    <title>AngularDemo1</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>

    <script src="Scripts/angular.js"></script>

    <!-- AngularDemo1 references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>
<body>
    {{5+5}}
</body>
</html>

And that’s it. If you run this, your app should print “10”. Getting WinJS to work with Angular is a whole other story… which I’ll explain in a separate post…

Additional note:

In order to get ng-cloak and ng-show to work property you’ll have to add some styles to you project. These style would be added dynamically in other situations, but because ng-csp is used this is disabled. This is the CSS, which can be found at the end of ‘angular.js’ (I removed a few unsupported):

<style type="text/css">
    @charset "UTF-8";

    [ng-cloak], [data-ng-cloak], [x-ng-cloak],
    .ng-cloak, .x-ng-cloak, .ng-hide:not(.ng-animate) {
        display: none !important;
    }

</style>

In one of my apps I wanted to have the items in a list with the list being in a Pivot control. I wanted to have the items slide in with a little delay, like they are in the Windows Phone mail app. I’ve been looking for that a lot, but couldn’t find anything. Until I stumbled upon the Pivot Control Sample app. The actual solution is demonstrated in this sample. It doesn’t seem to be documented anywhere else…

Here’s how it’s done…

All you have to do to get the delay on the items, or basically any HTML inside the pivot items, is just adding one of three CSS classes: win-pivot-slide1, win-pivot-slide2, win-pivot-slide3. Where the first has the shortest delay and the last the longest.

To see the effect you can alter the “Pivot App (Windows Phone)” template app a little. Just create a new app using that template.

Then, open one of the pages. Section3Page.html for example and change the itemTemplate part of that HTML to:

<div class="itemTemplate"
     data-win-control="WinJS.Binding.Template">
    <div class="templatecontainer">
        <img class="win-pivot-slide1"
             src="#"
             data-win-bind="src: backgroundImage; alt: title" />
        <div class="itemcontainer">
            <div class="itemtitle label-extralarge win-pivot-slide2"
                 data-win-bind="textContent: title"></div>
            <div class="label-mediummid win-pivot-slide3"
                 data-win-res="{ textContent: 'Section3Description' }"
                 style="height: 82px;"></div>
        </div>
    </div>
</div>

 

And that’s it J

 

I’m my previous post I showed how you can add a website to a universal project and share some JavaScript between all three. This is nice, but I will run into a situation where you’ll have some code that is not supposed to run on one of the platforms. In the C# world you can use compiler directives in situations like this. In JavaScript this is not possible (Although you could create constructions that mimic directives using Grunt for example). WinJS has some functionality build in that can help finding out what platform you are using.

There are two properties on the utilities in WinJS you’ll need:

Here’s a small example of you could use it:

if (WinJS.Utilities.isPhone) {
    console.log("Phone");
} else {
    if (WinJS.Utilities.hasWinRT) {
        console.log("WinApp");
    } else {
        console.log("Else");
    }       
} 

While exploring the possibilities of using frameworks like KnockoutJS and Backbone in my store apps I started wondering if it would be possible to share my JavaScript code between Windows Store app, Windows Phone app and an ASP.NET website. After some exploration and fiddling with various options I figured it out.

Here’s how to do it.

If you have a solution with an ASP.NET website, add a universal project to the solution. Or add a MVC project to the solution with you universal projects.

Unload the web application and add to the following line to the file right before the import of “Microsoft.CSharp.targets”. Where App79 would be the name of your shared project of course…

 <Import Project="..\App79.Shared\App79.Shared.projitems" Label="Shared" />

This will enable the connection between the projects. Because linking JavaScript files doesn’t work in web projects (the files are not really in the expected folder) the files have to be copied too.

After some searching I came across the following blogpost by Matt Perdeck, Copying linked content files at each build using MSBuild. He explains how to have the build copy linked files to their target location.

By adding the following lines to the end of the project file, right before the last closing tag, files are copied before the build. He even optimized it a bit, by skipping the unchanged files.

<Target Name="CopyLinkedContentFiles" BeforeTargets="Build">
    <Copy SourceFiles="%(Content.Identity)" 
          DestinationFiles="%(Content.Link)" 
          SkipUnchangedFiles='true' 
          OverwriteReadOnlyFiles='true' 
          Condition="'%(Content.Link)' != ''" />
</Target>

Close the project file and reload the project. As you can see in the references section the shared project is included.

You need to make sure that the names of the folders in the shared project are available in the web project too. I assume these are already created in the Windows Phone and Windows Store projects.

One nice extra is that you can add breakpoints in the shared project that will hit when running the web project. You can also switch the context to the web application in the .js files.

 

 

For a while now I wanted to dive a little deeper into Promises, so I decided to write this tutorial.

For this tutorial I used the WinJS version as available on GitHub. If you want to follow along you’ll have to compile the code yourself. Which is very easy, but if you have any issues or questions please let me know and I’ll do a tutorial on that.

What’s a “promise”?

A promise is an object representing a value that is eventually returned by an operation. This object can be passed around like any other object.

Various frameworks have various implementations of promises. Promises are specified in the CommonJS Promises/A proposal. jQuery for examples uses Deferred. WinJS has its own implementation, but they basically work the same. You do something, and specify what happens then and then, until you are done.

The promise object has two functions you’ll use very often.

  • Then() à Allows you to specify what needs to be done when the promise is fulfilled. It also allows you to specify what to do when an error occurs and provide notifications on the progress.
  • Done()à Is almost similar to then, except it returns undefined instead of a promise. It is meant to be used at the end of the promise chain. It takes the same parameters, although unhandled exceptions need to be handled outside the promise chain and won’t be handled inside.

You will use the constructor a lot too. This can wrap some code in a promise and lets you handle the moment it is fulfilled.

Use a promise

One very common use of a promise in WinJS is its xhr() function. This function wraps the XMLHttpRequest in a promise and is used to make ajax calls. When given a URL and a response type the xhr() function returns a promise that is fulfilled when the call is completed, either by returning the data requested or when I fails and returns an error.

Let’s have a look at some code.

// create request object 
var request = 
{
    url:"https://gdata.youtube.com/feeds/api/users/paulsoaresjr/playlists?v=2&alt=json",
    responseType:"json"
};

//call to xhr
WinJS.xhr(request)	
    .then(function(r){
        var response = JSON.parse(r.response);
        console.log(response.feed.entry[0].title.$t);
    });

On lines 2 through 6 I create a request object. In this case I’m going to make a call to the YouTube API to request the playlists for a specific user. I specify I’d like the response to be JSON, both in the URL to YouTube and in the response type.

On line 9 I use the request object as a parameter in the xhr function. This function will make the call and returns a promise.

On line 10 the returned promise used immediately and its then function is called. As a parameter the then function takes up to three parameters, all three functions. The first, which is called when the promise is fulfilled successfully. The second parameter is a function the will be called when an error occurs. This allows you to handle the error and have the chain continue. The third function that can be passed to the promise function is used to handle the progress. Promises are not required to use progress.

Lines 11 and 12 parse the response and log the title of the first playlist to the console.

A more interesting situation

The service called in the previous examples returns the playlists for the specified user. But, say we want to know more about all these playlists. We’ll have to iterate over the lists of the playlists returned and make a new call for each playlists. When this is done we need to handle the results.

Promises are a big help in cases like this. Because promises are just objects we can create arrays of them. And the promise type has a function to join an array of promises to be handled as one.

Let’s change to code to the following:

WinJS.xhr(request)
    .then(function(r){
        var response = JSON.parse(r.response),
            promises = [];
        for (var i = 0; i < response.feed.entry.length; i++) {
             promises.push(WinJS.xhr({
                 url:response.feed.entry[i].link[2].href+"&alt=json",
                 responseType:"json"
            }));
         };
         return WinJS.Promise.join(promises);
     })
     .then(function(x){
         var playlistResult = [];
         for (var i = 0; i < x.length; i++) {
             var response = JSON.parse(x[i].response);
                 playlistResult.push({
                     title: response.entry.title.$t,
                     summary: response.entry.summary.$t,
                     url: response.entry.link[1].href
                 })
             };
             return playlistResult;
         }, function(err){
                console.log(err);
            }
     ).then(function(r){
         //do something with results from r[]
     });

The request object used as parameter in the xhr function on line 1 is the same object used in the previous sample.

Line 5 through 10 loop over the entries returned from YouTube. Per entry a new promise is instantiated (line 6) and added to the promises array.

The real magic happens on line 11. On this line the complete array of promises is joined into one and returned. After this, the next then function is called when all these promises are fulfilled. An array with results, one item per request, is passed to it.

Inside the then on line 13 I loop over this results, parse them and add them as a new object into an array if playlist results. At the end of the function at line 23 I return this array so it can be processed further into another then or done.

I also added a handler for the errors on line 24. This way I know when something went wrong here.

One major downside to this technique is that the whole chain fails whenever one promise returns an error.

Custom promises

Often you have to work with 3rd party libraries that don't use these promises. Wrapping existing code into a new promise.

First, let's look at same code again. This code replaces the last then of the previous sample.

.then(function(playlists){
    return new WinJS.Promise(function(complete, error){
        someRandomLibrary.magic({
            value:playlists,
            callback:function(x){
                complete(x);
            },
            error:function(err){
                error(err);
            }
        });
    })
});

The constructor of the promise on line 2 takes a function with 2 parameters. The promise uses these functions to keep the chain going. Both parameters are functions that you can call from your code. In this example I use call magic function of some random library. This function takes an object which has a callback and an error function. When magic call its callback function, I call the complete function that was given to me by the promise. This will trigger the next step in the chain of promises and call the then or done function if it is specified. The value passed to the complete function will be passed to the then or done functions. In case of an error occurring magic calls what I specified on line 8. I just call the error function that was provided to me, passing it the error. This way it can be handled somewhere else.

Wrap up

I hope I shed some light on these promises. Keep in mind that code like this can be refactored pretty easily into multiple methods, because promises can be passed around in variables and parameters.

A complete version of source is available on GitHub.