WinRT API learning – 70-481 Lazy dog

Last updated: 2013-04-26

Links to some other of my posts on WinRT

This post should make it easier to navigate and remember the WinRT and WinJS API.
“‘Cause I still – haven’t paaaassed – 481” – U2?

The 70-481 test contains 45 questions. You have 3:15 to complete. The questions are divided into

  • 29 questions – use max 125 mins
  • 1 case of 8 questions – use max 35 mins
  • 1 case of 8 questions – use max 35 mins

You have to complete each (of the three) part before you can continue to the next “world”.
There is no going back to a previous part, so if you are unsure, then it is nice to know in advance how much time you can spend on each part.

Hints:

There are some areas that are not covered thoroughly by neither the free eBook, MVA videos nor the HOL, so please study in advance:

Some areas you will find covered in the free eBook like

The API is divided into two tests

  1. 70-481
  2. 70-482

You will in the tables see a prefix of 1 or 2 many places. You should only concentrate on the test you are trying to pass, since learning both at the same time probably gives you information overflow.

WinRT API
http://msdn.microsoft.com/en-us/magazine/jj651567.aspx

Category NameSpaces Samples Abbreviated Code. License:MS-LPL
User Interface
Graphics
Windows.Graphics.Display
Windows.Graphics.Imaging
Windows.UI.Xaml.Media
Windows.UI.Xaml.Media.Animation
Windows.UI.Xaml.Media.Imaging
Windows.UI.Xaml.Shapes
User Interface
Controls
Windows.Storage.Pickers
Windows.UI.Xaml.Controls
Windows.UI.Xaml.Controls.Primitives
WinJS.UI
User Interface
Presentation
Windows.UI
Windows.UI.ApplicationSettings
Windows.UI.Core
Windows.UI.Core.AnimationMetrics
Windows.UI.Notifications
Windows.UI.Popups
Windows.UI.StartScreen
Windows.UI.Text
Windows.UI.ViewManagement
Windows.UI.Xaml
Windows.UI.Xaml.Controls
Windows.UI.Xaml.Controls.Primitives
Windows.UI.Xaml.Documents
Windows.UI.Xaml.Media.Animation
Windows.UI.Xaml.Media.Media3D
Windows.UI.Xaml.Navigation
WinJS.Navigation
WinJS.UI
WinJS.UI.Animation
WinJS.UI.Fragments
WinJS.UI.Pages
SDK: Loading HTML Fragments – First load files – then execute js in script loaded via loaded html

        ready: function (element, options) {
            this.fragmentScriptCSSDiv = element.querySelector("#fragmentScriptCSSDiv");
            WinJS.Utilities.query("#fragmentScriptCSSButton", element).listen("click", this.defaultScript.bind(this));
        },
        defaultScript: function () {
            var that = this;
            // Read fragment from the HMTL file and load it into the div. This fragment also loads linked CSS and JavaScript specified in the fragment
            WinJS.UI.Fragments.renderCopy("/html/4_FragmentScriptCSS_fragment.html",this.fragmentScriptCSSDiv).done(function (fragment) {
                        // After the fragment is loaded into the target element,CSS and JavaScript referenced in the fragment are loaded.  The
                        // fragment loads script that defines an initialization function, so we can now call it to initialize the fragment's contents.
                        FragmentScriptCSS_Fragment.fragmentLoad(fragment);
                        console.log("successfully loaded fragment, change date to fire change event.", "sample", "status");
                    },
                    function (error) {}
            );
        }

LoadedScript.js

    WinJS.Namespace.define('FragmentScriptCSS_Fragment', {
        fragmentLoad: fragmentLoad,
    });
    function fragmentLoad(root) {
        WinJS.UI.processAll(root).then(function () {
            WinJS.Utilities.query('.fragDatePicker', root).control({
                onchange: changeHandler
            });
        });
    }
    function changeHandler() {console.log("fragDatePicker change fired: " + ++changeHitCount, "sample", "status");
    }
User Interface
UIAutomation
Windows.UI.Xaml.Automation
Windows.UI.Xaml.Automation.Peers
Windows.UI.Xaml.Automation.Provider
Windows.UI.Xaml.Automation.Text
User Interface
Printing
Windows.Graphics.Printing
Windows.Graphics.Printing.OptionDetails
Windows.UI.Xaml.Printing
User Interface – Input
User interaction
Windows.UI.Input
Windows.UI.Input.Inking
Windows.UI.Xaml.Input
 CSS

  • -ms-user-select
    • none
    • inherit
    • text
    • element
    • auto
  • -ms-content-zooming
    • none
    • zoom
  • -ms-scroll-snap
  • -ms-touch-select
    • none
    • grippers
  • -ms-touch-action
    • none
    • auto
    • pan-x / pan-y
    • pinch-zoom
    • manipulation 
Gestures

Gesture Mouse Keyboard MSGesture Events CSS
Tap LeftClick Enter Tap
Hold RightClick RightClick button Hold
Swipe to select RightClick RightClick button or Space Start+Change+End .textbox {-ms-user-select:text;-ms-touch-select:grippers;}
Slide Drag on scrollbar Arrow keys Start+Change+End
Slide + inertia Drag on scrollbar, MouseWheel Page Up/Down Start+Change+End
Zoom: Pinch/Stretch Ctrl + MouseWheel Ctrl+/- Start+Change+End {overflow:auto;-ms-content-zooming:zoom;-ms-touch-action:manipulation;}
Rotate Ctrl + Shft + MouseWheel Ctrl+/- Start+Change+End

