31 Days of Windows 8 | Day #31: Design

This article is Day #31 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.

advertisementsample

Today is the last day of this series, and we’re going to focus on designing Windows 8 applications today.  You might be asking yourself:

I’m a developer…why would I want to read an article about design?

I’ll tell you why.  Because we developers have been making user interfaces that look like this for decades:

 

The point of this article is to get you to think differently about you user interface, not just the colors and shapes that are user, but the ENTIRE EXPERIENCE.  The way pages show content.  The navigation experience.  Even page transitions.  It all matters now. Here’s more proof, if you need it.  Think, for a moment, about what an app running in Windows 7 looks like.  Any app.  Picture it in your mind.  It probably looks like this:

31-XAML-Win7

If you take a closer look at this diagram, there’s no indication whatsoever about what this app does.  We’ve tended to focus on how we use the app, not what the content is.  Windows 8 fundamentally shifts that idea.  Now think about a Windows 8 application in your mind.  It probably looks more like this:

31-XAML-Win8

In this illustration, the ENTIRE image shows content.  This means that instead of remembering how to use your app, users are far more focused on the content of your app.  This is part of the conversation we’re going to have today.  This article will be divided into several sections, and each section talks about a different part of user interface creation.  Here’s the topics we’ll cover:

  • Content Before Chrome
  • Using The Windows 8 Silhouette
  • Navigation Patterns
  • Fluid Motion
  • Make Touch a Priority

That’s a ton of topics, so let’s get right to it.

Content Before Chrome

In this section, I want to focus on one of the most important lessons in this entire article:

STOP MAKING BUTTONS.

The focus of every screen of your application should be about the content.  If you’re adding buttons, you’re likely doing it wrong.  Here’s a very common scenario:

31-XAML-WithButtons

We have several sections to our application, and we want to provide an interface for our users to get to each section.  In general, most people would say that there’s absolutely nothing wrong with this interface (except that maybe those giant gray boxes should have photos in them.)  The key lesson to remember is that the entire colored block IS the button.  There’s no reason to add the circled arrow icons.  Instead, consider this:

31-XAML-WithoutButtons

By removing the circled arrows, we’ve made the interface cleaner by removing the clutter, we’ve provided the user with a larger touch target for their fingers on touch devices, and given ourselves less to worry about on the page.  “One button to rule them all”,” if you will.

When you desperately feel the need to add a button to the screen, ask yourself:

Could this live in an application bar?

If it can, do it.  For more on the application bar, check out Day #4.  In short, let the user tap the content instead of creating another button for them to click.  If an action can be taken on more than one item at a time, use the App Bar to provide contextual actions when multiple items are selected.

Using the Windows 8 Silhouette

It would be a dreary, boring world if every app looked exactly the same.  That considered, it is also difficult for users to learn a new interface with every application that they use.  This is where the idea of a silhouette comes into play.  Take a look at the four different application examples below.  They all present very different content in very different ways, but there’s a uniform experience about them that makes it very obvious to the user where the important content lives.

31-XAML-Silhouette

There are many ways to utilize this familiar silhouette, here are just a few examples:

31-XAML-Silhouette1

31-XAML-Silhouette2

31-XAML-Silhouette3

31-XAML-Silhouette4

All of the previous images follow a familiar format, which makes it easy for the user to figure out how to use your application, while still looking diverse enough to make your app visually unique.  The reason for all of this is because there will be learned behaviors your users will acquire simply from using Windows 8.  They’ll start to rely on the Charms bar.  They’ll start to expect that right-clicking brings up an AppBar with more options.  They’ll try pinching the screen to zoom.  Taking advantage of these silhouettes is another example of the expectations users will have about your application.

Navigation Patterns

As developers, we have a tendency to try to accommodate our users’ needs, almost to a fault.  One example of this that is rampant in both desktop applications as well as the web is this idea:

We need to allow the user to get TO any page, FROM any page.

You do NOT need to do this.  When we provide this type of functionality, we limit the amount of space that can actually be used for the purpose of the app.  Here’s an example of an RSS reader app that practices the “everywhere navigation” pattern (click to enlarge).

31-XAML-RSS

As you can see, an app that is dedicated to reading only uses about 30% of the screen for actual content.  We need to think about our application in a navigational scheme that makes sense for our content, which will almost always be hierarchical or flat.

Hierarchical Navigation

In this style of navigation, we work in a hub-and-spokes model, where the users’ choices move them further and futher from the home page, and using the back button allows them to return backwards through their path before choosing another branch of the tree to travel down.  Like this: 31-XAML-Hierarchical

We build pages with a master/detail structure so that navigation is intuitive and simple to use.  The user should always know where they are in the app, without having to lay an elaborate trail of breadcrumbs for them.  They should be diving into deeper and deeper detail about the original choice they made.  The default News application in Windows 8 is a great example of this hierarchy.

On the home page of the app, I can scroll to the right to see a few articles from each section (Entertainment and Sports are currently shown):

