• DaveDev

    Accessing the Accelerometer in a Windows 8 Metro Style App using HTML and JavaScript



    I have recently been coding a Windows 8 Metro Style App using the new Windows 8 Release Preview bits and Visual Studio Express 2012 RC.  The app is going to be a retro shooter that takes advantage of HTML5 Canvas for the main game engine and then several Windows 8 Metro Style App Features.  Rather then wait for the game to be completely finished I figured I would start sharing some of my development experiences here on my blog.

    One of the first ideas I had was for a “Gravity Pulse” power that would be granted upon earning a predefined a amount of points (1,500 pts being the default).  Every time the user gains these amount of points a custom sound file will be played and then the screen will display a message to shake the device.  If the user shakes the device within a predefined amount of time all ships on the screen will blow up. 

    Gravity Pulse - Shake the Screen!


    The language I chose to use was HTML and JavaScript but this example could just have easily been done in C++/XAML or C#/XAML.  The code needed to access the accelerometer was very small and I was impressed just how easy it was to add to my game.

    Declaration and Initialization

    I start out by defining three local class variables I will use to access the sensor itself and default values for the polling interval.

       var accelerometer;
       var intervalId = 0;
       var getReadingInterval = 0;

    Once the DOM of the default.js page has been loaded I call a custom function (named initialize).

    //If Document fully loaded than begin processing
       document.addEventListener("DOMContentLoaded", initialize, false);

    Inside of initialize I set up all of my ships, the coordinate system for the gameboard and other important details.  There is a function I have created that will handle the accelerometer instance called initAccel.

    //Set up accelerometer for shake events
    //Init Accelerometer
    function initAccel() {
        accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
        if (accelerometer) {
            // Choose a report interval supported by the sensor
            var minimumReportInterval = accelerometer.minimumReportInterval;
            var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
            accelerometer.reportInterval = reportInterval;
            getReadingInterval = reportInterval * 2; // double the interval for display (to reduce CPU usage)
        } else {
           displayError("No accelerometer found");

    The initAccel function assigns the default accelerometer (through the magic of WinRT) to the class variable accelerometer and if it finds a device it sets up the reporting interval properties.  Reporting interval is how often we will receive new sensor readings from the accelerometer so it is important to pick a value that won’t kill our cpu.


    Handling the Accelerometer Readings

    Always remember accessing the sensor (as in any other devices) will cause cpu load and drain your battery.  I am careful to only turn the sensor on when the user hits the predefined amount of points and then I shut it off until the next gravity pulse becomes available.  Fortunately this is easy to do in JavaScript by controlling the eventListener.  If the accelerometer object has an eventListener assigned to it it will be actively polling for new data. 

    The function I use to check for an in progress Gravity Pulse is called updateScore.  This is where I start listening to accelerometer readings by assigning an eventListener for “shake events” as well as updating the screen and playing a wav file (more on playing sounds and external libraries to come)

    //update player score
        function updateScore(points) {
            score += points;
            scoreGravity += points;
            txtScore.innerHTML = "  Score: " + score;
            if (scoreGravity === GRAVITY_WAVE_PTS_REQ) {
                accelerometer.addEventListener("shaken", onShakenAccel);
                txtScore.innerHTML = " > SHAKE THAT SCREEN <";
                scoreGravity = 0;
                SoundJS.play("pulse", SoundJS.INTERRUPT_ANY);
            //new level
            lvlNextPts = (lvlCurrent + 1) * LEVEL_PTS_REQ;
            if (score >= lvlNextPts) {
                txtLevel.innerHTML = "Level: " + lvlCurrent;
                lvlDifficulty = LEVEL_SPEED_INCREASE * lvlCurrent;

    When a user shakes the Windows 8 tablet enough to register a “shake” event the onShakenAccel eventHandler is called and the following code invoked:


    //Accelerometer has been shaken and now we need to grant the bonus power
     function onShakenAccel(event) {
          //Stop Listening to Accelerometer
         accelerometer.removeEventListener("shaken", onShakenAccel);
         //Gravity Wave Power - Destroy all ships


    You will notice the first thing I do is remove the eventListener which will effectively turn off the Accelerometer Sensor and then I call a custom function to blow up the on screen ships.



    That’s it!  By adding a few eventListeners and a call into the WinRT Windows.Device.Sensors namespace my game has full accelerometer support!  Hopefully this post will help you get started in adding sensor support in your own Metro Style Apps.  As Always - if you are currently working on a Windows 8 app I would love to hear about it!

    You may also want to check out my previous Windows 8 Metro Style Development Tips:

  • DaveDev

    Announcing the MetroGameKit – a free, sample, starter project for Windows 8 Casual Games using HTML5 and JavaScript



    spacecadet   Pew Pew! Fire Lasers!

    During the past couple of months I’ve been hacking around in the world of HTML5 Canvas and casual gaming.  The community that has formed up around HTML5 Gaming in particular is awesome and I am continually impressed by what I’ve seen.

    Not to mention I’m a big retro gaming fan – 8 bits anyone?

    With that in mind I wanted to contribute back to the community if I could.  I figured the best way I could do that was to take the experience I have writing Windows 8 Metro Style Apps and combine them with the world of HTML5 Canvas based gaming.

    Things were super easy to bring over from a code perspective.  All of my layout is done through CSS3 (including media queries for ViewState), the game loop is straight up HTML5 Canvas with requestAnimationFrame, the music uses HTML5 Audio Tags, and the sounds use third party JavaScript libraries like SoundJS.


    Get the Code

    You can grab the sourcecode from Codeplex here:


    Or GitHub here:




    I am replicating all the source back between GitHub into Codeplex so regardless of where you fork you will always have the latest source.

    If you decide to write a Windows 8 app and want to get into the Windows Store I would love to hear about it!  You may also want to check out my previous Windows 8 Metro Style Development Tips:

    Happing Coding!


  • DaveDev

    Build a Hybrid App for Windows Phone 8 using appMobi


    Via Davedev.net


    appmobi_logo_highres HTML5

    If you’re a web developer focused on HTML5 like me then chances are you’ve looked into how to port your web apps to one of the App Marketplaces out there.  I recently sat down with appMobi’s Developer Evangelist, Andrew Smith, to chat about how Web Developers can create Hybrid Apps which run on iOS, Android and Windows.  Due to the popularity of that interview I’ve asked Andrew to guest post here on how you can get started!

    Via Andrew…

    Smartphones running mobile apps are spreading quickly, just like Websites did in the 90’s. However, in order to have your software in the mobile app stores developers need to create native apps written in the programming language of the particular operating system. Rather than writing the same application over and over so your app can run on all smartphones, wouldn’t it be great if your current Web developers could build your application once but allow you to deploy it to a variety of devices? Perhaps appMobi is the answer.

    What is a Hybrid Mobile App?

    The key to creating a mobile app that is written once but runs anywhere is the concept of the hybrid mobile app. These apps are called “hybrid” apps because they are native apps that are coded using the exact same technologies that power the World Wide Web.

    Native applications are written specifically for a particular operating system of the device it is meant to run on. That would be xCode/Objective C for iOS, Eclipse/Java for Android, and Visual C# or Visual Basic for Windows Phone 8. There is no native universal programming language for all device platforms.

    appmobi-xdkOn the other hand, mobile Web apps are server-side apps that run within a smartphone’s Web browser. They use Web technologies such as HTML5, JavaScript, and CSS3. However, these applications are not available from the smartphones’ app stores since they are downloaded from the Web.



    Hybrid apps are a marriage of these two technologies. Like a native app a hybrid app runs natively on the device and are distributed through the smartphones’ distinctive app stores. However, these apps are coded using Web technologies rendered locally on the device so it does not require an Internet connection. Furthermore a Web to native abstraction layer gives the hybrid app access to device capabilities that are not accessible to mobile Web applications such as the accelerometer, contacts database, and camera.

    Web Developers Can Use appMobi to Create Hybrid Apps

    Using appMobi, you can create apps using Web technologies that you are already familiar with. The appMobi XDK tool can be used as a simulator to test how your app will look on a variety of devices and interact with the device’s native features such as the camera and accelerometer using the appMobi JavaScript API.



    Then using the appMobi XDK you can see how your application would look on a variety of devices. Once you like the app on the emulator, load it on an actual smartphone using the appMobi “test anywhere” feature. Use this tool to create a project “bundle”, a folder including all the HTML, JavaScript, CSS, image, video, audio, and other supporting Web technology files that will be built into the native apps.

    Create Your Project Bundle

    Building a hybrid native app is just like building a mobile Web app, except that the code is built into a binary at the end for submission to the appropriate application stores. Using the appMobi appHub build system, your project bundle – all the files used to create the application including HTML, JavaScript, images, videos, CSS – is automatically compiled into a binary for you. No need to buy a Mac and learn XCode to create iOS apps. Don’t bother installing Eclipse and learning Java programming techniques to create an Android app. The appMobi appHub build system does all that for you.



    With the advent of Windows Phone 8, the appMobi appHub will soon include the capability of creating a native application for a Windows smartphone as well. Meanwhile, you can follow these easy steps to create your very own Windows Phone 8 application using the free tools Microsoft has provided.


    Decide what you want your app to do, and build it using the tools you are already familiar with. Consider using the appMobi XDK to test any calls to the appMobi JavaScript Bridge API, or see how your bundle will appear on a variety of devices.



    Build For Windows Phone 8

    Once you have an app project bundle finished, it is time to build it for Windows Phone 8. To build an appMobi application as a hybrid Windows Phone 8 app, you’ll need to install Visual Studio Express 2012 for Windows Phone on a Windows 8 PRO computer. The Windows 8 PRO operating system is key since The Windows Phone 8 emulator relies on Windows 8 Professional, so be sure you have the appropriate operating system before getting started.






    First create a Windows Phone 8 project in Visual Studio. Start Visual Studio for Windows Phone and select New and then Project. On the New Project setup screen, create a Windows Phone App using Visual C#. Supply a name for the project and select OK. This will create your new project.



    Select the Windows Phone 8 operating system. Click OK to continue.



    Once you have a project prepared, you will want to install one of appMobi’s Windows Phone 8 templates from NuGet to transform your empty new project into an appMobi application project. To install one of the appMobi templates visit:


    Consider trying one of the specialized templates another time, but just for the purposes of creating a Windows Phone 8 build you’ll want to stick with a simple template. Select the appMobi Windows Phone 8 Hello World template.

    HTML5 Hello World


    Click on the template and find the install command. Copy the Install-Package command to your clipboard. Do not include the PM> prompt portion.



    Return to Visual Studio and open the Package Manager window by selecting View > Other Windows > Package Manager Console. Paste the Install-Package command on your clipboard into the Package Manager Console and press the Enter key.

    PM Console


    After successfully installing the package, you will note that the Solution Explorer window updates to include an “html” folder and other specific “appMobiPage” files. You will also notice that a readme.txt file is displayed in the VS edit window. This file contains information about the contents of the template, and how to use it. Continue with those instructions, or follow the next few steps here.

    To bind the project to the appMobi template selected, you will need to modify the WMAppManifext.xml file loaded at project creation. This file can be found in the Properties directory. In the editor window for the WMAppManifest.xml file, you will need to update the Navigation Page field value.

    Nav Page


    Change the Navigation Page value to “AppMobiPage.xaml” and then save the file.


    appMobi Page


    Now you’ll want to import the appMobi project bundle into your newly created project. Copy all the files in the bundle with the exception of the files in the “_appMobi” directory. Paste all those files into the “html” directory of your Visual Studio project in the Solution Explorer.

    Once your project bundle is in position, you’ll need to identify which files you want included in the build. Make sure to reference all the files you use for your project bundle in AppMobiWebSource.xml.

    appmobi source


    At this point, you are now ready to start developing and debugging your application in the Windows Phone 8 environment. Use the WP8 emulator within Visual Studio to aid with device debugging.

    For More Information

    So you want to get started? Head to the Chrome Web Store to grab the XDK, and download Microsoft Visual Studio 2012 for Windows Phone 8.  

  • DaveDev

    Connecting to WCF RIA Services in a Windows 8 Metro Style App using Upshot.js and Knockout.js



    After messing around with KnockoutJS inside of Metro Style Apps I decided to dive a little deeper and see what Single Page Applications (particularly Upshot.js) could offer.  I’ve gotten asked by more than a few developers how best to connect to their existing WCF RIA Services inside of Metro Style Apps.  The approach I took here is one possible solution to help get your started.



    For those not familiar with Upshot it is a JavaScript Library that allows you to connect to WCF RIA Services.  It is by the same great wizards who wrote ASP.NET MVC4 Single Page Applications. and included already in Single Page App templates! 

    I also came across two really great posts you should check out that helped me get my head around things:

    Upshot.js & Knockout.js: The HTML5 Client for WCF RIA Services

    Building Single Page Apps with ASP.NET MVC4 - Part 1 - Basic Desktop Application

    If you just want to grab the MVC4 and Windows 8 Metro Style App source code you can download them here:



    Setting up the MVC 4 Environment

    In order to get the MVC4 Single Page Application Templates I downloaded and installed Visual Studio 2011 Beta Ultimate (currently freely available here).  I am running everything local: MVC4 Website is using IIS Express and the data is stored in SQL Server 2008 R2 Express( the one that comes with the Web Platform Installer).  The code that I used was based of a great sample Bart Jolling wrote on his blog here

    The example is a simple Deliverytracker SIngle Page Application that looks like this:


    To  keep things simple I am running everything local with integrated security on IIS Express and SQL Server Express.
    Also take note of our DomainModel as we will need to manually set up MetaData for this later.
    public class Customer
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    public class Delivery
        public int DeliveryId { get; set; }
        public virtual int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }
        public string Description { get; set; }
        public bool IsDelivered { get; set; }


    Setting up the Metro Style App to use Upshot.js

    I then created a new JavaScript based Metro Style App like usual and selected the Tools – > Library Package Manager – > Manage NuGet Packages for Solution menu and searched for UpShot.


    This will bring down all the required scripts you need for using Upshot.js in your application.


    Because the package installer assumes we are inside of an MVC application it will write everything into a new /scripts folder.  For simplicity sake I removed the /scripts folder and copied all of the JavaScript files into our existing /js folder.


    Declaration and Initialization

    We now reference these new JavaScript Libraries like usual inside of our default.html.

    <script type="text/javascript" src="js/jquery-1.6.4.js"></script>
    <script type="text/javascript" src="js/knockout.debug.js"></script>
    <script type="text/javascript" src="js/knockout.js"></script>
    <script type="text/javascript" src="js/DeliveriesViewModel.js"></script>
    <script type="text/javascript" src="js/upshot.js"></script>
    <script type="text/javascript" src="js/upshot.compat.knockout.js"></script>
    <script type="text/javascript" src="js/upshot.knockout.extensions.js"></script>
    <script type="text/javascript" src="js/arrayUtils.js"></script>

    There are two additional scripts here arrayUtils.js and DeliveriesViewModel.js that I copied over from the MVC4 Single Page Application DeliveryTracker example  mentioned previously.  arrayUtils is a helper function we can leave as is and DeliveriesViewModel will be how we wire up to our service. 

    The next step was to take the code from our MVC4 app’s Home View located in /Views/Home/Index.cshtml and move it into our Metro Style App.

        <button data-bind="click: saveAll">Save All</button>
        <button data-bind="click: revertAll">Revert All</button>
            <input data-bind="checked: excludeDelivered" type="checkbox" />
             Exclude delivered items</label>
        <ol data-bind="foreach: deliveries">
            <li data-bind="css: { delivered: IsDelivered, 
                                            updated: IsUpdated}">
                <strong data-bind="text: Description"></strong>
                is for <em data-bind="text: Customer().Name"></em>
                <label><input data-bind="checked: IsDelivered"
        <ul data-bind="foreach: deliveriesForCustomer">
                <div>Name: <strong data-bind="text: key.Name"></strong>
                <ul data-bind="foreach: values">
                    <li data-bind="text: Description, 
                        css: { delivered: IsDelivered,
                                 updated: IsUpdated}">                


    All of this gets done inside our default.html:

    <!DOCTYPE html>
        <meta charset="utf-8">
        <!-- WinJS references -->
        <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
        <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
     2:     <script src="//Microsoft.WinJS.0.6/js/ui.js">
     1: </script>
     3:     <script type="text/javascript" src="js/jquery-1.6.4.js">
     1: </script>
     2:     <script type="text/javascript" src="js/knockout.debug.js">
     1: </script>
     2:     <script type="text/javascript" src="js/knockout.js">
     1: </script>
     2:     <script type="text/javascript" src="js/DeliveriesViewModel.js">
     1: </script>
     2:     <script type="text/javascript" src="js/upshot.js">
     1: </script>
     2:     <script type="text/javascript" src="js/upshot.compat.knockout.js">
     1: </script>
     2:     <script type="text/javascript" src="js/upshot.knockout.extensions.js">
     1: </script>
     2:     <script type="text/javascript" src="js/arrayUtils.js">
     1: </script>
     4:     <!-- UpshotWin8 references -->
     5:     <link href="/css/default.css" rel="stylesheet">
     6:     <script src="/js/default.js">
    <div >
        <button data-bind="click: saveAll">Save All</button>
        <button data-bind="click: revertAll">Revert All</button>
            <input data-bind="checked: excludeDelivered" type="checkbox" />
             Exclude delivered items</label>
        <ol data-bind="foreach: deliveries">
            <li data-bind="css: { delivered: IsDelivered, 
                                            updated: IsUpdated}">
                <strong data-bind="text: Description"></strong>
                is for <em data-bind="text: Customer().Name"></em>
                <label><input data-bind="checked: IsDelivered"
        <ul data-bind="foreach: deliveriesForCustomer">
                <div>Name: <strong data-bind="text: key.Name"></strong>
                <ul data-bind="foreach: values">
                    <li data-bind="text: Description, 
                        css: { delivered: IsDelivered,
                                 updated: IsUpdated}">                


    Once we have our view code wired up we now need to call out to the service and databind everything.  Just like my previous KnockoutJS examples I wire up everything after the DomContentLoaded Event has fired using a custom function called initialize.

    document.addEventListener("DOMContentLoaded", initialize);

    Initialize will then tell our app about the fields returned by our Domain Service.  In order to do this we need to call the upshot.metadata function and map values manually based on their original DomainModel source types.  The basic formatting used here is Classname#Namespace.  Once you get your head around that it’s pretty easy to map everything (although laborious).  I also set the key to be based of DeliveryID.  

    After our mapping are set we’ll tell KnockoutJS to bind everything using the provided DeliveriesViewModel function.

    function initialize() {
            "Delivery:#DeliveryTracker.Models": {
                "key": ["DeliveryId"],
                "fields": {
                    "DeliveryId": { "type": "Int32:#System" },
                    "CustomerId": { "type": "Int32:#System" },
                    "Customer": { "type": "Customer#DeliveryTrack.Models" },
                    "Description": { "type": "String:#System" },
                    "isDelivered": { "type": "Int32:#System" }
        ko.applyBindings( new DeliveriesViewModel( ));


    The last step now is to edit our DeliveriesViewModel.js file with the location of our Domain Service.  This will be different for everyone but on my local machine the service runs at http://localhost:61907//api/DataService.

    function DeliveriesViewModel() {
        // Private
        var dataSourceOptions = {
            providerParameters: {
                url: "http://localhost:61907//api/DataService",
                operationName: "GetDeliveriesForToday"
            entityType: "Delivery:#DeliveryTracker.Models",
            bufferChanges: true,
            mapping: Delivery
        // Public Properties
        this.dataSource = new upshot.RemoteDataSource(dataSourceOptions).refresh();
        this.localDataSource = upshot.LocalDataSource({ source: this.dataSource,
            autoRefresh: true
        this.deliveries = this.localDataSource.getEntities();
        this.deliveriesForCustomer = this.deliveries.groupBy("Customer");
        this.excludeDelivered = ko.observable(false);
        // Operations
        this.saveAll = function () { this.dataSource.commitChanges() }
        this.revertAll = function () { this.dataSource.revertChanges() }
        // Delegates
        this.excludeDelivered.subscribe(function (shouldExcludeDelivered) {
            var filterRule = shouldExcludeDelivered
                ? { property: "IsDelivered", operation: "==", value: false }
                : null;
    function Customer (data) {
        this.CustomerId = ko.observable(data.CustomerId);
        this.Name = ko.observable(data.Name);
        this.Address = ko.observable(data.Address);
        upshot.addEntityProperties(this, "Customer:#DeliveryTracker.Models");
    function Delivery (data) {
        this.DeliveryId = ko.observable(data.DeliveryId);
        this.CustomerId = ko.observable(data.CustomerId);
        this.Customer = ko.observable(data.Customer);
        this.Description = ko.observable(data.Description);
        this.IsDelivered = ko.observable(data.IsDelivered);
        upshot.addEntityProperties(this, "Delivery:#DeliveryTracker.Models");


    Other than the service location I did not need to modify the function in any way from the original MVC4 DeliveryTracker example.

    We now have the Metro Style App binding to the same Domain Service and being fully interactive. 





    Obviously we would need to style the application to make it feel like a native Metro Style App but the hard plumbing work has been done.  We were able to keep a majority of the MVC4 code, from both the views and the model, to get us started with our Windows 8 Metro Style App! 


    If you are currently working on a Windows 8 app I would love to hear about it.  You may also want to check out my previous Windows 8 Metro Style Development Tips:

Page 5 of 68 (272 items) «34567»