Six hundred and sixty six XSS vectors, suitable for attacking an API

So I need to attack an API. None of the XSS tools do it well - not Burp, not xsser, not Xenotix. All of the XSS vectors are packed away in Perl or Ruby or Python, or in articles. So I made my own data file.

Honestly, I didn't tweak the number, that what it came out to when I was done.

Anyway, here it is, ready for your File.ReadLine pleasure:

http://pastebin.com/48WdZR6L

Please use it responsibly.

S

Reflected XSS

As some of you know, I have been spending much of 2013 doing security related testing of applications (sometimes called penetration testing, or pentesting). This is a change from my usual, 20 year history of writing secure applications. I am still all about writing secure applications, and will be doing more of that in the future, but there are a lot of apps that need to be fixed.

All of the applications that I have tested this year, from fortune 100 companies to small companies that have a community web presence, have a common and very dangerous vulnerability called Reflected XSS. This is a Cross Site Scripting vulnerability that is related to content driven XSS, but has a different, and very scary, scope - values that are directly written to the user's screen from a POST or GET operation.

I could go on and on about the dangers of XSS, but I'll leave that to OWASP, and instead tell you how to avoid it.  Leave it to this: XSS is a phishing related vulnerability. It requires users to get all clicky with an email, but when it works, it gives the attacker a very easy path to application ownage.

How it works

We all know to encode output by now, but some things, like exception handling especially, escape our view. Error handling is often encapsulated in common controls (as it should be), written quickly at the start of a project. Encoding of the output is usually not handled by the control, and is rarely implemented by those using the control.

Here is an example: a simple web site that expects the user to type the right string:

 

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <h3>Only type "xss" here!!</h3>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    Answer:
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Content>

 In the back end, I have rolled the exception management into the codebehind, just for example's sake.

 

protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text != "xss") throw new ApplicationException("The value " + TextBox1.Text + " is not correct.");
                Label1.Text = Server.HtmlEncode(TextBox1.Text) + " is correct!!";
                Label1.ForeColor = System.Drawing.Color.Black;
            }
            catch (ApplicationException ex)
            {
                Label1.Text = ex.Message;
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

 

Now, when we type the right string, the application behaves as expected:

  

 

And when we type the wrong string, the application also behaves as expected:

 

  

That's as far as much testing takes us.  However, when we type evilstring:

 

  

That's when the problems occur. Of course, the bad actor won't just put up an alert().

 

Fixing it

Fixing the problem is very simple.  Just encode the string you are writing to the screen. The exception manager should assume that string is evil, just like it should with every other string.

protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text != "xss") throw new ApplicationException("The value " + TextBox1.Text + " is not correct.");
                Label1.Text = Server.HtmlEncode(TextBox1.Text) + " is correct!!";
                Label1.ForeColor = System.Drawing.Color.Black;
            }
            catch (ApplicationException ex)
            {
                Label1.Text = Server.HtmlEncode(ex.Message);
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

 

My example is in .NET, which means I had to disable the AntyXSS AntiXSS library, but if you are writing in Rails, PHP or Java you aren't so lucky.  Better to be safe than sorry.  Encode that output folks!!  ENCODE IT!!

 

 

 

 

Summary of my Windows Store App security BlackHat talk

 

Last week, I spoke on the security implications of Windows Store apps for Windows 8 at BlackHat Europe. Running the risk of ruining the suspense for later listeners, I decided to take the advice of several of my attendees and summarize my main points here.

Remember, this is just a summary. I am boiling down a 60 minute talk into 12 or so talking points. If you have questions about specifics, ping me in the comments or via the contact form.

Some of this is original research, some of it is just from the documentation, but all of it applies to the security or privacy of Windows Store apps on Windows 8. Doesn’t matter what you think of Windows 8, you will have to deal with it eventually. It is growing faster than XP or 7 did. The store is selling stuff. It is out there. You will have to either scan an app for your company, or deal with BYOD.

This is all about helping you out.

Features with a risk component

  • You log into a Windows 8 machine with your Microsoft Account. Apps have access to the account information with only a request at install time. Are your users logging in with personal accounts? Company accounts?
  • Capabilities need to be used sparingly. Least Privilege is the rule, not the exception.
  • Remote Settings stores the data saved to it somewhere in the cloud.
  • Local Settings are saved in an unencrypted XML file.
  • The applications themselves are saved locally with source code available or easily obtainable. Code defensively!

 

 

 

 

Testing Windows Store Apps

  • Test backend services with Burp or ZAP.
  • Test for the same vulnerabilities you test your web apps for, manually for now.
  • Do a code review.

 

 

Countermeasures provided by WinRT

  •  Hashing and encryption are in Windows.Security, but are sloowwww.
  •  Instead of Microsoft Account, use OAuth for auth-n
  •  Apps that come across an unexpected error, don’t leak information. They just die!!

 

 

There you go. If you didn’t make it to my talk, you don’t need to go to a later rendition (although the demos are pretty awesome). I just want to make sure that people understand what they are getting into with Windows 8 apps.

Are you doing Windows Store app research? If so, drop me a line. You can find me @sempf on Twitter, or use the contact for on the blog here – it works good.

 

Why I went back to Android from WP8

At BUILD 2012 Microsoft gave me a Nokia 920 Windows Phone.  Ever since then I’ve been using as my primary cell phone.  It has had ups and downs, but in general I enjoyed very much.

Originally, I was using a Samsung Galaxy Nexus.  That phone had served me well for many months before I switched to the Nokia.  I wanted to give the Nokia a fair shot, because I really believe that Windows Phone can succeed.  Although it was a good run, there were several things that made the switch back necessary.  Let’s start with the good things first.

The good

First, the phone is truly beautiful.  I don’t just mean well-built. I mean everything about it is truly amazingly beautiful.  The device itself, the screen, the applications, the start screen.  Everything.  It’s a joy to use.

Second, the integration with Microsoft products is a very impressive.  The office tools work very well.  Skype and Messenger are very good.  The Xbox integration is truly incredible.  Microsoft has done a very nice job of making the Windows Phone platform part of the full Windows suite of products.

Third, despite what people say, the selection of applications is very impressive.  I have yet to find more than one significant application but I need that isn’t in the window store.  The only thing I ever found that was missing was Wuala, but with the weaknesses in Java I switched to SkyDrive anyway.

The bad

Despite the fact that the user interface is very smooth, the whole phone updates very slowly.  It takes a long time to update the applications.  Text messages come in the wrong order.  E-mail takes a long time to synchronize.  In general, network activity is less than wonderful.  When the phone goes to sleep, it forgets a lot.  A lot more than it should.  Every time I wake it to use it have to wait for it to remember what network it’s on, what wifi I was using and what I was doing last.

All of those same lines, and synchronization is very weak.  Trying to get service driven applications to get new data and refresh the cache is very difficult.  If the application developer fails to give you an explicit synchronization option, you’re often out of luck. Often, I had to restart the phone to get things updated.

While there are no lack of applications in the store, developers are not keeping up with new trends.  For instance, there’s no Pebble app for the windows phone.  Windows Phone is still the last in line to get an app for a new online tool, if it ever gets one at all.  I’m not really an early adopter so this isn’t a huge deal for me, but occasionally I’d like to see some of the new stuff that’s out there.  It’s frustrating that I never seem to be able to.

One more thing.  The phone is absurdly heavy.  I know that’s a small thing but after a while it gets to you.  It’s amazing how six ounces matters. Makes my pants fall down.  Nobody needs to see that.

The ugly

The phone reboots 10 times a day.  This is a not the huge problem for me it is for some people because I am not a heavy phone user.  It can get frustrating when I sit down for short ‘break’ (you know what I mean), launch Angry Birds, and immediately get to watch the phone reboot.  Where it really becomes a problem is when some call comes in, and the phone reboots.  This happens to me least once a day.  I have more than a few uncomfortable moments having to call somebody back and explain that my phone reset.

A huge problem is the lack of S/MIME support.  There is just simply is no way to send secure email using Windows Phone.  Yes I’m aware that I could write an application for S/MIME.  But that’s not really my area of specialty in programming, and I have other things I need to write more.  It seems like S/MIME is something that should be supported out of the box on any platform these days.  I mean come on, even Windows Mobile 5 supported S/MIME.

The real nail in the coffin for me is the lack of integration with other e-mail platforms.  Many moons ago I used Microsoft’s online office tools for my business.  The product flopped, and I went to Google Apps.  I very much enjoyed using the Google product since then.  I don’t mind paying for Google Apps, I think Gmail is a fantastic product.  The spam filtering, certainly, and threaded messaging are just too good to leave.  The domain level integration, document storage, search and sharing, and ease of use are just better than anything else out there. Plus, it supports two-factor authentication.

For whatever reason, Windows Phone 8 is horrible running Google Apps. Email synchronization is awful.  Google Talk barely works at all. Notifications don’t work. None of the other applications are available.  Google has decided that they are going to beat Microsoft on at least this one thing, and this is a pretty successful way to do it.  They have not wanted to make their tools available on the windows platform and I can’t blame them.  Microsoft on the other hand has made most of the tools available on Android.  Thus if I want to use a Microsoft tool, it is probably available on the Android platform.  The reverse is not true.

Conclusion

So there you have it.  The problem is not the app store.  The problem is not the lack of the phone’s popularity.  The problem is that in making the phone easy to use and easy to develop for, they have closed the door to too much innovation and integration. It’s really easy to do the things we wanted to do yesterday, and really hard to do the things we need to do tomorrow.

I still think the Windows Phone is an excellent consumer device.  I would recommend it to anybody.  Not too many people worry about A/MIME support, or integration with their business’s Google Apps.  The application selection, games, and Microsoft integration is really very good.  The phone draws stares everywhere I use it.  But it just isn’t right for me, and I can’t make it right for me.  Therein lies the rub.

I’ll still develop for the windows phone.  I’ll still use it as a standalone device.  It just doesn’t work for me as a primary phone, and I can’t imagine that it does for anyone else with specialized needs.  Microsoft has made their decision, and they’re shooting for the 80%. Unfortunately, the 20% are the folk with loud voices.  That might be the platform’s downfall.

Fixing the 'The package contains code signing keys <project>_TemporaryKey.pfx' WACK error

I recently updated a Windows 8 application for a client, but it failed submission to The Windows Application Certification Kit. The problem was shown as: 

The package contains code signing keys <project>_TemporaryKey.pfx

The development key was in the project, but it needed to be to do the signing for the test run. I had no idea what to do so I pinged Jon Box and he asked if the project has been initially done on someone else's machine. That got me thinking - this project file was from an earlier pre-release version of Visual Studio! Perhaps there was a configuration problem with the project itself.

Next, I opened the file uin a text editor and located the PropertyGroup that hosted the key information.

 

<PropertyGroup>
    <TargetPlatformIdentifier>Windows</TargetPlatformIdentifier>
    <TargetPlatformVersion>8.0</TargetPlatformVersion>
    <DefaultLanguage>en-US</DefaultLanguage>
    <PackageCertificateKeyFile>Tower_TemporaryKey.pfx</PackageCertificateKeyFile>
    <AppxAutoIncrementPackageRevision>False</AppxAutoIncrementPackageRevision>
  </PropertyGroup>

 

I deleted the PackageCertificateKeyFile to see if Visual Studio would remake it, and it did, and included a hash this time (interesting addition). What was more interesting was that VS changed the ItemGroup node for the key inclusion from Content to None. That was probably the bit that did it.

Hope this helps someone else who runs into this problem.

Viewing the source code of installed Windows Store apps on Windows 8

While it isn't surprising that you can access the files of installed Windows Store apps (they are installed locally after all) it might to come as a surprise to some that the code isn't encrypted or obfuscated at all. In my early conversations with Microsoft I was led to believe that the code would be encrypted as part of the signing process, but that isn't true at all.

Getting to the installed apps

Files for installed apps are in C:\Program Files\WindowsApps, which is 'hidden' so make sure you have 'View Hidden Items' turned on. This folder isn't accessible by the governing user even if you are running as the administrator, which you shouldn't be. The easiest way to get access to the folder is to take ownership of the folder and everything in it.  You can do this with Powershell if you like.

Get-ChildItem 'C:\Program Files\WindowsApps' -recurse | ForEach-Object {Get-Acl $_.FullName}

But is remarkably easy to do in the UI, so that is how I did it.  Right click on C:\Program Files\WindowsApps and select Properties, then click on the Security tab. From there you can click Advanced to get the Advanced Security Settings. As you can see from Figure 1, the owner is TrustedInstaller. 

Click the Change link and then type in your Microsoft Account email address. Then press enter, OK, and OK again to close all of the dialog boxes. From there you can easily navigate to any installed apps.

Open one of these, Amazon for instance, and you can see that the file structure is just as it would be in Visual Studio.

From there you can browse at will.

As expected, apps written in C++ or .NET are compiled EXEs, although the XAML is still browsable. Here is Barnes and Noble's Nook app, as a point of comparison.

 

Nothing that a small dose of dotPeek won't fix, I am sure. I'll leave that as an exercise for the reader.

The implications

What are the implications of all of this? Not a lot really. For most apps written in JavaScript, there is nothing there that a quick right-click, browse-source won't do for you on that organization's web site. JavaScript is just as discoverable as HTML in those cases.

For some apps, though, there may be some consideration for keys to services such as Google, Bing or other service providers.  For instance, we are using Weather Underground in an app I am developing, and the client's use key is right there in the settings.js file. Usually, that would be accessed server-side in a regular web app, and apparently we are going to have to do something similar for the Windows 8 app. Perhaps wrapping external services in your own service layer and then accessing those to get the values provided by the original service.

There has been some discussion of changing code, recompiling using the provided key, and getting access to for pay content or disabling ads. I am not a fan of ripping of developers (being one myself) so I won't go into that here. It could be a very significant detriment to those seeking to monetize apps, however.

The most significant thing, as usual, is developer ignorance. If the developer doesn't realize that all of the code is easily browsable, then they may make poor decisions in the construction, commenting or production of the code base.

Lesson learned - code as if someone is watching you. Because they are!

Using QUnit with Windows 8 Apps

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

Some of the new research in Windows 8 revolves around using a unit testing framework with your JavaScript, just as if you are writing a JQuery or Node.JS project. Some of those frameworks work well with Windows 8.

For instance, take QUnit as an example. Originally created to be the unit testing environment for JQuery projects, QUnit is now a standalone project. The source can be included in a Windows 8 project, and your tests can get a lot more interesting.

To run tests using QUnit, download the QUnit file and the CSS file from Github (at https://github.com/jquery/qunit) and then put this into your default HTML in your tests file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Qunit</title>

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

    <!-- Qunit references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
    <script type="text/javascript" src="js/qunit.js"></script>
    <link rel="stylesheet" type="text/css" href="css/qunit.css" />
</head>
<body>
  <div id="qunit"></div>
</body>
</html>

 

tip: Make sure the script source matches.

This gives you a reference point to start your tests. We just need to insert a test into the Windows 8 code. A test looks like this, from the sample website:

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                test("hello test", function () {
                    ok(1 == "1", "Passed!");
                });
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

QUnit will give you a nice output on the main page of the Metro app. I just set up a separate page control for testing, and set the default page of the app to it when checking tests.

image

 

 

 

 

That’s all there is to it! Happy testing.

Organizing your WinJS Metro code into namespaces

I have been struggling with namespacing since I started with WinJS. Not sure why, just can never get the Magical Rites correct. I think is has to do with when to add the Feral Cat Whiskers.

Anyway, here is a list of how I made it work for a simple reference project.

1) Add a base.js file to your /js directory. Populate it with a namespace declaration. DO NOT FORGET the closing parens.

(function () {
    WinJS.Namespace.define('MyApp', {});
})();

2) Add a settings.js file to the /ja folder (for example). Populate it with a method to share with the namespace.