31-XAML-News1

Using Semantic Zoom, the user can easily see all of the categories, and jump to the one they want to read more about.

31-XAML-News2

If I tap on one of the section headers on the main page (like the word Entertainment above the large photo of the woman, Lynn Shelton), I am taken to a new page that contains only Entertainment news.

31-XAML-News3

Finally, and this can be done from anywhere in the app that I see an article, when I tap on a specific article, I am taken to a detail page for that item.

31-XAML-News4

In each instance, there is the presence of a back button which will take me back through my previous choices.  What you don’t see, however, is the ability to jump from an Entertainment news article over to a Sports article.  In fact, there’s not even a way to get to the Sports category without using the back button.  That is, until you take a look at the AppBar for this app.

31-XAML-News5

There, you’ll see that they succumbed to the need to let the user navigate quickly between sections without cluttering up the screen with all of this navigation.  The AppBar is a great way to provide some of these navigation mechanisms without taking away from the visual appearance of your application.

This is a hierarchical navigation pattern.  Learn to use it.  It will be your friend, and clear your screen of all of the navigation elements you would need otherwise.

Flat Navigation

Flat navigation is something that you see every day in your web browser.  You also see it in instant messaging apps, and other places that have similarly formatted, but somewhat unrelated content.  A picture would look like this:

31-XAML-Flat

When we navigate a website, we’re using this flat navigation style.  We can move forwards and backwards, but there is really no concept of branches in this format.  Since you’re likely using a web browser to view this article, I’m going to assume you know what I’m talking about.

Fluid Motion

Motion is one of those things that we never think about as developers.  We tend to focus on the important topics, like data, and never really consider how much nicer our app would look if it incorporated a little animation.

When I talk about animation, however, I’m not talking about it for visual adornment.  It’s not a decoration that you slap on your page.  Animation should be purposeful.  If you can use animation to transition between screens of your app, your user will perceive load times to be shorter, and feel that your app is faster and more responsive than it actually is.

In addition, there are a bunch of animations available to you with minimal effort.  Check out this article on Animating Your UI from MSDN.

Make Touch A Priority

A “tap” and a “click” in Windows 8 are the same thing.  It requires no effort on your part to make touch happen.  Making your click targets big enough for a finger, however, does.  Always, always, always make anything on your page that is clickable larger than 48 x 48 pixels.

Incorporate gestures where possible.  Your users will expect them.  It requires minimal extra effort, and it lets your users interact with your app the way they expect to:

31-XAML-Touch

In addition, it’s important to remember that because your users will be touching the screen, this also means that there are optimal places to put your buttons and content.  Generally, a user will hold a tablet horizontally, with their thumbs hovering over the two sides of the tablet.  This means your primary buttons should probably live in these regions as well.  What shouldn’t live there is your content.  If the user’s thumbs are hovering over this region of the screen, this also means they can’t see what is happening on that region of the screen.  Here’s a good rule of thumb:

 31-XAML-Occlusion

Summary

In this article, we covered some of the important things you should be thinking about when you start building, and more specifically designing, your Windows 8 applications.  There are tons of additional resources at

http://design.windows.com

and you should definitely make a trip over to the site to check them out.  There are additional design patterns, UX guidelines, Adobe Photoshop templates and much more.

This article also puts the finishing touches on this lengthy series, and we want to sincerely thank each of you that have taken the time to read our words.  There are many reasons to write an article series like this, but our primary reason is that it’s an amazing excuse to dive deep into a technology stack and really understand it.  My second reason, however, is you, the reader.  Jeff and I have made our best effort to understand each of these topics thoroughly, and explain them in a “no assumptions, start from the beginning” manner.  You, our readers, bring us comments and questions that we hadn’t anticipated, and for that, we truly are thankful.

Please leave comments and questions on our articles.  These will continue to live on as excellent learning resources for developers looking to build Windows 8 apps, and your contributions only make them that much better.

Thanks.

Posted in 31 Days, Windows 8 | Tagged , | 1 Comment

31 Days of Windows 8 | Day #30: Store

This article is Day #30 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.WindowsStore

Wow, here we are finally talking about the Store. This is really our last step ( and a very exciting one no less ) in your development process. Today we’re going to share with you some of our steps and experience in not only helping others get their apps into the store, but also submitting our own.

If you’ve gotten to this point, then no doubt, these are exciting times. Whether you’re a few code slingers at Rovio making Angry Birds or someone like me who was building an app on the nights and weekends, it’s exciting. If you’ve have an app in the Store, I would also invite you to share in the comments the things that have worked well for you, and not so well.

Microsoft announced just a few short days ago, that they’ve sold 40 million licenses of Windows 8 in it’s first month of life. I don’t know about you, but that’s a pretty big audience for some indie developer like me. The Store is our new platform for us to ship our software to.

For purposes of today, we are only going to talk about the public facing Microsoft Store. If you feel you fall outside of that scenario, say you’re an enterprise developer and might like to deploy through group policy, I would suggest start by reading the Managing Client Access to the Windows Store.

