Treating users right

This is an excerpt from the upcoming book Programming Windows 8 with HTML5 for Dummies

----------------------------------------

Metro apps are different.  As I mentioned in This Is Not .NET, Metro apps are optimized for touch, usually mashups, and often single use. They are not complex, menu driven or multi-functional.  They are usually for consumption, not creation. It is a totally different user experience that we are after here.

Because of this, there is a totally different design paradigm.  Now, Microsoft has tried to lay on the User Interface guidelines before with mixed success, but this time they are serious! The development environment is set up to only allow certain kinds of user interface elements, and if you step away from the path you will find your going rather tough.

Setting some design principles

Microsoft is being very clear in laying out some user interface and architectural design patterns.  It remains to be seen if these will be upheld in the review process, but they are good guidelines and should be followed.

While we will go into more detail in Chapter 2, there are a few core principles I want to use to describe Metro apps that will make the rest of this chapter make more sense. Metro apps are:

  • Socially connected. Metro apps make use of social network and public sharing networks to broadcast information, connect with friends, and make new groups.
  • Living in a sandbox. An install of the Metro app should never alter the core functionality of the user’s machine.
  • Designed for touch. These apps are designed to be run on a tablet, but should work with a mouse. Much more on this later.
  • Screen size sensitive. Like a web page, Metro apps should be sensitive to resolution, orientation, and docking.
  • Made for multitasking. Users can ‘snap’ Metro apps into specified parts of the screen, and if you want a nice looking app you have to handle that in your interface.

Using the Design Checklist

Something that Microsoft has implemented to help with the core principles is the Design Checklist. It covers what you need to make sure you have planned for in your app.

                           *  Basic design groups – core things you need to make sure you have covered

                                       *App tile – the icon that the user touches to launch your app

                                       *Splash screen – what the user sees while your app is loading

                                       *Application Lifecycle – be ready when the app gets suspended, or the battery runs out.

                                       *App bar – all your apps commands go in the same place.

                           *  Engaging the user with app contracts

                                       *Settings – how the app communicates with Windows

                                       *Search – how does it apply to your app?

                                       *Share – be social!

                                       *Play to – stream to other devices

                           *  Various Views

                                       *Full Screen

                                       *Snapped

                                       *Filled

                                       *Portrait

                                       *Scaled

                           *  Adding features – take advantage of the neat stuff you can do

                                       *Semantic Zoom

                                       *Notifications

                                       *Roaming

                                       *Content tiles

                                       *Gesture library

                                       *File picker

                                       *Animations

                                       *User tiles

Convention over configuration

You may have noticed by now that the Metro style is a lot about convention – convention being defined as how Apple decided to make the IPad work. You don’t actually have a lot of artistic license over how the user will interact with the meta-information related to your app; it is pretty well defined by the Design Checklist and Core Principles.

Let’s take navigation for example.  In Windows Forms application, navigation is all over the place.  There are menus and ribbons and buttons (oh my!). In MetroUI, however, the navigation of the application should be document oriented, and in the app bar, at the bottom of the application.

The programming model supports this, in fact.  It supports it so well that there really isn’t any other way to implement the app bar.  To see what I mean, open up the Hello World application we made in Getting There Ourselves.

In the HTML, inside the body tag, add a div that represents the AppBar control.  Notice the data-win-control declaration:

<body>

    <h1 id="headline"></h1>

   <div data-win-control="WinJS.UI.AppBar" id="appbar">

   <button data-win-control="WinJS.UI.AppBarCommand" data-win-options="{icon:'back', id:'', label:'example', onclick:null, section:'global', type:'button'}"></button>

   </div>

</body>

Now you can run the application, and have a nice back button in the app bar. All of your navigational type stuff would go here – start over, change views, go home.  Not in a menu, not in the page.  In the app bar.

CSSLP continued - uCertify's web client

Well, I had planned to take my CSSLP in April but life got in the way, so I am shooting for more of an August timeframe now, after the book is written.

uCertify has a web client that I thought would work out well for me since I keep moving back and forth between different machines. I think they are pushing to the web to draw in tablet users, but either way, it works out well for me.

The web is a lot like the PC version in functionality. They have four test styles - the pre-assessment, the quiz, a regular practice test, and a new thing, Flash Cards, which I think are very cool. There are four study materials, too: the textbook, reports on your trials, a planner and the Final Test, which you should get a 95 on before you go take the exam.

The whole thing is implemented in HTML, and is occasionally a little choppy. I am running it in Firefox right now, and it is a little better than it behaved in IE10. It is very touch friendly and runs well on my Windows 8 slate.

