Category Archives: Javascript

WinRT Contact Picker

One of the best features of Windows 8 is that it allows you to store all your contacts in one place. This means you can link your e-mail, Linked-in, Facebook, Twitter and Google+ contacts in a single list. If you want to access this programatically, it’s surprisingly simple.

The first thing to do is to create a contact picker

        // Create the picker
        var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
        picker.commitButtonText = "Select" ;

The commitButtonText allows you to say what the dialog’s OK button will say. The next function is called to make the contact selection. In Windows 8 this was pickMultipleContactsAsync (there was also a pickSingleContactAsync), but both are deprecated for 8.1, and you should use the following:

     // Open the picker for the user to select contacts
     picker.pickContactsAsync();

Or

     // Open the picker for the user to select a contact
     picker.pickContactAsync();

This needs to be inside a promise, to ensure that the app doesn’t become unresponsive while you select contacts:

    function pickContacts() {

         // Create the picker
        var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
        picker.commitButtonText = "Select";

        var emailsPromise = new WinJS.Promise( function (complete, error, progress) {

            // Open the picker for the user to select contacts
            picker.pickContactsAsync().then( function (contacts) {
                if (contacts.length > 0) {
                    // Iterate through the contacts collection and do something
                    
                    complete(); // Call complete to exit the promise
                } else {
                    complete(); // Call complete to exit the promise
                }
            });
        });

        return emailsPromise;
    };

This works, with one slight caveat – it gives you every single contact. But say you just want the e-mail address? The following will return only the contacts for which you have an e-mail address:

         picker.desiredFieldsWithContactFieldType.append(Windows.ApplicationModel.Contacts.ContactFieldType.Email);

(Note, this replaces the deprecated desiredFields property in Windows 8.0)

So, the final cut looks like this:

    function pickContacts() {

         // Create the picker
        var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
        picker.commitButtonText = "Select";
        picker.desiredFieldsWithContactFieldType.append(
               Windows.ApplicationModel.Contacts.ContactFieldType.Email);

        var emailsPromise = new WinJS.Promise( function (complete, error, progress) {

            // Open the picker for the user to select contacts
            picker.pickContactsAsync().then( function (contacts) {
                if (contacts.length > 0) {
                    // Iterate through the contacts collection and do something
                    
                    complete(); // Call complete to exit the promise
                } else {
                    complete(); // Call complete to exit the promise
                }
            });
        });

        return emailsPromise;
    };

So, what does this look like in C#? IMHO, it looks a lot neater:

             // Create the picker
            Windows.ApplicationModel.Contacts. ContactPicker picker = new Windows.ApplicationModel.Contacts.ContactPicker ();
            picker.CommitButtonText = "Select";
            picker.DesiredFieldsWithContactFieldType.Add(
               Windows.ApplicationModel.Contacts. ContactFieldType .Email);

            // Open the picker for the user to select contacts
            var contacts = await picker.PickContactsAsync();
            if (contacts.Count() > 0)
            {
                //...
            }

Final Note

It’s also worth noting that when you get the contacts, the e-mail addresses for each are a collection (each contact can have many); so you’ll need to do something like this:

contacts.forEach( function (contact) {
    contact.emails.every( function (email) { output += email.address + "," ; });
});

Or

foreach( var em in c.Emails)
{
    System.Diagnostics. Debug.WriteLine( "{0} email {1}" , c.Name, em.Address);
}

Back To Front (Scrolling a Vertical Game Background Using Windows 8, Javascript & HTML5)

I’m currently trying to write my first game using the Windows 8 platform. I’ve just finished a painful time trying to work out how to vertically scroll a repeating background. In my case, it’s a star-scape, but this should work for anything.

 

The Problem

 

Imagine you have a single image as a background to your game, but you want to make it look like your game is moving forwards (literally). However, also imagine that you’re incredibly bad at drawing, or manipulating images in any way – so you want to just use one image.

 

Caveat

 

This works for a star-scape because stars look pretty much the same unless you pay very close attention – obviously if you have a vertical shoot ’em up then this might not work, depending how innocuous you make the background.

 

The Solution

 

Okay, so my solution here was to simply scroll the background into itself. In order to do this, you have to visualise the background as a large sheet of paper, and the screen canvas as a small magnifying glass (but square). Strictly speaking, you don’t have to actually visualise it at all, because I’ve drawn it below:

 

background_1

Now, we can scroll that image downward, giving the impression that it’s moving (or we are):

background_2