To the Store

Now to get in the store, you have to have to first be signed up as a individual developer ($49 USD) or a company ($99 USD). Once signed up, you can then start reserving app names. Now I know this might sound a bit like duh, of course, but maybe you already have an idea but just haven’t started it. Nothing is stopping you from creating your account and reserving those application names now. Now unlike all of those domain names you’ve been buying over the years and just parking until you get time, you have 1 year from the time of reservation to shipping. If you don’t release anything, then that reserved name goes back into the pool. As someone who has a few apps reserved, it’s a pretty good incentive program for me.

Pre-Certification

If for some reason you’re new to this notion of a “store” or “marketplace” concept, as developers once we finish our app we have to go through a certification process before our application will be officially published. While this may seem somewhat cumbersome, this certification process is really there for everyone’s benefit. Having been through it, the first time you submit your app the minutes can feel like hours but in the end it’s the right thing.

Of course the certification process is both automated and manual. For the Microsoft Store you as the developer have access to the same automated tools (WACK) which are used once you’ve submitted to the store. This allows you to go through the process before you’ve ever submitted addressing any potential issues.

The Windows App Certification Kit or WACK is really two different kits; one kit for Intel based processors and another one for ARM based processors. These kits are tools that you would of course install on a test system which will run through the same automated process that the Microsoft Store would do from it’s servers. The beauty about these kits you can run them on yourself before you ever submit your application to the marketplace. As I said this really helps to ensure you’ve cut down any issues long before submitting to the store, ultimately cutting down your certification time if you we’re to have any issues.

After starting the Windows App Certification Kit you have 3 different categories of apps that you can select. For our apps we would select the validate Windows Store App option. Once selected, you’ll be asked as to what application you want to validate.

SNAGHTML2a9a1b2d

Once you pick out your application, the WACK tool will start running. It will start to run a variety of tests against your application and even do things like open it, to see how long wait times are. After it’s completed, you will get a detailed report as to what was validated. Of course just like in TDD, green is good and red is bad. Below is just a snip from a failed event report.

image

The WACK tool provides a very detailed report as to its findings. Having said you should run it across all of the platforms you expect to run on, as your load times on a low power ARM device might be a lot longer than that of a multicore Intel machine. It’s also not a replacement for hard core testing, both manual and automated. Just saying…

It’s also true, when you submit there is still a potential for failing the certification. Now Microsoft has released a pretty good document which details a number of the most common certification failures but make sure you have read through the certification requirements such that you’re not surprised.

One of the biggest reason apps fail is certification requirement 4.1. 4.1 states that an app with the Internet Access capability checked must provide a policy policy to the Store. Of course this means you might have to setup a simple website just to contain the privacy policy required. If you’re not using the internet, just uncheck it.

TIP

All of the Visual Studio templates for the Windows Store create the shell of an app but with the internet capability.enabled. If you’re *not* using the internet – uncheck it and save yourself the hassle.

App Images

Like it or not, the first thing your potential customer will see is an image of your application  in the store. In fact, there are a number of different images your user might see depending on where the store app has placed your application.image Now mind you, this is all before your potential customer has even installed it, so make sure you have some great store appeal is a good thing.

During day 1 when we talked about the blank application, we discussed a number of different images you needed to include in your application. These were things like the store logo, small tile, wide tile and so on.

As it turns out, when you try and submit your application, you’re not done with the image creation process. At the time of submission you will be asked for a number of new logos that will be used by the store specifically. They are not part of your app’s package, they are images uploaded directly to the store. Specifically these images are your billboard images as well as screenshots of your application.

Making logos is clearly an art form. To help make things a bit easier, a friend of mine build a number of Photoshop templates around these Store submission graphics. I would encourage you to check them out as they could save you a number of hours.

Whatever you do, please, please, PLEASE replace all of the default images. Now I do not know who wrote Backgammon Gold nor am I not trying to place a dig on all the hard work they’ve done. But, I would never spend $4.99 on something where someone hasn’t even taken the time to replace the default Visual Studio images. I’m not saying, but I’m saying. Clearly their rating proves my point.

image

Making Money

Your monetization model is clearly something that only you can determine. While charging outright for the application is one way, there are many creative ways as well. The minimum price someone can charge for an application is $1.49 USD with increments starting at .50 USD.

While charging upfront is a clearly an easy way to make some coin, it’s not the only and it might not be the best depending on your scenario. What about offering the user a time-limited trial, or a feature-limited trial? Remember the goal is to make money and getting user to test drive your app isn’t a bad thing. There are a number of studies written about how trials have a much higher conversion rate that ones without trials. You don’t buy a car without driving it first, why not test drive an app?

Another very popular mechanism for making money is an ad supported model. This is nothing more than putting some ad container in your applications such that you’re displaying ads to your customers. While you can use any ad platform you wish (assuming they adhere to Microsoft’s certification requirements ) Microsoft offers an ad sdk from Microsoft Advertising which will get you easily up and running on Microsoft’s platform.

