Animating Windows

 

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

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

The component animation that is inherent to HTML5 and even JQuery is not only supported in Metro, it is encouraged. The navigation model is new through, and there are bits in WinRT that make it easy to animate.

 

Everything for page and content level animation (sometimes called Transitions) is covered by WinJS though, and you can find it in WinJS.UI.Animation. Here is a sample of what you can get there:

 

  • Page transition: Animates the contents of a page into or out of view.
  • Content transition: Animates one piece or set of content into or out of view.
  • Fade in/out: Shows transient elements or controls.
  • Crossfade: Refreshes a content area.
  • Expand/Collapse: Shows additional inline information.
  • Reposition: Moves an element into a new position.
  • Show/Hide popup: Displays contextual UI on top of the view.
  • Show/Hide edge UI: Slides edge-based UI into or out of view.
  • Show/Hide panel: Slides large edge-based panels into or out of view.
  • Add/Delete from list: Adds or deletes an item from a list.
  • Add/Delete from search list: Adds or deletes an item from a list when filtering search results.
  • Badge update: Updates a numerical badge.
  • Start/End a drag or drag-between: Gives visual feedback during a drag-and-drop operation.

 

That’s a lot of animating. Don’t feel like you have to animate everything to get into the store. I would, though, seriously consider animating page and content transitions in order to show that you have given a nod to the realities of the Metro design language.

 

Page level transitions

 

Compared to dealing with the GestureLibrary, page transitions are a snap. In WinJS.UI.Animation you will find an enterPage function, and an exitPage function. They both do about the same thing, they just need to be run at different times in the page lifecycle.

 

Both methods take an element object and an offset object, and return a Promise. While an element is in transition you can’t act on it, so you want to use the promise to delay any page functionality (like removing an element) until the animation is over.

 

WinJS.UI.Animation.enterPage(content, startingPosition).done();

 

The content is the element or elements that you are animating. This seems counterintuitive but I believe it is set up this way so that you can choose to animate only certain parts of the page, and still have content level control later. The enterPage function is designed to be used with the Navigation libraries we talked about in Saying Hello World.

 

The startingPosition is exactly what it looks like. It is where the content collection should start before the animation occurs. You can pick a place on the page and pass in a JavaScript array of the location to make this happen. The recommendation is, though, to use “undefined” for the default start location.

 

The done of course represents the Promise that is being returned by the function. When the animation is done, the rest of the code will be run, and not until the animations is done. This is to prevent the entire UI from locking up while an animation is being performed.

 

To set up an animated page sequence, try the following steps:

 

  • Create a blank JavaScript Metro project.
  • Make a new directory called “pages” for the pages we are going to transition amongst.
  • Add three pages. Right click on the pages directory and select Add New Item. Select Page Control. Do it three times. I named mine firstpage, nextpage and thepageafter.
  • In default.html, add a content div replacing the paragraph tag, like this:

 

<body>
    <div id="content"></div>
</body>

 

  • In the default.js file, add a navigated event handler.

 

WinJS.Navigation.addEventListener("navigated", function (eventObject) {
        var url = eventObject.detail.location;
        var content = document.getElementById("content");
        WinJS.Utilities.empty(content);
        eventObject.detail.setPromise(WinJS.UI.Pages.render(url, content, eventObject.detail.state).then(function () {
            WinJS.Application.sessionState.lastUrl = url;
        }));
    });

 

  • Also, navigate to the first content page in the onactivated event. This will get things started.

 

app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            args.setPromise(WinJS.UI.processAll().then(function(){
                return WinJS.Navigation.navigate("/pages/firstpage.html");
            }));
        }
    };

 

  • The firstpage.html, nextpage.html, and thepageafter.html give the header and main sections a ID. While you are in there, add a button for navigation.

 

<body>
    <div class="firstpage fragment">
        <header aria-label="Header content" role="banner" id="header">
            <button class="win-backbutton" aria-label="Back" disabled></button>
            <h1 class="titlearea win-type-ellipsis">
                <span class="pagetitle">Welcome to firstpage</span>
            </h1>
        </header>
        <section aria-label="Main content" role="main" id="main">
            <p>Content goes here.</p>
            <button id="nextPage">Next Page</button>
        </section>
    </div>
</body>

 

Add a transition function to firstpage.js, nextpage.js and thepageafter.js that navigates to the shosen page and uses the animation.

 

function transition() {
        WinJS.UI.Animation.exitPage([[header],[main]], null).done(
            function () {
                WinJS.Navigation.navigate("/pages/nextpage.html");
            });
    }

 

This will be different for each page! It should navigate to the page you want to go next.

 

  • Finally, in the firstpage.js (and the others) and change the ready event to fire the new transition function when the click event occurs.

 

WinJS.UI.Pages.define("/pages/firstpage.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            var nextPage = document.getElementById("nextPage");
            nextPage.addEventListener("click", transition, false);
            WinJS.UI.Animation.enterPage([[header],[main]], null);
        }
    });

I wish I had a pretty picture of this to show you, but wiley STILL hasn’t implemented those animated pages. If you can’t get it to work, download the sample code and give that a try. There is also a fantastic sample (if a little overcomplicated) on the dev.windows.com samples site.

 

Animating content

 

Good news! Animating content is almost excactly the same as animating entire pages. The Animation library has enterContent and exitContent functions that work a lot like enterPage and exitPage.

 

WinJS.UI.Animation.enterContent(content, startingPosition).done()

 

The content object is an HTML element (the ID of said object) that you want to animate. The startingPosition is best set to null unless you have a specific starting position. And the Promise returned is just to make sure that you don’t do anything with the entity until the animation is through.

 

I’ll spare you the steplist – it looks a lot like the Animating Pages example above. Just put the enterContent in the load function, and the exitContent in the navigation event.

 

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);
    });

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.

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

MonthList