The content is just as good as the PC version, and I feel very secure having it as my study partner. The flash cards are awesome - just like something you might have written for yourself in school: the term on one side, the definition on the other. I think this plus the official textbook will get me through the test. We'll see in August, though. The proof is in the pudding!

You can learn more about the uCertify web client at learn.ucertify.com.

Updating your Windows 8 HTML 5 Metro project to RC

In updating my Metro app to Windows 8 RC, I only ran into one incompatibility - Microsoft revved WinJS (as they should!) The error I got was:

Error 1 Could not find SDK "Microsoft.WinJS, Version=0.6". C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets 1682 6 ToDoToday

All I had to do was delete the old reference from the References folder, right click and Add Reference, and select the new version. Looks like this:

 

Then I needed to change my references. The original default.html has this WinJS Reference code:

<link href="//Microsoft.WinJS.0.6/css/ui-light.css" rel="stylesheet">
<script src="//Microsoft.WinJS.0.6/js/base.js"></script>
<script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

 And I changed it to this:

<link rel="stylesheet" href="//Microsoft.WinJS.1.0.RC/css/ui-light.css" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>

 And then everything worked!

Upcoming talks

I'm speaking at the Louisville .NET Developer's group about ASP.NET MVC pen testing and the OWASP Top 10 on Thursday June 21.

I'm also scheduled to speak at That Conference, a developer summer camp in Wisconsin on August 13-15. I'm speaking about Charms and Contracts in Windows 8 Metro and how they impacted my current project's design.

I'm planning on attending BSides Cleveland on June 13, and I have three papers in for submission. If you would like to see any of them, let the organizers know at @bsidescleveland.

Windows 8 Metro HTML parser closes tags as you add them to an element.

I found some interesting HTML Parsing behavior in Metro.  I had been stuck on a positioning issue for a bit, so I went to the DOM explorer to see what was going on. (Shoulda done that first!) As it turns out, this code:

newCommentsBin.innerHTML = "";
for (var comment in newComments) {
    if (comment >= 3) { break }
    newCommentsBin.innerHTML += "<div class='newComment'>";
    newCommentsBin.innerHTML += "<img class='commentPic' src='" + newComments[comment].fromPicture + "'>";
    newCommentsBin.innerHTML += "<div class='commentFrom'>" + newComments[comment].fromName + "</div>";
    newCommentsBin.innerHTML += "<div class='comment'>" + newComments[comment].text + "</div>";
    newCommentsBin.innerHTML += "</div>";
}

was producing this HTML:

<div class="newComment"></div>
</div>
<img class="commentPic" src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/xxx.jpg"></img>
</img>
<div class="commentFrom">User 1</div>
</div>
<div class="comment">where do you see the icon? I don't. Is this in the BB wall?</div>
</div>
<div class="newComment"></div>
</div>
<img class="commentPic" src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/xxx.jpg"></img>
</img>
<div class="commentFrom">User 2</div>
</div>
<div class="comment">the icon shows up... yay</div>
</div>
<div class="newComment"></div>
</div>
<img class="commentPic" src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/xxx.jpg"></img>
</img>
<div class="commentFrom">User 1</div>
</div>
<div class="comment">no idea...</div>
</div>
</div>

The renderer was altomatically closing each tag as I added it to the InnerHTML property of the element! I did not know it would do that.

I got around the problem by using a variable and assigning it all at once.

Pentesting ASP.NET talk notes

I gave my Pentesting ASP.NET talk at Safelite today, celebrating the 20th presentation of  this deck. It's a good talk, I'm glad so many people like it. I know I'll be delivering it at the Louisville .NET user group in June, and there is probably some others that I am forgetting.

Anyway, there was a request for some links that I talk about diring that talk, so here they are:

The Secure Coding Practice Quick Reference Guide

The OWASP Top 10 Cheat Sheet

Troy Hunt's OWASP Top 10 ASP.NET blog series - probably the best writing on the topic ever. No foolin.

The Zed Attack Proxy

Backtrack

SET - The Social Engineer's Toolkit

Oh, and here are the sites for Defcon, Derbycon and Notacon, too.

I've been deep fried!

Keith Elder and Chris Woodruff were nice enough to have me on their excellent and very popular webcast Deep Fried Bites last month, and the episode is up and ready! We discuss the security environment for web developers today, focused on the OWASP Top 10 and testing your web app.

I had a good time on the show, and it turned out really well, I think. Hope you'll take a listen!

http://deepfriedbytes.com/podcast/episode-83-helping-web-developers-get-more-secure-with-bill-sempf/ 

Windows 8 CP installation experience

Some of you may have read my dual boot setup post when Dev Preview (DP) came out. Now it is time to upgrade that rig to Consumer Preview (CP), and I through I would give an update.