Lastly offering the ability for an in app purchase shouldn’t be out of your reach either. Using a game app example, one could offer more levels once the user got to a particular point in their journey just for a bit more money. I personally think this is a pretty interesting scenario as it gives you the ability to get people using your app, but offers them the ability to purchase something more full featured.

Now when you’re making most of the money, the Microsoft Store is doing all of this legwork for you, hosting the bits, transitions, currency conversions etc.  As you might expect there is a cut that Microsoft needs to take just to offer such support. For your first $25k Microsoft will charge you a 30% fee, but after your app makes $25k, that fee will drop to 20%. These are just a few of the items you will find in the app developer agreement.

Creating the package(s)

Creating the packages for the store is a painless process. There is basically two reasons to create a package, sideloading or WACK testing OR to upload to the store. The difference between the two different packages is really one is signed with your developer account whereas the other isn’t.

To get started, Project –> Store –> Create App Packages… As you can see, the first dialog box you’re presented with is in fact the two different options we just mentioned.

SNAGHTML1006b5c3

If we’re building a package for the Store. Then our next step is to select what our app name was in the store such that we can associate things correctly.

image

Regardless of what direction we choose first the next step in the process is picking what platform we want to build for. These will be the packages we will later either sideload or upload to the store.

SNAGHTML100afd09

And once created all of your glory should look something like:

image

For more information about sideloading please see this article: http://technet.microsoft.com/en-us/library/hh852635.aspx

Ready to submit

Submitting your application is mostly just a one page web form you’re required to fill out. These are things like, description, search keywords, release date and so on. The Windows Store team has done an excellent job of documenting everything, so I won’t rehash that here but rather ask you to please read their article.

App Update(s)

You’ve pushed and now you need to fix up a bug. Well, thankfully you’ve already been through the entire process already. Now it’s just a matter of creating a new release and changing anything that might be now applicable. Oh yea, of course you would need to update the new package too.

Summary

Honestly submitting your app into the store is the easy part. All of the planning and development that’s been done to this point has really been the hard part. While you have a plan in mind about how you may make money, don’t be afraid to think outside of the box and try a few different things. You never know what will net you the best results.

Tomorrow, we’re going to talk about our last day in this series which is focused on design.

downloadTheTools

Posted in Uncategorized | Tagged | Leave a comment

31 Days of Windows 8 | Day #29: PLM

This article is Day #29 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.ProcessLifecycleManagement

After 29 days, we’re finally going to talk about the Application Lifecycle or Process Lifecycle management ( aka PLM ). Now before you close the browser thinking I will just skip this one, please don’t. We’re going to talk about how your application will run, when it runs, and what events are there for us to plug into. Ultimately we’re looking at the management of the different states our application can be in on a user’s device.  Here’s an illustration (image from MSDN):

29XAMLLifecycleDiagram_thumb1

As web developers this process lifecycle thing might feel a bit foreign to us. Of course our web applications and\or sites have a lifecycle but our word is a pretty stateless world. Now having said that, we’ve always had to deal with bouncing between servers, network volatility and overall session management. The same principals are somewhat true in our native app. Windows makes the call as to when we should live, and we should be ready for that.

The reason that this is important to us as developers of Windows 8 applications is because we want to provide a seamless user experience in our apps.  When a user presses the Windows key on their machine, and leaves your app, you want to make sure you save or preserve their data in some way, so that when they come back, it’s all still there.

I Thought Windows Handled This Automatically??

Yes and no.  By default, if you run a Windows 8 application, leave it, and come back, it will automatically be exactly where you left it.  However, if you leave it, and then open 6 or 7 more applications, it’s likely that the operating system is going to suspend your application, or even terminate it.  Thankfully, there’s a couple of great mechanisms we can use to manage this.

Recognizing Your App Has Been Suspended

According to Microsoft, “an app can be suspended when the user switches away from it, *or* when Windows enters a low power state.  Most app stop running when the user switches away from them.”  There’s a few things you need to know about how your app will end up in a suspended state:

  • Your app “might” be suspended.  For the simple app I’ve built for this article, I’ve never seen it enter a suspended state on its own.
  • Generally, when the system runs out of resources, this is the time your app will enter a suspended state.
  • When you leave an app to use another, Windows will wait a few seconds before suspending it, just in case you were planning to return to it quickly.

So, if you’re anything like me, you’re probably wondering how we are going to write and test some code that only occurs when Windows feels like making it happen. Thankfully, there’s some tools for that.

Now to talk about this whole lifecycle thing, I’m purposefully going through things somewhat backwards, this will make more sense when we turn to talking about what happens when our application launches. Most likely you’d started your application development from one of the Visual Studio templates. Assuming so, then will see a bunch of boilerplate code in your default.js file. This boilerplate code is basically some of the simple hooks for PLM as well as getting your app started up.