(function () {
    function getSettings() {
        var settings = "D";
    }
    WinJS.Namespace.defineWithParent(MyApp, 'Settings', {
        getSettings: getSettings,
    });
})();

3) In the default.html file, add a reference to the two new files.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Namespace</title>

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

    <!-- Namespace references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
    <script type="text/javascript" src="js/base.js"></script>
    <script type="text/javascript" src="js/settings.js"></script>
</head>
<body>
    <p>Content goes here</p>
</body>
</html>

4) In default.js, call MyApp.Settings.getSettings() in the onactivated event. It's the bold line below.

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                MyApp.Settings.getSettings();
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };
    
    app.start();
})();

That's it. All there is too it. Everything else is gravy. At least this will give me something to go back and look at when I forget how to do it.

Make sure to get my new Windows 8 Programming with HTML5 For Dummies book when it comes out.

Doing security analysis on Windows 8 Metro Apps with Zed Attack Proxy

This is the first in a series of articles about attacking Windows 8 applications using Zed Attack Proxy, or ZAP. Windows 8 is the new version of the venerable Windows operating system from Microsoft. It has a new Windows programming model that is heavily based in a new API for Windows development, called WinRT. ZAP is a web proxy for security analysis of applications by OWASP. It is free.

Setting up ZAP for Windows 8