That’s going to look like we’ve moved across the image. However, the eagle eyed amongst you may notice that we’ve now ran out of image! Actually, this is quite straightforward, just do what the BBC do when they run out of programs – repeat:

background_3

In Detail

Okay, so how do we do all that? It’s alarmingly difficult actually. I’ve marked this as a javascript post, but I don’t see why it wouldn’t work for any language – the principle and maths should be the same.

First, create a variable; for example:

var backgroundOffset = 0;

Inside your game loop, this needs to be iterated:

var gameLoop = function () {        
    canvasContext.clearRect(0, 0, canvas.width, canvas.height);

    // Draw Background
    ++backgroundOffset;
}

Then you need to actually draw the background. This does work, but I’m not claiming it’s the most efficient way of doing it:


canvasContext.drawImage(backgroundImage, 0, backgroundOffset);

if (backgroundOffset >= 0 &amp;&amp; backgroundOffset <= canvasHeight) {
    canvasContext.drawImage(backgroundImage, 0, backgroundOffset - backgroundImage.height);
}

// Scrolling off the bottom of the screen
if (backgroundOffset > canvasHeight) {
    backgroundOffset = canvasHeight - backgroundImage.height;
}

Conclusion

If, like me, you’re just dabbling in game development and want something that gives the impression of moving, then this will do it. If you want Call Of Duty then you’re going to need something more complex!

Gesture of Goodwill in HTML5

This is the second time I’ve typed this. For some reason, WordPress musn’t have liked the first attempt, and so trashed it – which is annoying!

I’ve been playing with gestures on HTML5, and encountered a strange problem (this may be peculiar to Windows 8, but I doubt it).  Here’s the scenario:

The Problem

You have an app (remember that we’re talking about Windows 8).  In the app, you have a particular response to a swipe gesture: say you want to record the swipe distance; and to react to a tap / touch gesture.  This works for mouse events, too.

Here’s some code:

<body>
    <canvas id="mainCanvas">

    </canvas>
</body>

Yeah – I know, you’re wondering how I ever managed to get so good at HTML5!

Here’s some more interesting code:


    var canvas;
    var canvasContext;

    var initialiseApp = function () {
        canvas = document.getElementById("mainCanvas");
        canvasContext = canvas.getContext("2d");

        canvas.width = window.outerWidth;
        canvas.height = window.outerHeight;

        // define GestureRecognizer  
        var recognizer = new Windows.UI.Input.GestureRecognizer();
        recognizer.gestureSettings = Windows.UI.Input.GestureSettings.manipulationTranslateX
        recognizer.addEventListener('manipulationcompleted', function (e) {
            var dx = e.cumulative.translation.x

            canvasContext.clearRect(0, 0, 1000, 20);
            canvasContext.fillStyle = "#2F1BE0";
            canvasContext.fillText('manipulationcompleted ' + Date.now(), 10, 10);
            
        });

        // actual element which feeds the GestureRecognizer  
        var processUp = function (evt) {
            try {
                recognizer.processUpEvent(evt.currentPoint);

                canvasContext.clearRect(10, 90, 1000, 50);
                canvasContext.fillStyle = "#2F1BE0";
                canvasContext.fillText('processUp' + Date.now(), 10, 100);

            }
            catch (e) { } 
        }

        canvas.addEventListener('MSPointerDown', function (args) {
            try {
                recognizer.processDownEvent(args.currentPoint);

                canvasContext.clearRect(10, 190, 1000, 20);
                canvasContext.fillStyle = "#2F1BE0";
                canvasContext.fillText('processDown' + Date.now(), 10, 200);
            }
            catch (e) { } 
        }, false);

        canvas.addEventListener('MSPointerMove', function (args) {
            try {
                recognizer.processMoveEvents(args.intermediatePoints);

                canvasContext.clearRect(10, 250, 1000, 200);
                canvasContext.fillStyle = "#2F1BE0";
                canvasContext.fillText('processMove' + Date.now(), 10, 300);
            }
            catch (e) { } 
        }, false);
        canvas.addEventListener('MSPointerUp', processUp, false);
        canvas.addEventListener('MSPointerCancel', processUp, false);

    }

If you try that, you’ll notice something… or at least you will now I’ve told you to. That is that if you click / touch then you get a mouse up, but if you swipe then you get a mouse up and a manipulationcomplete! Good God – BOTH! But what if you only want to react to one? Say you have a fishing game, and the swipe casts the … err fishing string thingy, and the touch reels the … err… okay, maybe I should have picked an example I know something about, but you get the idea.

The Solution