The bootable USB drive I used for DP got repurposed for CP, so the laptop got booted from that. I decided to format the partition that I had used to set up dev preview, and do a fresh install of Consumer Preview. The disk tools look unchanged (since Vista, actually) and that went painlessly. So far so good.

Interesting that the license key management has been installed, anthough it is freely avainatable. The English key is DNJXJ-7XBW8-2378T-X22TX-BKG7J. Other than that the installation was the same as DP. The install took about 6 minutes on my Intel i7.

If you are using a bootable USB note that Windows won't warn you before reboot. It will go right back into the setup routine when it is finished installing. You can just turn the machine off, unplug the USB drive, and turn the machine back on to continue installation.

The best news was that is honored my dual boot that DP set up!

 I was happy about that. There are backups, and honestly I pretty much live in Windows 8 now, but it is nice to know my Windows 7 partition is still there if I need it.

It should be noted that my display driver wasn't recognized. I downloaded the NVidia display driver from Acer's site and installed it. After a reboot, I was in business - awesomesauce.

Oh, and another thing: I installed Windows 8 CP on my Asus slate Wednesday with zero problems also. It isn't a dual boot though so I didn't think it was worth a blog post. This one is a little neater.

Hope everyone is enjoying Windows 8! Now go build some apps!!

How to login to Facebook from Windows 8 Metro using HTML 5

Facebook login with OAuth 2.0 is baked into WinRT. You can't actually use the samples on the Facebook Developer postal. So, from an application, try these steps:

  • Start with a Navigation template, or add an appbar to your app
  • Add a login button to your appbar. Should be in the default.html page in the root directory
<button id="loginButton" class="win-command" style="float: right;">
  <span class="win-commandicon win-large login"></span><span class="win-label">login</span>
</button>
  • In the related JS file, add an event handler for the button. This collects the required values for the OAuth call and then calls Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync, where all the magic happens. The scope parameter in the querystring is how you get extended permissions.
function loginButtonClick() {
        var facebookURL = "https://www.facebook.com/dialog/oauth?client_id=";
        var callbackURL = "https://www.facebook.com/connect/login_success.html";
        var clientID = "12434567890987654321";
        facebookURL += clientID + "&scope=publish_stream,publish_checkins,publish_actions,share_item&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);

        try {

            Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
								Windows.Security.Authentication.Web.WebAuthenticationOptions.default,
								startURI,
								endURI).then(callbackFacebookWebAuth, callbackFacebookWebAuthError);
        } catch (err) {
            console.log(err.message);
            return;
        }
    }
  • The promise has callbacks for completion and error. You can swallow the error, but on completion, make sure to keep the token.
function callbackFacebookWebAuth(result) {
        var url = result.responseData;
        var querystring = {};

        url.replace(
            new RegExp("([^?=&]+)(=([^&]*))?", "g"),
            function ($0, $1, $2, $3) {
            querystring[$1] = $3; }
        );
        facebookToken = querystring["access_token"];

    }
 
And that's about it. The token in facebookToken is what is used to call the open graph. For instance, to get my data, I could call the graph like this: 
 
facebookButton.addEventListener('click', function () {
	var buildUrl = "https://graph.facebook.com/billsempf/feed?access_token=" + PA.facebookToken;
	WinJS.xhr({ type: "GET", url: buildUrl }).then(parseProfileJson, promiseError);
    });

Win8 Metro Style navigation

WARNING! This is based on Developer Preview, and much has changed.

Navigation in Metro is a little fuzzy right now. Fortunately Visual Studio has a navigation template. If you click File.NewProject, and dig into the Metro JavaScript apps, then you will see the Navigation Application. It is described as a “minimal style application that uses Windows Metro style frameworks and includes navigational support.”

The Navigation Template

A look at the source that the Navigation template shows us a pretty contemporary divided-screen model.  It has div that will contain the content, and another one that has the navigation tools.

<body data-homePage="/html/homePage.html">
    <div id="contentHost"></div>
    <div id="appbar" data-win-control="WinJS.UI.AppBar" aria-label="Command Bar" data-win-options="{position:'bottom', transient:true, autoHide:0, lightDismiss:false}">
        <div class="win-left">
            <button id="home" class="win-command">
                <span class="win-commandicon win-large">xE10F;</span><span class="win-label">Home</span>
            </button>
        </div>
    </div>
</body>

The div labeled contentHost will be used to store the content that is directed there. The appbar div is of some more interest. It has a data-win-control property, which is a Metro-specific field that includes specific styles and functionality at render time.