After installing ZAP, it needs to be made ready to act as a proxy for Metro applications. As most Metro applications make heavy use of the Internet for data storage, information access and communication with the Windows Store, use of a proxy is a great place to start to test the underlying security.

1) Press the Windows button and type Internet Options.

2) Press the Settings tab on the right of the Start Screen.

3) Select the Internet Options control panel.

4) Click the Connections tab.

5) Click the LAN Settings button

6) Change the Provy Server settings like Figure 1. Check the 'Use a proxy server' checkbox, then set the address to 'localhost' and the port to '8080'.

 

Figure 1 - configuring a proxy

7) Click OK, then click OK.

Finally, you have to configure the app you are testing to allow the loopback (locakhost) address as a proxy, which by default AppContainers aren't allowed to do. You can do this with PowerShell, but it is a lot easier to download Eric Law's excellent EnableLoopback utility, which will do the work for you. You just need to find the app you want to test and select the checkbox, then click Save Changes, like Figure 2.

 

Figure 2: the EnableLoopback Utility

Not your machine is configured to use ZAP as a proxy. While these settings are set, you will have to have ZAP running to use the Internet. Also, enabling the loopback address circumvents important security controls placed on Metro apps. Only use it on a test system.

Testing your settings

To test your settings, run ZAP by pressing the Windows key and typing ZAP then pressing enter. Then run an installed Metro app, like the Finance app, which you have configured for loopback. In ZAP, all of the services being called by the application will appear in the Sites pane, and all of the individual calls will appear in the History tab. Figure 3 shows my results.

 