Before our application transitions into another state and event called oncheckpoint will get called. This *an* opportunity ( not the only one, you can always save too ) for you to do something like possibly save the users session state or something like their navigation history

app.oncheckpoint = function (args) {
    args.setPromise(finishOff());
};

function finishOff() {
    return new WinJS.Promise(function (complete, cancel, progress) {
        WinJS.log && WinJS.log("app.oncheckpoint called.", "31 days", "status");
        complete();
    });
}

Looking at the code above, you can see I we have created a function that will in turn get executed when the checkpoint event is fired. In our code we are  creating a promise that will in turn tell Windows there is some async activity occurring and things shouldn’t end until complete has been called. Having said that, Windows isn’t going to wait around forever either. Windows will wait a few seconds ( 5 seconds I believe ) before it says, “sorry dude, I am outty you’re just taking to long”.

In WinJS there is an object called sessionState. This sessionState object is a great place for you to keep some of your users session data like navigation history ( as the Navigation template in fact already does ). The beauty of this sessionState object is Windows will in fact manage the persistence and recreation of that object and its associated data. While less work for us, we will still have to take the data from that object and re-create our own objects if necessary.

Checkpoint is called when you application is going to be suspended. If  you app is suspended there are no more notifications that you’ll receive, so this is the place to take care of business while you still have a chance.

Recognizing That Your App Is Resuming

In this case, we’re going to simply add an event handler that will execute when the resuming event is fired.

var webUI = Windows.UI.WebUI.WebUIApplication;

webUI.addEventListener("resuming", onResume, false);

function onResume() {
    WinJS.log && WinJS.log("app resuming", "31 days", "status");
}

On Launch

This is where things can get a bit more complicated. In the code below, I have listed out all of the different execution states and I am logging that to the console window. Just like we did with the blank app on day one, this gives us some history as to when these things will get fired and whatnot. This is our place where we can do things like reconstitute objects depending on the state the applications was in before ( if we care of course ).

var app = WinJS.Application;

app.onactivated = function (args) {
    WinJS.log && WinJS.log("app.onactivated", "31 days", "status");

    if (args.detail.kind === activation.ActivationKind.launch) {
        WinJS.log && WinJS.log("Activation Kind === Launch.", "31 days", "status");

        switch (args.detail.previousExecutionState) {

            case activation.ApplicationExecutionState.terminated:
                WinJS.log && WinJS.log("previousExecutionState terminated", "31 days", "status");
                break;

            case activation.ApplicationExecutionState.running:
                WinJS.log && WinJS.log("previousExecutionState running", "31 days", "status");
                break;

            case activation.ApplicationExecutionState.suspended:
                WinJS.log && WinJS.log("previousExecutionState suspended", "31 days", "status");
                break;

            case activation.ApplicationExecutionState.closedByUser:
                WinJS.log && WinJS.log("previousExecutionState closedByUser", "31 days", "status");
                break;

            case activation.ApplicationExecutionState.notRunning:
                WinJS.log && WinJS.log("previousExecutionState notRunning", "31 days", "status");
                break;
        }

        args.setPromise(WinJS.UI.processAll());
    }
};

To look at a concrete example of this. We can look no further than the Navigation App template found inside of Visual Studio. Here we will see no only are we saving our navigation history on checkpoint to the sessionState object but when our application launches we are making sure we 1. reconstitute it as well as navigate them back to the place they had left off.

app.addEventListener("activated", function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
        if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
        } else {
        }

        if (app.sessionState.history) {
            nav.history = app.sessionState.history;
        }
        args.setPromise(WinJS.UI.processAll().then(function () {
            if (nav.location) {
                nav.history.current.initialPlaceholder = true;
                return nav.navigate(nav.location, nav.state);
            } else {
                return nav.navigate(Application.navigator.home);
            }
        }));
    }
});

app.oncheckpoint = function (args) {
    app.sessionState.history = nav.history;
};

Now how in the world do I test this PLM stuff?

Because this is a tough scenario to make happen automatically, there are tools inside Visual Studio that allow us to simulate these states in our application.  First, make sure that you’ve opened the Debug Location toolbar in Visual Studio.

29-XAML-DebugLocation

Once you’ve added that toolbar, it’s as simple as choosing one of these three options:

29-XAML-Suspend

  • Suspendwill immediately put your application in a suspended state.  This will also fire your suspended event handler before it stops running.
  • Resumewill obviously resume your app from a suspended state.  If your app is not suspended, nothing will happen.
  • Suspend and shutdown will simulate what happens when Windows terminates your application.  The suspended state will happen first, followed by a complete shutdown of your app.

Summary

In short, we want to provide a seamless experience for our users, so keep the lessons in this article in mind.  Don’t overdo it, though.  Saving unsaved data for a user is a convenience, so unless you think it will be important, don’t exhaust yourself trying to anticipate everything the user might need. Also be mindful of performance, I don’t think we want to persist to disk ever single time a character changes in a textbox.

