• DaveDev

    Everything you need to know about Windows Phone “Mango” Tools, Training Kit and Developer Phone Images

    • 1 Comments

    What a great time it is to be a Windows Phone developer!  Thanks to your efforts we just hit 25,000+ apps in the marketplace!  The next few months are going to be extremely exciting as we roll out the Mango update to existing Windows Phone customers everyone.  Now is the time for you to get up to speed and start playing around with an early build of Mango on your own phone.  The Windows Phone Team just announced some great stuff for all registered developers

    Windows Phone SDK Beta 2 Tools

    The first thing you will want to do is grab the new Windows Phone Beta 2 SDK for “Mango.”  This free download will install the latest SDK, Windows Phone Emulator, Visual Studio 2010 for Windows Phone and Expression  Blend 4 for Windows Phone.  If you already have a full installation of Visual Studio 2010 or Expression Blend 4 the tools will integrate with those products and just install the templates.

    Beta2

    There are a few things I want to point out about these tools:

    Multi-Targeting

    You will now be given the option to multi-target Windows Phone versions. Note that 7.0 is the current NoDo retail version and 7.1 is the Mango release.  If you want to continue targeting the current SDK for existing phones you will need to change the version to 7.0 as 7.1 is the default. 

    MangoVersionProject

    Applications that are built against the 7.1 SDK will require a phone with the Mango OS (the beta image version you receive as a developer is 7661) installed.  It is important to note however that existing 7.0 targeted applications should run just fine on devices with Mango OS installed.

    One of the questions I often get asked is how this will affect users of Windows Phone later this year when Mango is rolled out to everyone?  Microsoft plans to be very aggressive with this release and users will be notified of the upgrade both on the phone and when they connect to Zune.  What version of your application the user sees in the marketplace will be based on the version of their OS.  If they chose to not upgrade to Mango they will not see any Mango enabled apps in the marketplace.  This means you will need to have a version compiled against the 7.0 SDK for existing users (the same app you have today in marketplace) and an upgraded version compiled against the 7.1 SDK for users that have upgraded to Mango.  Users who have  upgraded to Mango will see all of the new Mango enabled apps as well as the 7.0 apps but they will only ever see one version of your app.

    Upgrade Wizard

    If you right click on a 7.0 compiled project in Visual Studio 2010 you will be given a new option to go through the migration wizard.

    Upgrade

    This will open a Wizard that will upgrade your project settings to the new Mango Release as well as point out any updates you may need to add to your code.  You won’t see this upgrade wizard in Expression Blend so be sure to open the project in Visual Studio if you want to check it out.

    Windows Phone Emulator

    One of the first things you will notice about the new Windows Phone Emulator is the Additional Tools that come bundled.  Both the Accelerometer and Location tools we showcased during MIX10 will be available to you.

    Emulator

    It is important to not however that the Phone OS image in the emulator is actually based off Mango.  You can see this by the new search icon that is visible in the application list.  This is important to keep in mind as you are testing your apps.  Even if you are targeting the 7.0 SDK in your application will in essence be a 7.0 application running on a Mango device.  If you want to run against the 7.0 OS Image you will need to keep a machine with the older SDK installed or a device that has not been flashed to Mango.

    Mango OS Image for Retail Phones

    Now for the most exciting part – how about playing with Mango right now on your existing Windows Phone!  The team is happy announced that all registered AppHub users will be receiving invites to an early beta build of the Mango OS.  Invites will be sent out via MS Connect to the e-mail address you used to register your account on AppHub.  These invites will be sent out in batches so if you haven’t received your invite yet please be patient.

     

    Windows-Phone-Mango-Overview


    Once you received the invite you will login to the MS Connect website with the same AppHub account Windows Live ID and then need to accept the license agreement.  I have gotten some questions around the confidentiality agreement guidelines specifically around what developers are and are not allowed to share.  Thankfully the team has posted more details here that should clarify any confusion.

    Q: What are the confidentiality requirements of my participation in this pre-release program?
    By participating in this pre-release program, you are agreeing to not share the ‘Mango’ pre-release device image, binary dumps, or the applications used to update to this pre-release image, with third parties.

    Basically you can talk about it!  You just can’t download the Phone Image and start hosting and distributing it out to non registered developers or third parties.  Pretty common sense stuff. 

    It is all super important to read the instructions fully.  Microsoft will be supporting bricked phones through this process but only one phone per developer account.  Please take every precaution when flashing your device to the Mango build!  I want to bring particular focus to the step around backing up your retail Nodo Windows Phone Image.  This image will be placed in a folder inside your windows user account directory AppData folder and assigned a guid.  Depending on the size of your phone image (mine was 12 gigabytes) this directory may be quite large.  You should immediately back up this directory to some type of external data source so that you will not lose it.  In order to flash your phone to the retail Mango image later this year you will need to restore back to your retail Nodo image.  Don’t lose the backup!

     

    Windows Phone “Mango” Training

    Ok you got the new Windows Phone SDK Beta 2 Tools and the Mango image loaded on your phone.  How do you start playing with what’s new outside of the existing sessions we did at MIX10?  If you are a fan of self paced hand on labs you will want to head over to MSDN and grab the updated Mango Training Course.

    MangoTrainingKit

    This course will walk you through many of the new features such as SQL CE, Background Agents and Fast App Switching.  The kit is designed to work completely offline and will install everything local for you.

    AppHub has also been updated with many new Mango enabled tutorials for both XNA and Silverlight Applications.  You can get to the updated content by hovering over the education column in the header and selecting education catalog.

    AppHubCatalog

    The MSDN Code Samples website has also been updated with lots of Mango goodness.  Be sure to check it out!

    MSDNMangoSamples

     

    Microsoft Advertising SDK Update

    In the midst of all the Mango announcements last week we also released an update to the Microsoft Advertising SDK.

    AdvertisingSDK

    If you are using Ads in your Windows Phone application you will definitely want to check out this release.  There are many updates included such as additional end user privacy and auto-hide of the control when no Ads are available to be shown.

    Windows Phone Sketchflow Templates

    If you happen to be one of those lucky folks running Expression Blend 4 Ultimate with Sketchflow then I’ve got some additional goodies for you! 

    WP7Sketchflow

    The Expression Team released updated Sketchflow templates that will now allow you to sketch out Windows Phone applications.  You can head on over to Codeplex to download the free templates.  Keep in mind you will need a licensed version of Expression Blend 4 Ultimate with Sketchflow these will not run with the free Blend for Windows Phone edition.

     

    Students get first access to Mango hardware

    Finally, if you are a student looking to get your hands on some of the first Mango enabled hardware then we have exciting news. As the team points out we have 50 devices reserved just for you!

    Here is what to do:

    1. Make sure you’re registered for DreamSpark
    2. Download and install Expression Studio Ultimate and the new Mango Windows Phone Developer Tools (available free as a member of DreamSpark)
    3. Get the free Sketchflow Template for Windows Phone and create a Sketchflow mock-up of your app
    4. Post the Sketchflow mock-up somewhere online and tweet out the link using the hash tag #WPAppItUp
    5. We will review all prototypes and will contact the developers who submit the best ones and send them a special Mango developer device

     

    Summer of Must Have XBox Games on Windows Phone

    The Xbox Team has been busy as well these past few weeks with their Six Weeks of Smash Hit Games.


    With over 70+ quality Xbox Live titles on Windows Phone this summer suddenly became a lot less boring!  I personally plan to break 5,000+ points on my gamerscore courtesy of both Angry Birds and PvZ.


    Xbox-WP7Games

    Happy Coding this Summer I am looking forward to seeing another 25,000+ apps!  – Dave

  • DaveDev

    Over 20+ hours of free WPF training videos!

    • 1 Comments

    With all of the Silverlight Training resources I posted recently it is now time for some WPF love.  =)

    WPFBootcamp

    Be sure to check out the WPF Bootcamp at Mix University

    With over 20 hours of hands on labs, customer examples, and a plethora of topics it will take you through WPF inside and out from start to finish.  Here is just a sample:

    Keynote: Windows Presentation Foundation
    Ian Ellison-Taylor

    A Lap Around Windows Presentation Foundation
    Rob Relyea

    A Lap Around Microsoft Expression Blend
    Pete Faraday

    Building WPF Applications Part I
    Ian Griffiths

    Building WPF Applications Part II
    Ian Griffiths

    LAB: Building WPF Applications

    LAB: Building WPF XAML Browser Applications

    LAB: Interactive Fabrikam Catalog in Blend

    Controls, Styles and Templates
    Kevin Moore

    LAB: Creating a Button with Expression Blend and Design

    LAB: Creating a Glass Button in Blend

    Data Binding with WPF
    Beatriz de Oliveira Costa

    WPF Partner Showcase
    Tim Sneath

    Documents, Text and the Reading Experience
    Kevin Gjerstad

    LAB: Using Data Binding in WPF

    LAB: Reading Experience

    Windows Forms Interoperability
    Scott Morrison

    Visual Studio Orcas Enhancements for WPF
    Mark Wilson-Thomas, Mark Boulter

    Grab all the content here today!

    WindowsClient

    Also don't forgot about WindowsClient.NET.  There is entire learning section around WPF filled with short 15-20 minute digestible videos around various WPF topics.

    Check it out here! 

  • DaveDev

    Using KnockoutJS in Windows 8 Metro Style Apps

    • 3 Comments

    What is it?

    If you have been messing around with JavaScript lately and come from a .Net Background you might have already heard of KnockoutJS.

    Knockout

    If you haven’t, KnockoutJS is a lightweight, free, JavaScript Library from Steve Sanderson that brings the MVVM pattern to the web world.  It’s also filled with #awesome sauce.

     

    Cats and Dogs Living Together – Mass Hysteria!

    It wasn’t too long ago that Windows app development and Web app development were two entirely different views of the world.  Thanks to the magic of WinRT language projection with Metro Style App development we no longer have to give up all the great libraries we are used from the web when  moving onto the desktop.  Most JavaScript libraries will run by just including it in your Metro Style App project.  Well at least local copies of those JavaScript Libraries.  If you want to call out to external libraries however you will need to start looking into the security model of how Windows Web Apps run (WWA). 

    The exception to this is jQuery if you are pulling from the public CDN’s it has already been whitelisted for you.  I wont dive into details here but you can check out the great Build Session from Chris Tavares to learn about the security model for third party JavaScript libraries.

     

    Ok Dave where's the code?

    Hang tight!  If you just want the Windows 8 Metro Style App soure code grab it now.

    Source Code

     

    Setting up KnockoutJS

    The first thing you will need to do is grab the latest version of KnockoutJS off GitHub.  I’ve included and tested with both the stable 2.0.0 release as well the 2.1.0rc update.

    Create a new project in Visual Studio 11 Express as usual and then add the Knockout.js file to your JS folder.

    KnockoutJS.js

    As with all JavaScript files if you want Visual Studio to give you Intellisense you will need to add the following to the current JavaScript source file you are working on:

    /// <reference path="knockout-2.0.0.js" />

    Note that Visual Studio will do this automatically for you if you simply drag the .js file over to your code window.

    Next, you will need to add a reference to the KnockoutJS file in the html source. While we are at it let’s go ahead and grab the latest jQuery Library as well.  Some of the KnockouJS Learning samples assume jQuery is included.  Your references should look like below:

    <script src="/js/knockout-2.0.0.js"></script>
    <script src="/js/jquery-1.7.2.min.js"></script>


    Now we should have working jQuery and Knockout JavaScript functionality but don’t forget that both of these libraries assume you have a DOM.  On the web we would normally start executing code after the onLoad event.  Fortunately for us this is super easy to do in Metro Style Apps by adding an event handler for DOMContentLoaded.  This should be the last line in your main function like so:

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

    This will ensure your DOM is loaded and now accessible inside of your app.

    The last step now is to ensure that all of our KnockoutJS bindings occur once our initialize function has been called.  Here is an example of what I mean:

    //Main Execution
    function initialize() {
     
        // Activates knockout.js
        ko.applyBindings(new AppViewModel());
     
    }

     

    Converting Learn.KnockoutJS samples to a Metro Style Apps

    There are some really great tutorials on Learn.KnockoutJS.com to help get you started.  I decided to go through each of those and bring them over into a Metro Style App.

    Learn KnockoutJS

    All five tutorials came over with minor tweaks except for Single Page applications.   I’ve named the tutorials using the following convention:

    • Introduction – default.html/default.js
    • Working with Lists and Collections – seats.html/seats.js
    • Single page applications – spa.html/spa.js
      • Didn’t work.  I’ve included the source so if anyone wants to hack on it some more and see what’s up please let me know. 
    • Creating custom bindings – custom.html/custom.js
    • Loading and saving data – data.html/data.js

    To change which sample you want to run just edit the startup page inside the project properties.

    Capture

     

    Introduction Example

    No tweaks needed this came over perfectly.  Here is what my html looks like:

    <body>
     
    <p>First name: <strong data-bind="text: firstName"></strong></p>
    <p>Last name: <strong data-bind="text: lastName"></strong></p>
     
    </body>

     

    Here is the JavaScript:

    (function () {
        "use strict";
     
        var app = WinJS.Application;
     
        app.onactivated = function (eventObject) {
            if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize 
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension. 
                    // Restore application state here.
                }
                WinJS.UI.processAll();
            }
        };
     
        function AppViewModel() {
            this.firstName = "David";
            this.lastName = "Isbitski";
        }
     
        
     
        //Main Execution
        function initialize() {
     
            // Activates knockout.js
            ko.applyBindings(new AppViewModel());
     
        }
     
     
        app.oncheckpoint = function (eventObject) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the 
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // eventObject.setPromise(). 
        };
     
        app.start();
     
        //If Document fully loaded than begin processing
        document.addEventListener("DOMContentLoaded", initialize, false);
     
    })();

     

    Working with Lists and Collections Example

    Worked right out of the box.  Here is the HTML:

    <body>
     
    <h2>Your seat reservations</h2>
     
    <table>
        <thead><tr>
            <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
        </tr></thead>
        <tbody data-bind="foreach: seats">
            <tr>
                <td data-bind="text: name"></td>
                <td data-bind="text: meal().mealName"></td>
                <td data-bind="text: meal().price"></td>
            </tr>    
        </tbody>
    </table>
    </body>

     

    Here is the JavaScript:

     
    (function () {
        "use strict";
     
        var app = WinJS.Application;
     
        app.onactivated = function (eventObject) {
            if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize 
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension. 
                    // Restore application state here.
                }
                WinJS.UI.processAll();
            }
        };
     
        // Class to represent a row in the seat reservations grid
        function SeatReservation(name, initialMeal) {
            var self = this;
            self.name = name;
            self.meal = ko.observable(initialMeal);
        }
     
        // Overall viewmodel for this screen, along with initial state
        function ReservationsViewModel() {
            var self = this;
     
            // Non-editable catalog data - would come from the server
            self.availableMeals = [
            { mealName: "Standard (sandwich)", price: 0 },
            { mealName: "Premium (lobster)", price: 34.95 },
            { mealName: "Ultimate (whole zebra)", price: 290 }
            ];
     
            // Editable data
            self.seats = ko.observableArray([
            new SeatReservation("Steve", self.availableMeals[0]),
            new SeatReservation("Bert", self.availableMeals[0])
            ]);
        }
     
       
     
        //Main Execution
        function initialize() {
     
            // Activates knockout.js
             ko.applyBindings(new ReservationsViewModel());
     
        }
     
     
        app.oncheckpoint = function (eventObject) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the 
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // eventObject.setPromise(). 
        };
     
        app.start();
     
        //If Document fully loaded than begin processing
        document.addEventListener("DOMContentLoaded", initialize, false);
     
    })();

     

    Creating Custom Bindings Example

    I needed to do two things to get this example to work.  The first one was to include jQuery it assumes it would be present.  The second was to replace the alert() function call (this doesn’t exist in WinRT) with a native WinRT MessageDialog.  Here is what the HTML looks like:

    <body>
     
    <h3 data-bind="text: question"></h3>
    <p>Please distribute <b data-bind="text: pointsBudget"></b> points between the following options.</p>
     
    <table>
        <thead><tr><th>Option</th><th>Importance</th></tr></thead>
        <tbody data-bind="foreach: answers">
            <tr>
                <td data-bind="text: answerText"></td>
                <td><select data-bind="options: [1,2,3,4,5], value: points"></select></td>
            </tr>    
        </tbody>
    </table>
     
    <h3 data-bind="fadeVisible: pointsUsed() > pointsBudget">You've used too many points! Please remove some.</h3>
    <p>You've got <b data-bind="text: pointsBudget - pointsUsed()"></b> points left to use.</p>
    <button data-bind="enable: pointsUsed() <= pointsBudget, click: save">Finished</button>
    </body>

     

    Here is the JavaScript:

     
    (function () {
        "use strict";
     
        var app = WinJS.Application;
     
        app.onactivated = function (eventObject) {
            if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize 
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension. 
                    // Restore application state here.
                }
                WinJS.UI.processAll();
            }
        };
     
        
     
        // ----------------------------------------------------------------------------
        // Page viewmodel
     
        function Answer(text) { this.answerText = text; this.points = ko.observable(1); }
     
        function SurveyViewModel(question, pointsBudget, answers) {
            this.question = question;
            this.pointsBudget = pointsBudget;
            this.answers = $.map(answers, function (text) { return new Answer(text) });
     
            //Dave Isbitski - 4/24/12 - Changed alert to native WinRT dialog
            this.save = function () {
                var dlg = new Windows.UI.Popups.MessageDialog("To do");
                 dlg.showAsync().done();
     
            };
     
            this.pointsUsed = ko.computed(function () {
                var total = 0;
                for (var i = 0; i < this.answers.length; i++)
                    total += this.answers[i].points();
                return total;
            }, this);
        }
     
        //Main Execution
        function initialize() {
     
            ko.bindingHandlers.fadeVisible = {
                init: function (element, valueAccessor) {
                    // Start visible/invisible according to initial value
                    var shouldDisplay = valueAccessor();
                    $(element).toggle(shouldDisplay);
                },
                update: function (element, valueAccessor) {
                    // On update, fade in/out
                    var shouldDisplay = valueAccessor();
                    shouldDisplay ? $(element).fadeIn() : $(element).fadeOut();
                }
            };
     
            // Activates knockout.js
            ko.applyBindings(new SurveyViewModel("Which factors affect your technology choices?", 10, [
       "Functionality, compatibility, pricing - all that boring stuff",
       "How often it is mentioned on Hacker News",
       "Number of gradients/dropshadows on project homepage",
       "Totally believable testimonials on project homepage"
            ]));
     
        }
     
     
        app.oncheckpoint = function (eventObject) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the 
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // eventObject.setPromise(). 
        };
     
        app.start();
     
        //If Document fully loaded than begin processing
        document.addEventListener("DOMContentLoaded", initialize, false);
     
    })();

     

    Loading and Saving Data Example

    Only thing I had to add here was jQuery due to the dependency on it. Here is the HTML:

    <body>
     
    <h3>Tasks</h3>
     
    <form data-bind="submit: addTask">
        Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
        <button type="submit">Add</button>
    </form>
     
    <ul data-bind="foreach: tasks, visible: tasks().length > 0">
        <li>
            <input type="checkbox" data-bind="checked: isDone" />
            <input data-bind="value: title, disable: isDone" />
            <a href="#" data-bind="click: $parent.removeTask">Delete</a>
        </li> 
    </ul>
     
    You have <b data-bind="text: incompleteTasks().length">&nbsp;</b> incomplete task(s)
    <span data-bind="visible: incompleteTasks().length == 0"> - it's beer time!</span>
     
    </body>

     

    Here is the JavaScript:

     
    (function () {
        "use strict";
     
        var app = WinJS.Application;
     
        app.onactivated = function (eventObject) {
            if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize 
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension. 
                    // Restore application state here.
                }
                WinJS.UI.processAll();
            }
        };
     
        
        function Task(data) {
            this.title = ko.observable(data.title);
            this.isDone = ko.observable(data.isDone);
        }
     
        function TaskListViewModel() {
            // Data
            var self = this;
            self.tasks = ko.observableArray([]);
            self.newTaskText = ko.observable();
            self.incompleteTasks = ko.computed(function () {
                return ko.utils.arrayFilter(self.tasks(), function (task) { return !task.isDone() });
            });
     
            // Operations
            self.addTask = function () {
                self.tasks.push(new Task({ title: this.newTaskText() }));
                self.newTaskText("");
            };
            self.removeTask = function (task) { self.tasks.remove(task) };
     
            // Load initial state from server, convert it to Task instances, then populate self.tasks
            $.getJSON("/tasks", function (allData) {
                var mappedTasks = $.map(allData, function (item) { return new Task(item) });
                self.tasks(mappedTasks);
            });
        }
     
        //Main Execution
        function initialize() {
     
            // Activates knockout.js
            ko.applyBindings(new TaskListViewModel());
     
        }
     
     
        app.oncheckpoint = function (eventObject) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the 
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // eventObject.setPromise(). 
        };
     
        app.start();
     
        //If Document fully loaded than begin processing
        document.addEventListener("DOMContentLoaded", initialize, false);
     
    })();

     

    Conclusion

    I hope this post has given you an idea of how easy it is to include existing JavaScript Libraries from the Web inside 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

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

    • 2 Comments

    Overview

    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.

    One of the things I wanted to do in the game was to keep Player Profiles.  These profiles track player high scores, player names and a player avatar.  Eventually these high scores could be used in a leaderboard running in the cloud. 

    Player Name and Avatar

     

    I thought it would be neat to let players take a picture of themselves for their Avatar by accessing the webcam.  Fortunately for us WinRT makes this super easy to use.  We can even pull up prebuilt camera capture UI by using the built-in Windows.Media.Capture API’s.  If you are an existing Windows Phone Developer this may remind you a lot of Windows Phone Development Tasks – something I absolutely loved. 

    Features like camera timer, settings, and  even picture cropping are all done for us via the Windows.Media.Capture.CameraCaptureUI.  For those looking for more control you also have the ability to call into Windows.Media.Capture.MediaCapture.  You won’t get a default UI with MediaCapture but you do get full control of the streams.  MediaCapture is also a way to record Audio streams in your app.

    Here is what the default Capture Capture UI looks like when using the cropping tool:

    Camera Capture Cropping Tool

    After cropping the photo to my liking and tapping the OK button my new Avatar is automatically set.  The new Avatar Image is automatically scaled correctly thanks to the predefined CSS styling we have created.

    New Avatar Picture

     

    Sweet!

     

    Declaration and Initialization

    One of the joys of doing Windows 8 Metro Style development with HTML and JavaScript is that it feels like Web Programming.  In fact my entire game header is done using normal <div> tags and CSS Styles.  Inside of my default.html file I defined the following header to display the player score, level, name and avatar picture:

    <div id="divGame">
            <div id="txtScore">Score: 0</div>    
            <div id="txtLevel">Level: 0</div>
            <div id="divPlayer">
                 <div id="txtPlayerName">Player1</div>
                 <img id="imgPlayer" src="/images/helmet.png" />
             </div>
    <div>  

     

    I then defined a CSS Style for the Avatar Picture using it’s imgPlayer id.

    #imgPlayer {
        max-width: 100px; 
        max-height: 50px;
        float:left;
        margin-right:10px;
     
    }

     

    The Windows Library for JavaScript (WinJS) gives us a way to create a Windows 8 AppBar easily by just a few lines of HTML (more on WinJS Controls later).  By opening the AppBar and tapping the cmdCamera button our players will get the option to take a new Avatar picture.

    <div id="AppBar" data-win-control="WinJS.UI.AppBar" data-win-options="">
           <button id="cmdHome" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{id:'cmdHome',label:'Menu',icon:'home',section:'selection',tooltip:'Menu'}">
           </button>
          <button id="cmdCamera" data-win-control ="WinJS.UI.AppBarCommand" data-win-options="{id:'cmdCamera',label:'Cadet Photo',icon:'camera',section:'global',tooltip:'Change Cadet Photo'}">
           </button>
         <button id="cmdName" data-win-control ="WinJS.UI.AppBarCommand" data-win-options="{id:'cmdName',label:'Cadet Name',icon:'url(images/accept.png)',section:'global',tooltip:'Change Cadet Name',type:'flyout',flyout:'nameFlyout'}">
           </button>
    </div>

     

    All of the AppBar buttons tap events are handled using standard JavaScript EventListeners:

    //AppBar Commands
            document.getElementById("cmdCamera").addEventListener("click", capturePhoto, false);
            document.getElementById("cmdName").addEventListener("click", showCadetNameUpdate, false);
            document.getElementById("cmdHome").addEventListener("click", showMenu, false);
            document.getElementById("submitButton").addEventListener("click", updateCadetName, false);

    That’s it! We now have a working Game Header and AppBar for our game.  When a player clicks on the Camera Button we will invoke a call to the capturePhoto function.

     

    Opening the Camera Capture UI

    capturePhoto is where the magic happens.  The first thing we do is make a call to WinRT using the Windows.Media.Capture namespace.  This gives us a reference to CameraCaptureUI where we can set default properties.  For my game I am telling the camera to use a 16x9 aspect ratio and lock to the photo mode.  If I wanted the user to capture video I could easily do this as well by using Windows.Media.Capture.CameraCaptureUIMode.video.

    //WinRT Camera API
        function capturePhoto() {
            try {
                var dialog = new Windows.Media.Capture.CameraCaptureUI();
                var aspectRatio = { width: 16, height: 9 };
                dialog.photoSettings.croppedAspectRatio = aspectRatio;
                dialog.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (file) {
                    if (file) {
                        imgPlayer.src = URL.createObjectURL(file);
     
                    } else {
                        //No Photo captured
                    }
                }, function (err) {
                    displayError(err);
                });
            } catch (err) {
                displayError(err);
            }
        }

    This is where you will start to see all of the Async goodness inside of WinRT.  The Camera Capture UI  will run asynchronously while it awaits the user to take a picture.  I handle the callback by invoking a JavaScript Promise using the then keyword.  The promise will call a function when the user takes a photo and if there is an object it will set the source of my imgPlayer tag to be that file.  Those of you familiar with Web programming will recognize the URL.createObjectURL call so that my <img> tag knows where to reference the new source file.

     

    Conclusion

    Hopefully you have seen how easy it is to access the WebCam on Windows 8 now thanks to WinRT and the Windows.Media.Capture API’s.  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:

Page 2 of 68 (272 items) 12345»