Figure 3 - Finance Test results

 Each of these represents an HTTP call being made by the Finance app to populate it's screens. Apparently, the developers of this app chose not to use SSL for any of the calls, which makes our job easier - although since we have a man in the  middle the analysis can still be carried forward. Either way, this gives us a ripe field to begin our analysis.

Attacking underlying services

You can now use ZAP to test the underlying services with the fuzzer.

1) Select a service to test in the Sites pane. I selected the api.bing.com/appex service.

2) Highlight a parameter to fuzz in the Request pane, right in the querystring. I selected the 'a' parameter in Figure 4.

 

Figure 4 - Setting the fuzzing dictionary

3) Right click and select Fuzz. The dialog that appears is also shown in Figure 4.

4) Select the Fuzz category in the dropdown. I selected SQL Injection in Figure 4.The list of pre-installed fuzzers appear in the Fuzzers listbox. These are known attacks that work against a variety of databases. As this is a Microsoft service, we can assume that MSSQL is probably the database, although other test tools could be used to ascertain this. In Figure 4 that is the fuzzer I selected.

5) Click Fuzz to begin your attack. ZAP will begin to call the service with the attacks in the SQL Injection file.

And ... it didn't work at all. The Fuzzer tab shows each attack, and all of them have a 404 error in the result column. Apparently that field is being used as a controller method name - I should have thought of that!

Oh wrell, let's try something else. Select the 'q' parameter and try again with a SQL attack. This one is a lot better - every result comes back as a 200. Awesome.  Click on a line in the Fuzzer tab to see the result in the Response tab.

{
   "BdiGeneric_BingResponse_1_0":{
      "AppNS":"AppEx",
      "Responses":[

      ],
      "Errors":[
         {
            "Code":1002,
            "Message":"Parameter has invalid value.",
            "Parameter":"AppExNewsVerticalRequest.AppId",
            "Value":"'create user name identified by pass123 temporary tablespace temp default tablespace users; "
         }
      ]
   }
}