This one is the WinJS.UI.AppBar, which is the little sliding bar that you can access in a Mero app by sweeping from the bottom. There is a 1 pixel trigger left in the bottom of all application that makes the sweep work, and the div shown here sets up the content for the bar.

Right now there is just one button in the bar. If you just click the Debug button without making any changes, you get one button that goes to one page that you already start at. Not terribly interesting.

What that AppBar is supposed to do it give you the ability to load new fragments into contentHost. You can do this with direct buttons, page numbers, or VCR style controls. Doesn’t matter, as long as the content gets loaded.

Loading the fragments is set up in default.js. Remember that weird data-homepage attribute in the body tag of the default page? Well, that’s used to set the initial page in contentHost.

WinJS.Application.onmainwindowactivated = function (e) {
        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            homePage = document.body.getAttribute('data-homePage');

            document.body.addEventListener('keyup', function (e) {
                if (e.altKey) {
                    if (e.keyCode === WinJS.Utilities.Key.leftArrow) {
                        WinJS.Navigation.back();
                    }
                    else if (e.keyCode === WinJS.Utilities.Key.rightArrow) {
                        WinJS.Navigation.forward();
                    }
                }
            }, false);

            WinJS.UI.process(document.getElementById('appbar'))
                .then(function () {
                    document.getElementById('home').addEventListener('click', navigateHome, false);
                });

            WinJS.Navigation.navigate(homePage);
        }
    }

After activating the app, a few keyboard events are handled, and then the WinJS.Navigation namespace is used to navigate the page to homepage.

Adding a fragment

One page is really quite boring – why would you need navigation for one piece of content, right? To make things a little more interesting let’s do something wild, like add a page, screen form, wqhatever you want to call it. From Microsoft’s perspective, it is a ‘fragment’ and it is treated like a form or page in any other paradigm.

To add a ‘page 2’ to the template application:

1) In the Solution Explorer, right click on the HTML folder and click Add | New Item…

2) In the Add New Item dialog select the HTML Fragment item and name is Page2.html.

3) After you have added the new fragment, all of the fragment files will be in the HTML folder, as of this writing. Move them into their correct folder. The CSS file goes in the CSS folder and the JS file goes in the JS folder.

4) Update the references in the Page2.html file to point to the new file locations.

<link rel="stylesheet" href="/css/Page2.css" />

<script type="ms-deferred/javascript" src="/js/Page2.js"></script>

5) Update the body content of Page2.html so that we can show some cool neato content when we get there.

<body>
    <div class="Page2 fragment">
        <header role="banner" aria-label="Header content">
            <button disabled class="win-backbutton" aria-label="Back"></button>
            <div class="titleArea">
                <h1 class="pageTitle win-title">Welcome to Page2</h1>
            </div>
        </header>
        <section role="main" aria-label="Main content">
            <p>This is my new page 2! Isn’t it cool?</</p>
        </section>
    </div>
</body>

6) In default.html, add a button that will take the user to page 2. This goes in the appbar div.

<div id="appbar" data-win-control="WinJS.UI.AppBar" aria-label="Command Bar" data-win-options="{position:'bottom', transient:true, autoHide:0, lightDismiss:false}">
    <div class="win-left">
        <button id="home" class="win-command">
            <span class="win-commandicon win-large">xE10F;</span><span class="win-label">Home</span>
        </button>
        <button id="page2" class="win-command">
            <span class="win-commandicon win-large">xE10F;</span><span class="win-label">Page2</span>
        </button>
    </div>
</div>

7) In default.js, you will need an event handler for the new button.   Add it to the process method for the appbar (it’s near the end).

WinJS.UI.process(document.getElementById('appbar'))
    .then(function () {
        document.getElementById('home').addEventListener('click', navigateHome, false);
        document.getElementById('page2').addEventListener('click', navigatePage2, false);
        });
WinJS.Navigation.navigate(homePage);

8) Hey, we need a navigatePage2 method, don’t we? Let’s add that above the process code.

function navigatePage2() {
    WinJS.Navigation.navigate("html/page2.html");
    WinJS.UI.getControl(document.getElementById('appbar')).hide();
}

That should be everything we need. Press F5 to run and (if you are on a regular machine) press Windows+Z to bring up the new appbar. Tap that neat new Page 2 button. And of course here is more to it than this. You might need to keep an array of pages in memory and provide a next/back button, or give random access via a menu. The principles are the same though. Good luck!

Bill Sempf

Husband. Father. Pentester. Secure software composer. Brewer. Lockpicker. Ninja. Insurrectionist. Lumberjack. All words that have been used to describe me recently. I help people write more secure software.

 

 

PageList

profile for Bill Sempf on Stack Exchange, a network of free, community-driven Q&A sites

MonthList