Windows 8: Building Up to Blank


When you’re learning a new platform or development stack or seeing something for the first time, it’s an exercise in concept building. If you don’t get the concepts down then you may as well be a monkey walking through steps. And sometimes when you start with a project template, so much has been done for you that grasping concepts involves separating what is fundamental to the technology and what has been done for you by the tooling.

I’m not one to throw the tools and templates out the window. Once you get the concepts down they’re awfully handy. But let’s throw them away temporarily while we learn the concepts and then we’ll run out to the curb before the garbage guy gets here and retrieve them.

I’m going to use Visual Studio 11 (Consumer Preview) and start with a truly blank HTML/JavaScript project and work us up to the blank project - that is - work us up to the project template that you get with VS11, which although it’s called blank is not quite.

Here we go...

Start with the blank template... then kill it...

Open VS11. Create a new Windows Metro Style JavaScript project using the Blank Application template.

Here’s what your Solution Explorer should look like...

Notice that you already have a bunch of stuff. So let’s kill it. Delete everything in there except for the images folder (because we’d just have to recreate those anyway). Also, go to the References folder and remove the reference to Microsoft Windows Library for JavaScript SDK.

Your Solution Explorer should now look like this...

Ah... clean slate. That’s better. Now it’s time to get started.

Add a default.html file

If you’re going to make an HTML application, you’re going to need an HTML file for sure. So right click on your project and choose Add New Item, then choose a simple, old, plain, no frills, basic, classic HTML file. Actually, it will be HTML5 so I guess that’s not so classic yet. Call it default.html and be done with it.

Type “Hello, World!” inside the body and you should have something like this...

At this point, it seems the app would be executable, but if you try you’ll get a message that you’re required to have an application manifest file. That’s one of the few ways in which an HTML/JS app in Metro is different from a website. So we’ll add that now.

Add an application manifest file...

Add a new blank XML file to your project. Call it package.appxmanifest.

There are a few things required in this file. Let’s enumerate.

Below the XML declaration add the Package element...

<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">
</Package>

Then inside the Package element add...

<Identity
    Name="dfc9ddf8-dde8-4460-8967-1dbb70b653fa"
    Version="1.0.0.0"
    Publisher="CN=Jeremy" />

The Name value is a unique identifier for your application. You should be safe using the GUID from my example above since I don’t have any plans of publishing this application to the store 🙂 Obviously you can put your name in there as the publisher.

Then add this after the Identity element...

<Properties>
    <DisplayName>Application1</DisplayName>
    <Description>Application1</Description>
    <PublisherDisplayName>Jeremy</PublisherDisplayName>
    <Logo>images\storelogo.png</Logo>
</Properties>
<Prerequisites>
    <OSMinVersion>6.2</OSMinVersion>
    <OSMaxVersionTested>6.2</OSMaxVersionTested>
</Prerequisites>
<Resources>
    <Resource Language="x-generate" />
</Resources>

You can imagine what each of these elements does, so I won’t bore you with the details.

The next section is more interesting. Add this...

<Applications>
    <Application Id="App" StartPage="default.html">
        <VisualElements
            DisplayName="Application1"
            Logo="images\logo.png"
            SmallLogo="images\smalllogo.png"
            Description="Application1"
            ForegroundText="light"
            BackgroundColor="#000000">
        <DefaultTile ShowName="allLogos" />
        <SplashScreen Image="images\splashscreen.png" />
        </VisualElements>
    </Application>
</Applications>

This is almost entirely intuitive, so I won’t explain. Notice all the links to the images that I had you leave in the project.

Finally, add...

<Capabilities>
    <Capability Name="internetClient" />
</Capabilities>

... which declares a single capability - internetClient. This capability declares that this app will want to be able to access the internet. Without it, HTTP calls outside the application would be blocked. In this blank app, we don’t actually need to access internet, but we’ll leave this in there since the blank project template does.

That’s it for the package.appxmanifest file.

Now try running your app! You should see Hello World on a big white screen. Exciting isn’t it. You have two files in your project and already you have a working, albeit boring application.

Let’s keep moving though and work up to what the blank project template offers. It’s not a lot further we have to go.

Sign your application...

The blank template contains a .pfx file. That is a Personal Information Exchange file that allows for release signing. To generate it double click on your package.appxmanifest file. Then go to the Packaging tab. Then hit Choose Certificate next to the Publisher field. Then I just chose to create a test certificate. As you can see the .pfx file is automatically created for you.

Here’s a snapshot of your Solution Explorer again...

Add the WinJS styles and scripts to make it a Metro app...

Our app runs and shows “Hello, World!”, but it looks more like a web page than like a Windows 8 Metro style app. We just need to bring in some script and style sheet references in order to make this look and act like a Metro app. Those references are inside of the WinJS library package. To add a reference to that package, just right click on References and Add Reference. Under Extensions, you’ll see Microsoft Windows Library for JavaScript SDK (at version 0.6.0.0 as of this post). Add that.

There are three references we want to make.

  1. ui-dark.css - gives us the black background color, white foreground color, and a lot of Metro style rules
  2. base.js - gives us a lot of core functionality in WinJS like classes and namespaces and such
  3. ui.js - gives us a ton of UI functionality like animations and visibility control

Keep in mind that these dependencies are not entirely necessary. If you bring a web application into Metro it obviously won’t have them and it won’t need them until the first time you want to use something from WinJS. In fact you can still even call into the WinRT without these references, but if you’re making an application for Windows 8. then you probably want to use WinJS. There’s no real reason not to.