What have we here? A error code 1002? Aah, 'Parameter has invalid value.' -- they are using parameterized queries. I suppose one would expect a well vetted service like Bing to be hardened against the #1 exploit on the OWASP Top 10 though.

In the next in this series we will look at an exploitable app and try and test the services that make up its data storage facility. Thanks for reading!

Geting Notified

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

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

 Now that you have the template set up, getting notifications on the tile is not that tough. More or less, you want to decide what events in your system should update the tile, and then attach tile updates to them.

 So think about your application. In the ToDoToday app, I update the tile whenever the user updates the task list, making sure I show the latest tasks in the m notification area. If writing a game, you probably would want to update the tile every time the user clears a level.

 In general, treat the notification as exactly what it is. It is the opportunity to notify the user what the last thing happening in the app is. So:

 Update the notifications when the user does something significant

  • Update the notifications when there is significant information to pass on to the user.
  • Update the notifications when the app is about to be suspended.

 

Making notifications part of your tile

 The good news is that you have already made a notification part of your tile, in Rendering Content. Setting the Text element value in the tile XML is essentially a notification - the only difference is in use and strategy - the tactics are the same.

 So to best implement it probably would be best to construct a function that is designed to be called from any of the important events.

 

function updateTile(textNotification) {
    var tileTemplate = Windows.UI.Notifications.TileUpdateManager.getTemplateContent(Windows.UI.Notifications.TileTemplateType.tileWideImageAndText01);
    var tileTextAttributes = tileTemplate.getElementsByTagName("text");
       tileTextAttributes[0].appendChild(tileTemplate.createTextNode(textNotification));
    var tileImageAttributes = tileTemplate.getElementsByTagName("image");
    tileImageAttributes[0].setAttribute("src", "ms-appx:///images/WideLogo.png");
     var tileNotification = new Windows.UI.Notifications.TileNotification(tileTemplate);
    Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().update(tileNotification);
}

 

This we can then call, and maybe pass in the date just to see how it works. For instance, add a promise activated function after the processAll function in the default.js file of the sample project.

 

WinJS.UI.processAll().done(function (e) {
    var today = new Date();
    updateTile(today);
});

 

Run this and the tile should be updated with the date in the text region. Now, let’s say we want to update the tile live as the user is using the app. To replicate this, you can add a button and an event handler for said button right there on the default page.

 

<body>
   <button type="button" id="actionButton" style="position: relative; left: 300px; top: 300px;">Click Me</button>
</body>

 

Set up a variable for the button in default.js (I called it theButton) and then add a little code to call the updateTile function:

 

theButton = document.getElementById("actionButton")
theButton.addEventListener("click", function (e) {
    var today = new Date();
    updateTile(today);
});

 

Run the app again, then press the Windows key and confirm the date and time is in the tile. Then go back to the sample app and click the button.

 

Press the Windows key again and the tile will have changed. This could be the score, the news, or an appointment. The choice is yours.

 

Getting a message on the queue

 

What if there is more than one thing you want to show the user? You could use one of the templates with a lot of small text, but there is a better choice. Microsoft allows you to stack up to 5 messages on the queue and the tile will cycle through them one at a time.

 

In order to do this you MUST enable the queue. This is a one line property setting that you can put in the initialization code of your app. I used the onactivated event for this example:

 

Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueue(true);

 

After you do that, I would recommend clearing the queue. You don’t want what was in there before rolling through with your new content.

 

Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().clear();

 

So now our onAppActivated looks like this:

 

app.onactivated = function (eventObject) {
    if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
    Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueue(true);
Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().clear();
            theButton = document.getElementById("actionButton")
            theButton.addEventListener("click", function (e) {
               var today = new Date();
               updateTile(today);
            });
        }
        WinJS.UI.processAll().done(function (e) {
            var today = new Date();
            updateTile(today);
        });
    }
};

Press F5 to start the app, and then click the Windows button to take a look at the Tile. It should have the date on it. Go get a cup of coffee, and come back, I’ll wait.

 

Now press the Click Me button and then take a look at the tile. The notification should be scrolling between the two times - when you started the app, and when you clicked the button.

 

Go back to the app, click the button again. Now look at the tile; there are three dates scrolling by. You can have up to five of these, and the Notification manager will drop the oldest automatically.

 

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