In games, if the user leaves, and they have to replay a level, so be it.  You don’t have to remember that they were jumping over that block to make it a great experience.  Remember which level they were on is probably enough.

If you’d like to download my working sample that uses the code from this article, click the icon below:

downloadHTML

Tomorrow, it’s time to ship your awesome to the store.  See you then!

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , | Leave a comment

31 Days of Windows 8 | Day #28: Push Notifications

This article is Day #28 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.PushNotifications

Today we’re going to dive pretty deep into the world of Push Notifications. In short, push notifications is a mechanism for some external thing to send a notification to the user in a variety of different forms. Now, this isn’t anything new to us. On Day 9 we introduced Live Tiles, Day 10 – Toast Notifications and Day 11 Lock Screen Applications. These were all methods in which we could notify the user and allow them to take action if they so desired. When we explored each of these methods we we’re sending notification from within our application or some background process. Push notifications is really the last piece in that notification puzzle and maybe one we should have ordered a bit different in our series. Hindsight is always 20/20 right?

Before we dive into Push Notifications I want to set the stage a bit. I am going to assume a web like connected scenario. I am going to create a simple website. This website will be the thing that we ultimately send notifications to our apps on the different clients. The server will determine Who, What, When will get those notifications. Of course for demonstration purposes we’re going to cut out some of that “business logic” such that we can just exercise the ole internet pipes. At a 50k foot level this all looks something like this:

image

What is?

Now, what really is Push Notifications? Well Push Notifications is really some cloud infrastructure to manage and facilitate the sending of notification for applications who subscribed to receive them. These notification can be a tile, toast, badge and raw notifications ( any or or all of them ). They are actually determined from the server and then sent through to the WNS server which will then send it along to the appropriate client. The notification work the same way as we saw in our previous articles but are just sent from a outside source, such as the little website we will build.

These notifications are managed through what is called the Windows Push Notification Services or WNS. This is the piece of cloud architecture that resides in the middle of everything. The WNS server is the thing in which our client and server interact with to send and receive notifications. Having said that our client *will still have* to send its endpoint to the website, such that it knows who would like to receive a notification.

The basic steps are such:

  • Before we can do anything we need to be registered with the store. This will gives us our keys such that we can authenticate with the WNS server.
  • Our app needs to register a channel with the WNS server. The result of a successful registration is a URI. It will look something like:
    • https://bn1.notify.windows.com/?token=AgYAAAAe%2buFwf2o%2fz1nJdCAMwzf4bO9u3QXmrW4L73WAPNpsP8DpbfSmHIuRpoOIJKusNKxTvkXo4tposjhTPkbLNnsvXXzCh8eIMpyTPXOFNStcZ0FR7kQZHf86MwL4Ga5f7vg%3d
  • Once we have the URI we need to give it to our cloud service so it knows which clients want communication
  • Our cloud service ( in our case our website ) will have to have some knowledge about our secret WNS keys. These keys are what our site will use to authenticate to the WNS server. Once authenticated it can then post notification to that URI the client gave him.

Push notification registration, authentication, and data flow

Image curiosity of MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/hh913756.aspx. For more information on the Push Notifications process, please see the Push Notification Overview on MSDN.

The Setup

To start, we need to get our app registered. Now at the time of writing this there seems used to be two different methods.

Now the Windows Store is the official way that you will want to register your application. The Windows team has put together a nice set of documentation on how to get registered so I won’t rehash that here. Just check out the article How to authenticate with the Windows Push Notification Service (WNS). The first part of the article walks through in great detail just how to register your application in the store and so forth.

The Live Connect Developer Center used to be a place where you could also register an application and get all all of the goods but that seems to have recently changed. I tell you this because there are a number of blog posts out there with outdated information ( as one day this will be too ). Yes, you can still create an application there but you will be missing some essential pieces of information ( like the SID ) needed to do the proper authentication. Having said all this, any application you create in the Windows Store will appear listed here and with some of that information.

Why do we need to register anything to do Push Notifications? Security. This registration process does two things for us. 1. It will identify our application to not only the Store so we can submit our wonderful app but also identify itself to the WNS servers correctly. 2. Provides us an  identity to use outside our of our application ( aka server side ) which can authenticate via OAuth with our WNS servers, this is our SID and the Secret. If your secret was to ever get compromised, you can always regenerate it from either the Store ( which really takes you to Live ) or the Live Connect Developer Center. Below the top image is our results from the Store while the bottom image is the Live Connect portal page.

image

image

Ok, now you have your app registered in the store, the next thing to do is associate the solution with the Store. What that really means is changing all of that great information that we haven’t talked about in the Packaging tab of our appxmanifest. But rather than just entering it all by hand we can just go to Project –> Store –> Associate App with the Store. This will do all the nasty for us.

SNAGHTML1b308bd9

- tip -

One thing that has caught me once or twice, was the generation of our certificate. Every application has a unique certificate associated with it. When you create a new blank template Visual Studio will actually create a temporary certificate for you, something like App29_TemporaryKey.pfx. This certificate will be associated to your app in the packaging tab of the appxmanifest file. Now when you associate your app with the store, not only will it update that Packaging tab with new information but you should *also* get a new certificate that will be associated with the store.

Now I have personally seen this not happen and no matter how many times I tried to associate my application, I couldn’t seem to get the Store certificate.  As it turns out there was an easy fix. Make sure you somehow didn’t mess up your own temporary certificate. If you’re actually missing your pfx file ( say you deleted it or excluded it from source control ) you can recreate a temporary one from that Packaging tab in the appxmanifest. Once you have your certificate correctly associated, then re-associate with the store and you should in fact get your official key.

The Client

Now that our app is registered, and we have the keys ( SID and Secret ) to our castle, the first thing our application will need to do is register a channel with the WNS server. Our application *has* to be the thing that will tells the WNS servers that we in fact want notifications. In return our WNS server will tell our application what our actual Push Notification URI will be. Once we have that endpoint we can pass it along to our cloud services such that we can start receiving notifications.

Ironically, the client part is the easy part. The only thing we need to do in our application is register ourselves with the WNS server and pass along our URI. As we saw from our conversations on tile, toast, badge notifications we really didn’t have any work to do to receive notifications. Meaning we didn’t need to setup OS level events to catch and pop dialog boxes, unlike our devices conversation where we did ( at least have to register ourselves ).

When our application launches, we can register ourselves with the WNS servers.

var notify = Windows.UI.Notifications;
var push = Windows.Networking.PushNotifications;
var net = Windows.Networking.Connectivity;

notify.TileUpdateManager.createTileUpdaterForApplication().clear();
notify.BadgeUpdateManager.createBadgeUpdaterForApplication().clear();

var profile = net.NetworkInformation.getInternetConnectionProfile();

if (profile.getNetworkConnectivityLevel() === net.NetworkConnectivityLevel.internetAccess) {
    push.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync()
        .then(function (channel) {
            document.querySelector("#uri").innerText = channel.uri;

            /* 
            this would be the place to post your uri to your cloud service.
            */
        })
}

Above, I am just clearing all notifications ( it’s a demo after all ), then I will check for internet access. If so, we can then register for Push Notifications and pass along our URI. In our case I am just going to put the URI on the screen for us to see.

- another tip -

Internet Access. By default, the Visual Studio template has the Internet Access Capability already checked. This is in fact a capability we need for Push Notifications, so no immediate work is required by us.

Having said that, if we have Internet Access Checked then when we try to publish our app to the store we will also be required to provide a privacy policy. See section 4.1.1 for more information. Without that you will be rejected.

You’ve been warned.

The Server

Our server is where all the magic will happen. To send a notification it really just takes a few simple steps. Authenticate with the WNS servers, create your notifications and then send them along. Since we’ve already covered how to create tile, toast, and badge notifications I will not cover that but rather I would like to introduce a library which will make all of this pretty dead simple. It’s called WNS Recipe. While I could walk you through the OAuth Authentication process with the WNS servers, why?

WNS Recipe, makes all of this very simple. As a fun little experiment, I created a simple webpage on 31 Days to test Push Notifications. you plug in your information and it will send you a tile and toast notification. Sure I could go a lot further but for now, it will at least test the pipes. Below is the majority of that code.

var sid = Request["sid"];
var secret = Request["secret"];
var uri = Request["uri"];
var message = Request["message"];

WnsAccessTokenProvider tokenProvider = new WnsAccessTokenProvider(sid, secret);

var title = "31 Days";
var subText = message;

var tileNotification = TileContentFactory.CreateTileWideText01();

tileNotification.RequireSquareContent = false;
                        
tileNotification.TextHeading.Text = "31 days";
tileNotification.TextBody1.Text = message;
    
var tileResult = tileNotification.Send(new Uri(uri), tokenProvider).ErrorDescription;

if (!string.IsNullOrEmpty(tileResult) ){
    <h1>tile result: @tileResult</h1>
}

var toastNotification = ToastContentFactory.CreateToastText02();
toastNotification.TextHeading.Text = "31 Days";
toastNotification.TextBodyWrap.Text = message;

var toastResult = toastNotification.Send(new Uri(uri), tokenProvider ).ErrorDescription;
            
if (!string.IsNullOrEmpty(toastResult) ){
    <h1>toast result: @toastResult</h1>
}

The first major step is creating an instance of what is called the token provider. To create it, we need that SID and Secret that we received when we registered our application. They will look something like this:

Once we have our token provider in place, then we just need to create the notifications we would like to send. WNS Recipe makes this easy, as it’s wrapped all of the types of notifications in some nice factories. If you remember there are a number of different templates for each category of notification. WNS Recipe makes dealing with those templates a breeze.

Then when we’re ready to send, we just send to that URI our app gave us, using our token.

Sounds t0 easy

Sounds to easy Clark, I call BS. Ok, well, maybe you got me. Push Notifications is actually really easy. Here is what can be a pain.  Managing those URIs the hundreds of millions of customers will be sending you.

Yes, your services in the cloud will need to have some endpoint that your app can post it’s URI to. Then it will need to manage if that URI has expired ( yes they can change and expire ), who do you send to and when, and so forth. So yes, sending the notification is easy. Just how you leverage them is a different story.

But wait, there is more. Today I talked through the raw details of sending Push Notifications. At the time of writing this Microsoft has recently released something called Azure Mobile Services. Azure Mobile Services is a great utility for application developers. Azure Mobile Services will actually setup and host a great deal of this plumbing that I just mentioned. Now Jeff spent his day 28 working through that approach. This is something I would highly suggest taking a read through as well.

Hopefully between the two of us, you have a more than complete picture on how you can leverage Push Notification in your application.

Summary

Push Notifications is very cool. There have been some recent studies done where applications are claiming push notification driving over 60% of interaction with its application. Regardless, having a facility to entice the users to come back is always a good thing.

If you’d like to download my working sample that uses the code from this article, click the icon below:

 downloadHTML

Tomorrow, we’re finally going to talk about Process Lifecycle Management.  See you then!

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , , , , , | Leave a comment

31 Days of Windows 8 | Day #27: Inclinometer

This article is Day #27 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.logo

As someone who’s never written a game, or even an app which required such physics like heuristics, it’s become clear to me that getting the data from the sensor is really the easy part. I think it’s also pretty clear that no one sensor might ever be used alone but rather in partnership with the others. All of the devices really complement each other in someway and depending on what you’re building, while simple to work with they are essential to the overall experience you’re trying to create for your customer.

Today, finishes off our series of device sensor conversations that you might find in your new Windows 8 device. Today we’re going to take a very brief look at a device called the inclinometer. So what really is the inclinometer? Well, chances are you’ve probably been taken somewhere in a plane. When a plane turns, it actually exhibits all three axis to accomplish it’s turn. To make the plane turn in a nice smooth manor, we have three simple steps ( at least for the pilot that is ):

  • Pitch the plan in the direction of travel, by adjusting the aileron’s ( assumed in opposite directions to pitch the plane ). This is our Y axis or the Pitch.
  • Adjust the elevator either up ( or down ). This helps pull the nose of the plane up ( or down ) helping to point the noise in the direction of the desired turn. This is our X axis or the Roll.
  • Adjust the rudder. With the rudder we can make the play turn side to side. If you have ever landed in a windy situation and the plan felt sideways, it’s because it was, and they we’re using the rudder to cock the rear of the plan sideways. This is our Z axis or the Yaw.

Yaw, pitch, and roll as applied to an aircraft in flight

Image courtesy of MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/jj155767.aspx

While the physical example is nice, how does that translate to our computers in hand?

Inclinometer data showing degrees of rotation for yaw (z-axis), pitch (x-asix), and roll (y-axis) on a tablet PC

Image courtesy of MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/jj155767.aspx

As you can guess, working with the inclinometer is just like working with our other sensors.  Just a few simple steps and we’re getting data:

  • Initialize the Sensor.
  • If it’s available,
    • create a readingchanged event handler.
    • In the event handlers, grab the data from the sensor and write it to the screen.

Here’s my the entirety of my code and it looks well super duper scary similar to that of the other sensors.

    var _pitch, _yaw, _roll, _timestamp;

    function onReadingChanged(e) {
        _pitch.innerText = e.reading.pitchDegrees.toFixed(2);
        _yaw.innerText = e.reading.yawDegrees.toFixed(2);
        _roll.innerText = e.reading.rollDegrees.toFixed(2);
        _timestamp.innerText = e.reading.timestamp;
    }

    function getDomElements() {
        _pitch = document.querySelector("#pitch");
        _yaw = document.querySelector("#yaw");
        _roll = document.querySelector("#roll");
        _timestamp = document.querySelector("#timestamp");
    }

    function startInclinometer() {
        var inclinometer = Windows.Devices.Sensors.Inclinometer.getDefault()

        if (inclinometer) {
            var minimumReportInterval = inclinometer.minimumReportInterval;
            var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
            inclinometer.reportInterval = reportInterval;

            inclinometer.addEventListener("readingchanged", onReadingChanged);
        }
    }

    app.onloaded = function () {
        getDomElements();
        startInclinometer();
    }

Once again, no real surprises here. We get to our data in the same basic was as we did with the other sensors. Wire up to an event, which will fires on an desired interval giving us the X, Y, Z values. No real magic here other than the software you’re building to consume it.

Summary

Today we briefly looked at getting data from our inclinometer. Working with each of these sensors is pretty much the same but what you do with them is entirely up to you.

If you’d like to download my working sample that uses the code from this article, click the icon below:

 downloadHTML

Tomorrow, we’re going to look at the Inclinometer.  See you then!

downloadTheTools

Posted in 31 Days, Windows 8 | Tagged , | Leave a comment