I don’t like it, but here’s my answer to that particular conundrum:

    var canvas;
    var canvasContext;
    var eventFlag = 0;

    var initialiseApp = function () {
        canvas = document.getElementById("mainCanvas");
        canvasContext = canvas.getContext("2d");

        canvas.width = window.outerWidth;
        canvas.height = window.outerHeight;

        // define GestureRecognizer  
        var recognizer = new Windows.UI.Input.GestureRecognizer();
        recognizer.gestureSettings = Windows.UI.Input.GestureSettings.manipulationTranslateX
        recognizer.addEventListener('manipulationcompleted', function (e) {
            var dx = e.cumulative.translation.x

            canvasContext.clearRect(0, 0, 1000, 20);
            canvasContext.fillStyle = "#2F1BE0";
            canvasContext.fillText('manipulationcompleted ' + Date.now(), 10, 10);
            eventFlag = 1;
            
        });

        // actual element which feeds the GestureRecognizer  
        var processUp = function (evt) {
            try {
                recognizer.processUpEvent(evt.currentPoint);

                if (eventFlag == 0) {
                    canvasContext.clearRect(10, 90, 1000, 50);
                    canvasContext.fillStyle = "#2F1BE0";
                    canvasContext.fillText('processUp' + Date.now(), 10, 100);

                } else {
                    eventFlag = 0;
                }

            }
            catch (e) { } // translateYfails ?!  
        }

So we have a flag, and only do something based on the flag.

Conclusion

If there’s a better way of doing this then I’d like to hear. It would be particularly nice if you could get the return value of processUpEvent, or set some kind of handled flag. Having said that, this does work.

This and that – Javascript identity crisis

If you usually program in a language such as C#, you’ll be used to the this keyword.  If you aren’t then in C#, this means this; that is, it means the current object that you’re calling this from.  For example, you might have a class called house, which has properties called DoorOpen and WindowOpen, and a method called ShutTheDoor:

    class House
    {
        public bool DoorOpen {get; set;}
        public bool WindowOpen { get; set; }

        public void ShutTheDoor()
        {
            this.DoorOpen = false;
        }
    }

And the calling code:


    class Program
    {
        static void Main(string[] args)
        {
            House house = new House();

            house.DoorOpen = true;
            house.ShutTheDoor();
            Console.WriteLine(house.DoorOpen);


        }
    }

That makes sense to me. The object House contains the method ShutTheDoor AND the property DoorOpen, so I can call one from the other. As a matter of fact, this is even optional. Any property or method inside House will recognise DoorOpen. I can call this from anywhere, and it will have the same behaviour; for example:

    public void ShutHouseDoor(House house)
    {
        house.ShutTheDoor();
    }

In Main:


    house.DoorOpen = true;
    HouseMinder minder = new HouseMinder();
    minder.ShutHouseDoor(house);
    Console.WriteLine(house.DoorOpen);

How does Javascript deal with this then? Well, pretty much the same way for the most part (the code samples here are using WinJS):


    house: WinJS.Class.define(
        function() {},
        {
            doorOpen: true,
            windowOpen: true,
            shutTheDoor: function shutTheDoor() {                
                this.doorOpen = false;                
            }
        }
    )

The Problem

So that’s cool – it works in the same way. Well, not quite; say I want a program that shuts the house door when I click the canvas:

            var body = document.getElementById("body");
            var canvas = document.createElement("canvas");
            canvas.id = "houseCanvas";

            body.appendChild(canvas);

            var canvasContext = canvas.getContext("2d");

            canvas.width = window.outerWidth;
            canvas.height = window.outerHeight;

            canvasContext.fillStyle = "#f00";            

            canvas.addEventListener("MSPointerUp", house.shutTheDoor, false);

That’ll work, right – because shutTheDoor calls this.doorOpen. Well, and for me this is the most annoying thing about javascript, it will certainly compile. However, when it calls shutTheDoor, it calls in on the canvas, not on the house class. Let me say that again: NOT ON THE HOUSE CLASS.

So it’ll fall over?

No.

What it actually does it helpfully realise that you’ll called a property (this.doorOpen) which doesn’t exist, so it simply creates it for you and sets it to false… on the canvas object.

The Solution

canvas.addEventListener("MSPointerUp", house.shutTheDoor.bind(house), false);

The .bind tells javascript to use the object that you’re passing as the context.

Conclusion

Javascript’s dynamic creation of properties can be useful, but I can’t help thinking that problems like this are why statically typed languages are always going to be easier to work with. You get your first unit test for free: it compiles. In Javascript, not only will an incorrectly named property compile, it will exist – even if it doesn’t.