To add references to these three files, here’s what we do. Just add these three lines inside the <head> element of your default.html file...

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

Note that the values for the href and src attributes start off with “//”. If you leave the scheme off of the URL here then the assumed scheme is “ms-appx” which means “this package”. So “//” is equivalent to “ms-appx://”. Then when specifying the domain, you have the option of using the name of a package (in this case “Microsoft.WinJS.0.6”). So these lines are referring to the ui-dark.css, base.js, and ui.js files from the WinJS package.

Now run your application and note that it looks very Metro indeed.

Add your own style and script files and references...

If you are going to style anything on the default.html page, you’ll need a style sheet. By convention, we put the .css files into a css folder and we create one for each page. So let’s create a css folder and create a default.css file in it. Also, you’re going to want to write some JavaScript as well. Again, by convention we put .js files into a js folder and create one for each page. So we’ll also create a js folder and create default.js in it. Here we are...

The CSS style sheet that we created came with a single style tag for the body. The blank template has something more, so lets add and explain. Add this to the default.css after the body style rule...

@media screen and (-ms-view-state: fullscreen-landscape) {
}

@media screen and (-ms-view-state: filled) {
}

@media screen and (-ms-view-state: snapped) {
}

@media screen and (-ms-view-state: fullscreen-portrait) {
}

These are called media queries, and they are super nice. Media queries allow us to specify different styles for the different view states our application might be in. If you can control the look and layout of your app with CSS alone, then you don’t even need to write any code for when the user rotates his tablet or snaps your app. There is an event for when the layout changes, however, for when you need to write code.

We’ll need  references to our new .css and .js files in default.html too. Adding this to the <head> element (under where you have the WinJS references) should do it...

<link rel="stylesheet" type="text/css" href="css/default.css" />
<script type="text/javascript" src="js/default.js"></script>

Write the application lifecycle and event script...

The last thing we need to do is write some JavaScript to handle the basic application lifecycle and events. We don’t have a separate App entity in HTML/JS like you would have in a XAML/C# app. Instead, this logic goes into the default.js file and it’s quite simple. We’ll take it one step at a time.

First, open default.js. It’s completely empty. Here’s a snapshot of what a completely empty file looks like...

Nice, eh? Like a polar bear in a snow storm.

Now, in order to stick with a fundamental JavaScript pattern called the modular pattern, we’re going to start by writing an anonymous function...

function() {}

This function has no name. That’s why we call it anonymous. And so far its body is empty. We want the code in this function to execute though. We don’t want to just declare a function. We want it to go. So we do this...

(function() {

})();

Note that we have simply wrapped the function in parentheses and then put a football (the two calling parentheses) at the end... plus a semicolon for good measure. This effectively declares and calls our function all at once. Actually, first it declares it and then it calls it.

The reason we do this (and this is why the modular pattern exists) is because then the stuff we do inside our function is scoped to the function. If we declare a variable, it is only available inside that function. This is good because otherwise any other part of the application (including 3rd party libraries you might want to bring in) that tried to use the same variable name would have a collision and would get really angry.

One more thing we add is a “use strict” directive to tell Visual Studio we want a little help making sure we don’t accidentally to silly JavaScript wizardry like use a variable we having yet declared or the like. Here’s that...

(function() {
    "use strict";

})();

Inside that function now, we want to handle some application events. The blank template actually defines just two, but I’m going to do a third for your benefit.

We’re going to be referring to the application by using WinJS. We do that by using WinJS.Application. But we don’t want to have to type that out every time, so we can effectively give it an alias by adding...

var app = WinJS.Application;

Now we can just use app instead of the whole thing. I guess you could sort of compare it to a using in C# except that it doesn’t import a namespace. It only gives one an alias.

We’re ready to write our application events. These go inside the function we’ve been talking about...

app.onactivated = function (eventObject) {

};

app.oncheckpoint = function (eventObject) {

};

app.onready = function (eventObject) {

};

You can probably guess about onactivated and onready. onactivated fires when the app is started from scratch or when it revived from a suspended state. onready fires whenever you request the default page. And then we need to add one more line...

app.start();

This... um... well, it starts the app. 🙂

So all together, you’re default.js should look like this...

(function() {
    "use strict";

    var app = WinJS.Application;
    app.onactivated = function (eventObject) {

    };

    app.oncheckpoint = function (eventObject) {

    };

    app.onready = function (eventObject) {

    };

    app.start();
})();

And if you want to test the onready event for instance, try adding this line inside...

new Windows.UI.Popups.MessageDialog("ready").showAsync();

The blank application further breaks down the onactivated event with this code...

var a = Windows.ApplicationModel.Activation;

if (eventObject.detail.kind === a.ActivationKind.launch) {
    if (eventObject.detail.previousExecutionState !==
        a.ApplicationExecutionState.terminated) {
        // TODO: This application has been newly launched. Initialize
        // your application here.
    }
    else {
        // TODO: This application has been reactivated from suspension.
        // Restore application state here.
    }

    WinJS.UI.processAll();
}

Actually, I added the var a = ... there just to make it shorter, but the point here is to detect whether the application is being launch anew or resuscitated.

And there you have it. You should now be at the functional equivalent of the blank application, but you’ve done it all yourself. You can’t claim ninja status yet, but you can have a yellow belt.

Copyright (c) Microsoft. All rights reserved. The code provided in this post is licensed under the MS-Limited Public License


Skip to main content