CodeShow: Pointer Input

        ready: function (element, options) {
            var d1 = q(".homepage #clickPointer #parent > div:nth-of-type(1)");
            d1.onclick = function (e) { d1.innerHTML += "click
"; };
            var d2 = q(".homepage #clickPointer #parent > div:nth-of-type(2)");
            d2.addEventListener("MSPointerUp", function (e) {
                switch (e.pointerType) {
                    case e.MSPOINTER_TYPE_TOUCH: d2.innerHTML += "touch
"; break;
                    case e.MSPOINTER_TYPE_PEN: d2.innerHTML += "pen
"; break;
                    case e.MSPOINTER_TYPE_MOUSE: d2.innerHTML += "mouse
"; break;
                }
            });
            //gesture
            var gr = new Windows.UI.Input.GestureRecognizer();
            var target = q(".homepage #gesture .target");
            target.addEventListener("MSPointerDown", function (e) {
                gr.processDownEvent(e.currentPoint);
                e.currentTarget.msSetPointerCapture(e.pointerId);
                e.msTouchAction = "none";
            }, false);
            target.addEventListener("MSPointerMove", function (e) { gr.processMoveEvents(e.intermediatePoints); }, false);
            target.addEventListener("MSPointerUp", function (e) { gr.processUpEvent(e.currentPoint); }, false);
            target.addEventListener("MSPointerCancel", function (e) { gr.completeGesture(); }, false);
            var gs = Windows.UI.Input.GestureSettings;
            gr.gestureSettings = 65535; //gs.hold | gs.holdWithMouse | gs.tap | gs.drag;
            gr.addEventListener("holding", function (e) { target.innerHTML += "holding
"; });
            gr.addEventListener("tapped", function (e) { target.innerHTML += "tapped
"; });
            gr.addEventListener("righttapped", function (e) { target.innerHTML += "righttapped
"; });
            gr.addEventListener("dragging", function (e) { target.innerHTML += "dragging"; });
            gr.addEventListener("crosssliding", function (e) { target.innerHTML += "crosssliding
"; });
            //gr.addEventListener("manipulationstarted", function (e) { target.innerHTML += "manipulationstarted
"; });
            //gr.addEventListener("manipulationupdated", function (e) { target.innerHTML += "manipulationupdated
"; });
            gr.addEventListener("manipulationcompleted", function (e) { target.innerHTML += "manipulationcompleted
"; });
        }
2 Media Windows.Media
Windows.Media.Capture
Windows.Media.Devices
Windows.Media.MediaProperties
Windows.Media.Playlists
Windows.Media.PlayTo
Windows.Media.Protection
Windows.Media.Transcoding
Windows.UI.Xaml.Media
From simple media playback and media capture, to transcoding of media and playing media to external devices via the Play To contract, you’ll find Windows APIs in the Windows.Media namespace:

Devices Windows.Devices.Enumeration
Windows.Devices.Enumeration.Pnp
Windows.Devices.Geolocation
Windows.Devices.Input
Windows.Devices.Portable
Windows.Devices.Printers.Extensions
Windows.Devices.Sensors
Windows.Devices.Sms
Communication & Data
Social
Windows.ApplicationModel.Contacts
Windows.ApplicationModel.Contacts.Provider
Using classes from the Windows.ApplicationModel.Contacts namespace, you can launch the Contact Picker and acquire contacts. For apps that need to supply contacts to other apps, you can use the ContactPickerUI class to create a collection of contacts:

SDK: Contact “client” consumer

        ready: function (element, options) {
           var nsContacts = Windows.ApplicationModel.Contacts;
           //Wire to contactpicker
            document.getElementById("contactsbut").addEventListener("click", function (e) {
                var picker = new nsContacts.ContactPicker();
                picker.commitButtonText = "Select a friend";
                //Select only few fields (opposed to whole obj)
                picker.selectionMode = nsContacts.ContactSelectionMode.fields;
                picker.desiredFields.append(nsContacts.KnownContactField.email);picker.desiredFields.append(nsContacts.KnownContactField.location);
                picker.pickSingleContactAsync().done(function (x) {if (x !== null) {
                    document.getElementById("contactsdiv").innerText = x.name + " " + x.emails[0].value + " " + x.locations[0].city;
                }});
            });
        }

SDK: Contact “server” provider. Must have: Manifest – Declarations – Contact Picker

    var contactPickerUI;
    app.onactivated = function (args) {
        if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.contactPicker) {
            //contactPickerUI is the request from the consumer asking for single vs. multiple mode and object vs. fields, but also the basket to return
            contactPickerUI = args.detail.contactPickerUI;
            args.setPromise(WinJS.UI.processAll().then(function () {
                // Load contacts from hardcoded JSON objects.
                sampleContacts.forEach(createContactUI);
                contactPickerUI.addEventListener("contactremoved", onContactRemoved, false);
            }));
        }
    };
    function createContactUI(sampleContact, index) {
        var element = document.createElement("div");
        document.getElementById("contactList").appendChild(element);
        element.innerHTML = "</pre>
<div class="contact"><label><input id="&quot; + sampleContact.id + &quot;" type="checkbox" value="&quot; + index + &quot;" />" + sampleContact.name + "</label></div>
<pre>";
        element.firstElementChild.addEventListener("change", function (ev) {
            if (ev.target.checked) { addContactToBasket(sampleContact);}
            else                   { removeContactFromBasket(sampleContact);}
        }, false);
    }
    function addContactToBasket(sampleContact) {
        var contact = new Windows.ApplicationModel.Contacts.Contact();
        contact.name = sampleContact.name;
        appendEmail(contact.fields, sampleContact.homeEmail, Windows.ApplicationModel.Contacts.ContactFieldCategory.home);
        appendPhoneNumber(contact.fields, sampleContact.workPhone, Windows.ApplicationModel.Contacts.ContactFieldCategory.work);
        appendAddress(contact.fields, sampleContact.address, Windows.ApplicationModel.Contacts.ContactFieldCategory.none);
        // Add the contact to the basket
        switch (contactPickerUI.addContact(sampleContact.id, contact)) {
            case Windows.ApplicationModel.Contacts.Provider.AddContactResult.added:
                statusMessage.innerText = sampleContact.name + " was added to the basket";
                break;
            case Windows.ApplicationModel.Contacts.Provider.AddContactResult.alreadyAdded:
                break;
            case Windows.ApplicationModel.Contacts.Provider.AddContactResult.unavailable:
            default:
                statusMessage.innerText = sampleContact.name + " could not be added to the basket";
                break;
        }
    }
    function appendEmail(fields, email, category) {
        appendField(fields, email, Windows.ApplicationModel.Contacts.ContactFieldType.email, category);
    }
    function appendField(fields, value, type, category) {
        if (value) { fields.append(new Windows.ApplicationModel.Contacts.ContactField(value, type, category)); }
    }
    function removeContactFromBasket(sampleContact) {
        if (contactPickerUI.containsContact(sampleContact.id)) {
            contactPickerUI.removeContact(sampleContact.id);
        }
    }
    function onContactRemoved(e) {
        var contactElement = document.getElementById(e.id);
        var sampleContact = sampleContacts[contactElement.value];
        contactElement.checked = false;
    }
Communication & Data
Remote Desktop
Remote Desktop app container client
RemoteApp and Desktop Connections workspaces API
Communication & Data
Networking
Windows.Networking
Windows.Networking.BackgroundTransfer
Windows.Networking.Connectivity
Windows.Networking.NetworkOperators
Windows.Networking.Proximity
Windows.Networking.PushNotifications
1/2 Windows.Networking.Sockets
Whether you’re connecting to the network via TCP using the StreamSocket class, connecting via User Datagram Protocol (UDP) using the DatagramSocket, or simply querying for networking information status to figure out whether you can save some application data to a Web service or need to save it locally, you can find what you need in the Windows.Networking namespace:

Communication & Data
Data and content
Windows.ApplicationModel.DataTransfer
Windows.ApplicationModel.DataTransfer.ShareTarget
Windows.Data.Html
Windows.Data.Json
Windows.Data.Xml.Dom
Windows.Data.Xml.Xsl
Windows.Web
Windows.Web.AtomPub
Windows.Web.Syndication
Windows.UI.Xaml.Data
Windows.UI.Xaml.Documents
WinJS.Binding
Your app can also share content with another app via the Share charm. Here are some examples:

Communication & Data
Files and folders
Windows.Storage
Windows.Storage.AccessCache
Windows.Storage.BulkAccess
Windows.Storage.Compression
Windows.Storage.FileProperties
Windows.Storage.Pickers
Windows.Storage.Pickers.Provider
Windows.Storage.Provider
Windows.Storage.Search
Windows.Storage.Streams
CodeShow: Storage – Azure

        ready: function (element, options) {
            var inputAzure = q(".storage #azureMobile input");
            var storagedemo;
            var azclient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://yourservice.azure-mobile.net/","xGQqIbWxzyzXXXXXXXXXXXXXXXXXXXXX");
            azclient.getTable("appSupport").read().then(
                    function(table) { storagedemo = table.filter(function(r) { return r.key === "storagedemo"; })[0]; },
                    function() { storagedemo = { value: "" }; }
                ).then(
                    function () { inputAzure.value = storagedemo.value; }
                );
            q(".storage #azureMobile button").onclick = function(e) {
                storagedemo.value = inputAzure.value;
                azclient.getTable("appSupport").update(storagedemo);
            };
        },
1 Fundamentals
Globalization
Windows.Globalization
Windows.Globalization.Collation
Windows.Globalization.DateTimeFormatting
Windows.Globalization.Fonts
Windows.Globalization.NumberFormatting
Fundamentals
Security
Windows.Security.Authentication.OnlineId
Windows.Security.Authentication.Web
Windows.Security.Credentials
Windows.Security.Credentials.UI
Windows.Security.Cryptography
Windows.Security.Cryptography.Certificates
Windows.Security.Cryptography.Core
Windows.Security.Cryptography.DataProtection
Windows.Security.ExchangeActiveSyncProvisioning
You can retrieve credentials, which can then be passed to APIs that might require credentials (for example, to support single sign-on). You can also use password-based strong encryption to securely store private information on a local computer to protect credit-card accounts, bank accounts and software products. You can even perform many different forms of encryption using the Windows.Security.Cryptography namespace:

SDK: Login with Windows credentials (and play around with userinfo, -contacts and -events) – or do just “wl.signin”:

        var authenticator = new Windows.Security.Authentication.OnlineId.OnlineIdAuthenticator();
        var serviceTicketRequest = new Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest("wl.basic wl.contacts_photos wl.calendars", "DELEGATION");
        SdkSample.authenticator.authenticateUserAsync(serviceTicketRequest).done(function (authResult) {
                if (authResult.tickets[0].value !== "") {
                    SdkSample.accountStatus.isSignedIn = true;
                    SdkSample.accountStatus.delegationTicket = authResult.tickets[0].value;
                    if (SdkSample.accountStatus.delegationTicket !== "") {
                        retrieveUserInfo();
                        retrieveContacts();
                        retrieveActivity();
                    }
                }
            }, function (authStatus) {
                if (authStatus.name === "Canceled") { SdkSample.displayStatus("Canceled");
                } else { SdkSample.displayError("Autorization failed: " + authStatus.message);
                }
            });

SDK: Login with Web credentials:

        facebookURL += clientID + "&redirect_uri=" + encodeURIComponent(callbackURL) + "&scope=read_stream&display=popup&response_type=token";
        var startURI = new Windows.Foundation.Uri(facebookURL); var endURI = new Windows.Foundation.Uri(callbackURL);
        Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
            Windows.Security.Authentication.Web.WebAuthenticationOptions.none, startURI, endURI)
            .done(function (result) {
                document.getElementById("FacebookReturnedToken").value = result.responseData;
                if (result.responseStatus === Windows.Security.Authentication.Web.WebAuthenticationStatus.errorHttp) {
                    document.getElementById("FacebookDebugArea").value += "Error returned: " + result.responseErrorDetail + "\r\n";
                }
            }, function (err) {
            });

SSO with Web credentials:

        var redirectURL = Windows.Security.Authentication.Web.WebAuthenticationBroker.getCurrentApplicationCallbackUri().absoluteUri;
        var startURL = "https://?client_id=&redirect_uri=" + encodeURIComponent(redirectURL) + "&scope=&response_type=token";
        var startURI = new Windows.Foundation.Uri(startURL);
        Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
            Windows.Security.Authentication.Web.WebAuthenticationOptions.silentMode, startURI).done(function (result) {
                if (result.responseStatus === Windows.Security.Authentication.Web.WebAuthenticationStatus.errorHttp) {
                    document.getElementById("FacebookDebugArea").value += "Error returned: " + result.responseErrorDetail + "\r\n";
                }
                // Parse out the OAuth token from result.responseData
            }, function (err) {
                console.log("Error returned by WebAuth broker: " + err, "Web Authentication SDK Sample", "error");
            });

CodeShow: Login with Windows Live credentials:

            WL.init();
            WL.Event.subscribe("auth.login", function () { if (WL.getSession()) log("You are signed in!"); });
            WL.Event.subscribe("auth.sessionChange", function () { if (WL.getSession()) log("Your session has changed."); });
            q("#signIn", section1).onclick = function (e) {
                if (WL.getSession()) log("You are already signed in!");
                else WL.login({ scope: "wl.signin" });
            };

CodeShow: Login with Windows credentials via Azure Mobile Services (WAMS):

            var microsoftSection = q(".authentication #wams #microsoft");
            q("button", microsoftSection).onclick = function (e) { app.client.login("microsoftaccount").done(function (results) {
                        q("div", microsoftSection).innerText += "User ID: " + results.userId;
                   }, function (error) { });
            };

SDK: Credential “client”-App/picker:

        ready: function (element, options) {
            document.getElementById("button1").addEventListener("click", function () {
                try {
                    var options = new Windows.Security.Credentials.UI.CredentialPickerOptions();
                    options.message = document.getElementById("InputMessage").value;
                    options.caption = "Cred picker heading";
                    options.targetName = document.getElementById("InputTarget").value;
                    options.alwaysDisplayDialog = true;
                    options.callerSavesCredential = true;
                    options.authenticationProtocol = Windows.Security.Credentials.UI.AuthenticationProtocol.negotiate;
                    options.credentialSaveOption = Windows.Security.Credentials.UI.CredentialSaveOption.selected;
                    Windows.Security.Credentials.UI.CredentialPicker.pickAsync(options).then(function (results) {
                        document.getElementById("OutputDomainName").value = results.credentialDomainName;
                        document.getElementById("OutputUserName").value = results.credentialUserName;
                        document.getElementById("OutputPassword").value = results.credentialPassword;
                        document.getElementById("OutputCredentialSaved").value = results.credentialSaved ? "Yes" : "No";
                        document.getElementById("OutputCredentialSaveState").value = (results.credentialSaveOption === Windows.Security.Credentials.UI.CredentialSaveOption.hidden) ? "Hidden" :
                                                                                     ((results.credentialSaveOption === Windows.Security.Credentials.UI.CredentialSaveOption.selected) ? "Selected" : "Unselected");
                        console.log("pickAsync status: " + results.errorCode, "sample", "status");
                    });
                } catch (err) { console.log("Error message: " + err.message, "sample", "error"); }
            }, false);
        }
 

SDK: Backup-Restore to PasswordVault – as Web Credential – like a login to a webpage (the Vault is synced! )

        ready: function (element, options) {
            document.getElementById("Scenario1SignIn").addEventListener("click", signInScenario1, false);
            document.getElementById("Scenario1Launch").addEventListener("click", launchScenario1, false);
        }
    function signInScenario1() {
        try { //Backup creds
            var vault = new Windows.Security.Credentials.PasswordVault();
            var cred = new Windows.Security.Credentials.PasswordCredential("Scenario 1", document.getElementById("InputUserNameValue").value, document.getElementById("InputPasswordValue").value);
            vault.add(cred);
            document.getElementById("Scenario1WelcomeMessage").value = "Welcome to Scenario 1, " + cred.userName + " 'Control Panel->User Accounts>Credential Manager'";
        } catch (e) { console.log(e.message);}
    }
    function launchScenario1() {
        try { //Restore creds
            var vault = new Windows.Security.Credentials.PasswordVault();
            var creds = vault.findAllByResource("Scenario 1");
            document.getElementById("Scenario1WelcomeMessage").value = "Welcome to Scenario 1, " + creds.getAt(0).userName;
        } catch (e) { /* No stored credentials */}
    }
Fundamentals
Core
Windows.ApplicationModel
Windows.ApplicationModel.Activation
Windows.ApplicationModel.Background
Windows.ApplicationModel.Core
Windows.ApplicationModel.Resources
Windows.ApplicationModel.Resources.Core
Windows.ApplicationModel.Resources.Management
Windows.ApplicationModel.Search
Windows.ApplicationModel.Store
Windows.Foundation
Windows.Foundation.Collections
Windows.Foundation.Diagnostics
Windows.Foundation.Metadata
Windows.Management.Core
Windows.Management.Deployment
Windows.System
Windows.System.Display
Windows.System.Profile
Windows.System.RemoteDesktop
Windows.System.Threading
Windows.System.Threading.Core
Windows.System.UserProfile
Windows.UI.WebUI
Windows.UI.Xaml
Windows.UI.Xaml.Hosting
Windows.UI.Xaml.Interop
Windows.UI.Xaml.Markup
Windows.UI.Xaml.Resources
WinJS
WinJS.Application
WinJS.Resources
You can let users search within your app when they select the Search charm and display suggestions in the Search pane.

Fundamentals
Helpers
WinJS.Class
WinJS.Namespace
WinJS.Utilities

Roadmap for Windows Store apps using JavaScript (see also roadmap for C#, VB and C++)

Sections Topics – including some code. License:MS-LPL
Get startedProgramming Windows 8 Apps with HTML, CSS, and JavaScript
Hands-on labs for Windows 8
Create a basic user interface
Choosing the right UI surfaces

Start by ensuring that your app uses the right surface at the right time.
Guidelines for user interaction

Learn how to create an app that users can interact with in intuitive and immersive ways, no matter what device or input method they use.

#selectableDiv {
    -ms-user-select: element;
    cursor: text;
}
Accessibility

Learn how to make your app accessible to the widest possible audience, including people who have impairments or disabilities.
App bars

The app bar presents navigation, commands, and tools to users.
Context menus

Context menus display up to five commands that enable users to take immediate action that is relevant to what they are doing.
1 QuickStart: Controls – HTML

Create controls and connect them to code.Tip: Sample includes a theme changer
QuickStart: Controls and styles – WinJS

Use Windows Library for JavaScript controls and styles.
Layouts and views

When you plan for full screen, snap, and fill views, your UI can elegantly reflow across whatever size screen it’s on, no matter the screen orientation or user interaction view.
http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_multi-column.htm:

.columnbox {
    -webkit-column-count: 3; /* or auto, when using -width*/
    -webkit-column-width: auto; /* or e.g 15em. Set auto, when using -count */
    -webkit-column-gap: normal; /* or px*/
    -webkit-column-rule-color: gray;
    -webkit-column-rule-style: solid; /* none*/
    -webkit-column-rule-width: 2px;
    height: auto;
    overflow: auto;
}

CodeShow: Swipe Sections (using Snap Points)

.swipeSections .swiper {
    display: -ms-flexbox;
    width:100%;
    overflow-x: scroll;/*outer scroll x*/
    /* Snap to 80% of the width of this box width, which equals the width of the child boxes */
    -ms-scroll-snap-x: mandatory snapInterval(0%, 80%);
}
    .swipeSections .swiper > div {
        box-sizing: border-box;/*apply w/h to border, not content*/
        width: 80%;/*showing 1.2 divs inside parent*/
        border:solid 1px gray;
        overflow-y: auto; /*inner scroll y*/
        padding: 20px;
        padding-right: 60px; /*space for scroll y*/
    }

CodeShow: Snap Points

.snappoints #list .win-viewport {
    /* Snap to edge of items in a listview: 150+2x20+10(spacing)=200 */
    -ms-scroll-snap-x: mandatory snapInterval(0px,200px);
}
    .snappoints #list .win-item {
        width: 150px;
        padding: 20px;
    }
Navigation

        ready: function (element, options) {
            WinJS.Utilities.query("a").listen("click", linkClickEventHandler, false);
        }
function linkClickEventHandler(eventInfo) { //Wired to a navigation button
    eventInfo.preventDefault(); //prevent normal navigation
    WinJS.Navigation.navigate(eventInfo.target.href); //navigata and store history
}
init: function (element, options) {
this.beforenavigate = this.beforenavigate.bind(this);
this.navigating = this.navigating.bind(this);
this.navigated = this.navigated.bind(this);
},
ready: function (element, options) {
WinJS.Utilities.query("a", this.element).listen("click", this.navigationClicked.bind(this));
WinJS.Navigation.addEventListener("beforenavigate",this.beforenavigate);
WinJS.Navigation.addEventListener("navigating",this.navigating);
WinJS.Navigation.addEventListener("navigated",this.navigated);
},
navigationClicked: function (eventObject) {
var destUrl = this.getRelativeUrl(eventObject.target.href);
eventObject.preventDefault();// Prevent the default browser navigation
WinJS.Navigation.navigate(destUrl, this.getNavState()); //1
},
getNavState: function () {
var stateObject = { data: "" };
var input = this.element.querySelector("#navigationEventsNavigationState");
if (input.value) {
stateObject.data = toStaticHTML(input.value);
return stateObject;
}
return null;
},
beforenavigate: function (eventObject) { //2
if (this.shouldPreventNavigation) {
console.log("Navigation to " + eventObject.detail.location + " was prevented", "sample", "status");
eventObject.preventDefault(); //Quit the navigation
}
},
navigating: function (eventObject) { //3
if (this.doAsyncBeforeNavigating) {
console.log("Completing 5 second async operation before navigating to " + eventObject.detail.location,"sample", "status");
eventObject.detail.setPromise(WinJS.Promise.timeout(5000));
}
},
navigated: function (eventObject) { //4
console.log("Navigation to " + eventObject.detail.location + " completed",
"sample", "status");
},
unload: function () { //5
// If you don't, you end up leaking memory.
WinJS.Navigation.removeEventListener("beforenavigate", this.beforenavigate);
WinJS.Navigation.removeEventListener("navigating", this.navigating);
WinJS.Navigation.removeEventListener("navigated", this.navigated);
}
<meta name="ms-https-connections-only" content="true" /><!-- Only use HTTPS connections. -->

Navigate between pages or display content from other pages.E.g. from test: SelectAll ————– Filter | Remove, Add

Pen and stylus input

Enable digital ink functionality using a pointer device such as a pen or stylus.

function initialize() {
    inkCanvas = document.getElementById("inkCanvas");
    inkCanvas.addEventListener("MSPointerDown", onPointerDown, false);
    inkCanvas.addEventListener("MSPointerMove", onPointerUpdate, false);
    inkCanvas.addEventListener("MSPointerUp", onPointerUp, false);
    inkContext = inkCanvas.getContext("2d");
}
var inkManager = new Windows.UI.Input.Inking.InkManager();
function onPointerDown(evt) {
        var current = evt.currentPoint;
        // we only consider pen and mouse (with a button set) pointer types, we ignore touch
        if (((evt.pointerType === evt.MSPOINTER_TYPE_PEN) && (evt.button === 2)) ||
            ((evt.pointerType === evt.MSPOINTER_TYPE_MOUSE) && (evt.button === 0) && (evt.ctrlKey === true))) {
            inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.selecting; // select mode
            inkContext.lineWidth = 0.1;
            inkContext.strokeStyle = toColorString(Windows.UI.Colors.gold);
            inkContext.beginPath(); // start live rendering
            inkContext.moveTo(current.rawPosition.x, current.rawPosition.y);
        } else if (((evt.pointerType === evt.MSPOINTER_TYPE_PEN) && (current.properties.isEraser)) ||
                   ((evt.pointerType === evt.MSPOINTER_TYPE_MOUSE) && (evt.button === 2))) {
            inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.erasing; // erase mode
        } else if ((evt.pointerType === evt.MSPOINTER_TYPE_PEN) ||
                  ((evt.pointerType === evt.MSPOINTER_TYPE_MOUSE) && (evt.button === 0))) {
            inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.inking; // ink mode
            inkContext.lineWidth = currentWidth;
            inkContext.strokeStyle = toColorString(currentColor);
            inkContext.beginPath(); // start live rendering
            inkContext.moveTo(current.rawPosition.x, current.rawPosition.y);
        }
        inkManager.processPointerDown(current); // add current point to inkManager
}
function onPointerUpdate(evt) {
        var current = evt.currentPoint;
        // add current point to inkManager
        var update = inkManager.processPointerUpdate(current); // the return value is a dirty rect if we are in erasing mode.
        if (inkManager.mode === Windows.UI.Input.Inking.InkManipulationMode.erasing) {
            if (update.height > 0 || update.width > 0) { renderAllStrokes(); }
        } else {
            inkContext.lineTo(current.rawPosition.x,  // live rendering is done here
            inkContext.stroke();
        }
}
function onPointerUp(evt) {
        inkManager.processPointerUp(evt.currentPoint); // add current point to inkManager (stroke is ended with this point)
        inkContext.closePath(); // done with live rendering
        renderAllStrokes();
}
function renderAllStrokes() {
    inkContext.clearRect(0, 0, inkCanvas.width, inkCanvas.height);
    inkManager.getStrokes().forEach(
        function (stroke) {
            var color = toColorString(stroke.drawingAttributes.color);
            var width = stroke.drawingAttributes.size.width;
            if (stroke.selected) {
                renderStroke(stroke, color, width + 2);
                renderStroke(stroke, toColorString(Windows.UI.Colors.white), width);
            }
            else {
                renderStroke(stroke, color, width);
            }
        }
    );
}
function renderStroke(stroke, color, width) {
    inkContext.strokeStyle = color;
    inkContext.lineWidth = width;
    inkContext.beginPath();
    // render all rendering segments for the current stroke
    var first = true;
    stroke.getRenderingSegments().forEach(
        function (segment) {
            if (first) {
                inkContext.moveTo(segment.position.x, segment.position.y);
                first = false;
            } else {
                inkContext.bezierCurveTo(segment.bezierControlPoint1.x, segment.bezierControlPoint1.y,
                                         segment.bezierControlPoint2.x, segment.bezierControlPoint2.y,
                                         segment.position.x, segment.position.y);
            }
        }
    );
    inkContext.stroke();
    inkContext.closePath();
}
Resources

Create and manage app UI resources such as images and strings.
Tiles

Create and update tiles.
Toast notifications

Create and send toast notifications.
SDK: Toast notifications sample – scenario6.js

        ready: function (element, options) {
            document.getElementById("loopingButton").addEventListener("click", displayLongToast, false);
        }
    var Notifications = Windows.UI.Notifications;
    var ToastContent = NotificationsExtensions.ToastContent;
    function displayLongToast(e) {
        var content = ToastContent.ToastContentFactory.createToastText02();
        content.textHeading.text = "Long Toast";
        content.duration = ToastContent.ToastDuration.long;
        if (e.currentTarget.id === "loopingButton") {
            content.audio.content = ToastContent.ToastAudioContent.loopingAlarm;
            content.audio.loop = true;
            content.textBodyWrap.text = "Looping audio";
        } else {
            content.audio.content = ToastContent.ToastAudioContent.im;
        }
        Notifications.ToastNotificationManager.createToastNotifier().show(content.createNotification(););
    }
Touch input

Create a touch-first experience.
Manage launch, suspend, and resume
AutoPlay

Provide your app as an option when a user connects a device to their computer. This includes cameras, media players, USB thumb drives, and DVDs.
1, 2 File activation Provide your app as an option to handle a file type.
Protocol activation Provide your app as an option to handle a protocol.
1 Splash screen

The default splash screen displays when users launch your app, providing immediate feedback to users while your app initializes its resources.
SDK: How to extend the splash screen

function activated(eventObject) {
    if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        // Retrieve splash screen object
        splash = eventObject.detail.splashScreen;
        // Retrieve the window coordinates of the splash screen image.
        SdkSample.coordinates = splash.imageLocation;
        // Register an event handler to be executed when the splash screen has been dismissed.
        splash.addEventListener("dismissed", onSplashScreenDismissed, false);
        // Create and display the extended splash screen using the splash screen object.
        ExtendedSplash.show(splash);
        // Listen for window resize events to reposition the extended splash screen image accordingly.
        // This is important to ensure that the extended splash screen is formatted properly in response to snapping, unsnapping, rotation, etc...
        window.addEventListener("resize", onResize, false);
        // Use setPromise to indicate to the system that the splash screen must not be torn down until after processAll and navigate complete asynchronously.
        eventObject.setPromise(WinJS.UI.processAll().then(function () {
            // Navigate to either the first scenario or to the last running scenario
            // before suspension or termination.
            var url = WinJS.Application.sessionState.lastUrl || scenarios[0].url;
            return WinJS.Navigation.navigate(url);
        }));
    }
}
Suspend/resume When you handle app suspension and resumption, users will have a better experience with your app. They can switch away from your app and return to find it right where they left off, as if the app had been running in the background.
Implement contracts
Windows application contracts

File picker

You can help users pick files from your app while they are using another app. Users gain freedom and flexibility. Apps increase their popularity by participating in file picker contracts.
Play To Use the Play To contract to enable users to easily stream audio, video, or images from their computer to devices in their home network.
Search

You can add a search pane to your app so users can search your app’s content and content from other apps as well. Apps that participate in the Search contract gain traffic and usage.
Settings

You can implement the Settings contract so that users can access your app’s settings from the Settings charm.Application settings sample

</pre>
<div id="programmaticInvocationSettingsFlyout" data-win-control="WinJS.UI.SettingsFlyout" data-win-options="{settingsCommandId:'defaults',width:'wide'}">
<!-- Use either 'win-ui-light' or 'win-ui-dark' depending on the contrast between the header title and background color -->
<div class="win-ui-dark win-header"><button class="win-backbutton" onclick="WinJS.UI.SettingsFlyout.show()" type="button"></button>
<div class="win-label">Defaults</div>
<img style="position: absolute; right: 40px;" alt="" src="../images/smallTile-sdk.png" /></div>
<div class="win-content">
<div class="win-settings-section">
<h3>Toggle switch</h3>
Use toggle switches to let users set Boolean values.
<div id="Toggle1" data-win-control="WinJS.UI.ToggleSwitch" data-win-options="{title:'Download updates automatically',checked:true}"></div>
<div id="Toggle2" data-win-control="WinJS.UI.ToggleSwitch" data-win-options="{title:'Install updates automatically'}"></div>
</div>
<div class="win-settings-section">
<h3>Push button</h3>
Users initiate an immediate action.

 <label>Button label</label>
 <button onclick="WinJS.log && WinJS.log('Clear history button pressed', 'samples', 'status')" type="button">Clear</button></div>
<div class="win-settings-section">
<h3>Select control</h3>
 <label>State</label>
<select><option value="AK">Alaska</option><option value="CA">California</option></select></div>
<div class="win-settings-section">
<h3>Hyperlink</h3>
Take the user out of this flyout.

 <a href="http://go.microsoft.com/fwlink/?LinkID=190175" target="fix_link_too">View privacy statement</a></div>
<div class="win-settings-section">
<h3>Text input box</h3>
 <label>Email account</label><input type="text" />
 <button onclick="console.log('Button pressed', 'samples', 'status')" type="button">Add</button></div>
<div class="win-settings-section">
<h3>Radio button group</h3>
 <label><input type="radio" checked="checked" name="video" value="High" />High</label>
 <label><input type="radio" name="video" value="Medium" />Medium</label></div>
</div>
</div>
<pre>

Application settings sample – Events

        ready: function (element, options) {
            WinJS.Application.onsettings = function (e) {
                e.detail.applicationcommands = { "gameOptions": { title: "Game options", href: "/html/4-SettingsFlyout-Game.html" } };
                WinJS.UI.SettingsFlyout.populateSettings(e);
            };
        }
</pre>
<div data-win-control="WinJS.UI.SettingsFlyout" data-win-options="{settingsCommandId:'gameOptions',width:'narrow',
              onbeforeshow:beforeShowHandler,onaftershow:afterShowHandler,onbeforehide:beforeHideHandler,onafterhide:afterHideHandler}">
<!-- Use either 'win-ui-light' or 'win-ui-dark' depending on the contrast between the header title and background color -->
<div class="win-ui-dark win-header" style="background-color: #00b2f0;"><!-- Background color reflects app's personality -->
 <button class="win-backbutton" onclick="WinJS.UI.SettingsFlyout.show()" type="button"></button>
<div class="win-label">Game options</div>
<img style="position: absolute; right: 40px;" alt="" src="../images/smallTile-sdk.png" /></div>
<div class="win-content">
<div class="win-settings-section">{Game options content here}</div>
</div>
</div>
<pre>
        <!-- ENDSETTINGSFLYOUT -->
<script type="text/javascript">// <![CDATA[
function beforeShowHandler(event) {//When Game options pressed
                console.log("Game options settings flyout beforeshow event raised.", "samples", "status");
            } beforeShowHandler.supportedForProcessing = true;
            function afterShowHandler(event) {
                console.log("Game options settings flyout aftershow event raised.", "samples", "status");
            } afterShowHandler.supportedForProcessing = true;
            function beforeHideHandler(event) { //When back-button pressed
                console.log("Game options settings flyout beforehide event raised.", "samples", "status");
            } beforeHideHandler.supportedForProcessing = true;
            function afterHideHandler(event) {
                console.log("Game options settings flyout afterhide event raised.", "samples", "status");
            } afterHideHandler.supportedForProcessing = true;
// ]]></script>
Sharing

Great apps make it easy for users to share what they are doing with their friends and family. Apps that support the Sharing contract can automatically share content to and from any other app that also supports the Sharing contract.
Access data and content
Accessing and publishing syndicated content Publish, update, and remove syndicated feeds or feed items.
Data binding

Data binding enables you to synchronize the elements of your app with different sources of data, including databases, files, and internal objects.
Transferring data in the background Initiate, pause, resume, report progress for, and cancel a file download operation.
Access files and folders
Accessing files with file pickers

Show the file picker when users need to select a file to open.
Accessing files programmatically Use search queries to enumerate and access files in a folder, library, device, or network location.
Launch the default app for a file Launch the default app for a file type.
Reading a writing a file Create, write, and read files from the file system.
Connect with apps and people
Network connectivity

Enable your app to monitor and maintain the integrity of a connected experience by registering for changes to network connection states or the data plan usage associated with a specific network connection.
Proximity and tapping

Connect computers that are in close range with a simple tap gesture.
User contacts

Enable users to access their contacts so they can share content, email, message each other, or interact in new ways.
Add animation and graphics
Animating your UI Use the animation library to animate lists, transitions, pointers, and UI elements and surfaces.
Drawing to a canvas Use SVG and Canvas to add fast, lightweight vector graphics to your app.
Use multimedia
Capture photos and videos Capture photos and videos in your Windows Store apps.
Play audio and video Play audio and video in your Windows Store apps.
Support devices
Enumerating devices Enumerate devices by the functionality they provide.
Accelerometers Use an accelerometer to detect changes in movement on one or two axes.
Gyrometers Use a gyrometer to detect changes in orientation and rate of rotation. Gyrometers and accelerometers work together as game controllers.
Inclinometers Use an inclinometer to detect changes in movement on the X, Y, and Z axes.
Light sensors Use a light sensor to detect and respond to changes in ambient light.
Geolocation Detect the user’s geographic location.
Printers Use print capabilities to improve the print experience for the user.
Removable storage Access content on media and storage devices, such as Windows Portable Devices (WPD), Media Transport Protocol (MTP) devices, and Mass Storage Class (MSC) devices.
Debug and test apps
Run apps from Visual Studio Run apps on local machine, simulator, or remote device.
Start a debugging session Configure and start debugging sessions.
Debugger navigation Use the Visual Studio debugger to debug apps.
Debug JavaScript apps Use VS tools to debug HTML, CSS, and JavaScript code.
Analyze app performance Use Visual Studio profiling tools for JavaScript.
Analyze memory usage Use the JavaScript Memory Analyzer to help find memory leaks.
Related topics HTML/CSS for Windows Store appsWindows API for Windows Store appsPackaging apps

Other

Ongoing…

The End

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: