Tag Archives: code

APP: Markdown Notepad

Now available in the Store for Windows Phone 8 apps, my latest app is a simple notepad app that uses the Markdown format. Ingeniously called Markdown Notepad, this app builds on the Markdown features that were built into Visual Diary and extends it with note backup to the cloud. After a few false starts trying to use SkyDrive (a service which I love!) for the cloud backup feature I found that the SDK didn’t give me what I wanted, so I used Buddy instead. Whilst this meant that the service wasn’t quite as friction free as I’d have liked it to have been because I then had to create the user management (registration, login, forgotten password), the API was simple to use and I’ve been really happy. The Buddy team were really responsive and quick to fix the couple of bugs that I found. I’d be happy to share the service wrapper that I created and even consider turning the user management stuff into a reusable control if anyone is interested.

As always, your ratings and reviews are welcome in the Store, and you can give feedback at http://gapshooter.uservoice.com/

Page01 Page02 Page03 Page04 Page05 Page06

Getting Started with the Windows 8 Consumer Preview

There are plenty of posts around on how to actually install the Windows 8 consumer Preview, so I’m not going to both covering that right now, but there were a couple of really useful resources that I wanted to highlight.

First up is some great design resources for designing the user experience for Metro style apps: http://design.windows.com. This includes:

  • Guidance on how to implement common design patterns in Metro style apps for navigation, commanding and touch interaction.
  • PhotoShop design assets for common controls and layouts.
  • Detailed UX guidelines.
  • Guidance for assessing usability.

The other resource is a collection of approximately 200 sample applications in C#, VB.NET, C++, and JavaScript covering pretty much every topic for the new SDK for Windows 8 Metro-style application development: http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples.

Go forth and enjoy!

Unable to activate Windows Tailored Application

Whilst developing Metro-style applications (quite possibly limited to XAML apps) you may be unfortunate enough to receive the error message “Unable to Activate Windows Tailored Application” when you try to run the application from Visual Studio. You’ll probably find that other applications that worked previously still do so, but this one won’t budge. In my case, the only additional information was the message: “The remote procedure call failed” and a message in the Output window to say that the program exited with code -1073741819 (0xc0000005).

Possible Solutions

This has been experienced by a few people and the following have been reported as solutions:

  • Running at a screen resolution higher than 1024×768.
    This is the minimum resolution for Windows 8 Metro-style apps.
  • Creating a new project and migrating the existing files.
  • Fixing errors in the application manifest.
    These may not be reported at compile/deploy time, but if you double-click on the Package.appxmanifest file, an error indicator is shown in the relevant tab.
  • Ensuring that you only have one merged resource dictionary.
    This is completely weird and was actually my problem!

Many thanks to Jeremy Brayton for his help debugging this issue on the forums.

Stick to One Merged Resource Dictionary

As mentioned above, my solution was to do with merged resource dictionaries. As with many projects that I’ve worked on, my application resources were split into separate resource dictionaries: one for brushes and one for styles. These were then added in App.xaml as follows:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        <ResourceDictionary Source="Assets/Brushes.xaml"/>
        <ResourceDictionary Source="Assets/Styles.xaml"/>

As it turns out, I only had a single style in Styles.xaml, so I moved that into a <Resources/> section in MainPage.xaml, removed the entry from App.xaml and hey presto! My app now builds, deploys, and runs without error.

Metro Style App Samples

There are a large number (about 200) samples for HTML5+JavaScript and XAML (C#, VB, and C++) on MSDN at the moment. You can sort and filter the apps to find something relevant to the task at hand, or you can download a single sample pack that contains all of the samples.

Right now the documentation of Windows Runtime is pretty thin on the ground, so these samples are the best way for you to start learning, though Microsoft folks are pretty responsive and involved on the forums, too.

Metro style sample apps

Using Custom Fonts in XAML Apps

The first Metro application that I started to build for Windows 8 was a simple digital clock; partly because I thought this was a good simple application to get started with, partly because it would be handy combined with the docking station, and partly because I’d already written one for Windows Phone. However, the first issue that I noticed was that the embedded font I used originally no longer worked and without any XAML support in Blend it was difficult to see how this would work.

Twitter.FontEmbeddingHaving managed to convince Joanna Mason (the Lead Program Manager for Expression Studio) to start tweeting at BUILD, I asked her if font embedding was supported only to find that it’s not. Fortunately, the equally awesome Tim Heuer joined the conversation and confirmed that although there’s no support in the Visual Studio designer for embedded fonts, it can in fact be done, and here’s how.

Get to the Code!

Font file propertiesThere are just three simple steps to get custom fonts working in your XAML application:

  1. Add the font file to your project.
  2. Change the Build Action for the font to Content.
  3. Reference the font file and font name in your XAML using the format:
    /<path to font file>/<font file>#<font name>

As you’d expect from XAML, you can set this either directly on an element by using the FontFamily property, or you can set it in a suitable style. The inline approach looks like this:

&lt;TextBlock FontFamily=&quot;/Assets/QuartzMS.TTF#Quartz MS&quot;
           Text=&quot;Hello World!&quot; /&gt;

As mentioned above, there’s no support in the designer for custom fonts, so you won’t see anything different in Visual Studio, but when you run it the end result looks like this:



Digital Clock, my first Metro application, will feature a lot on this blog while I get to grips on various new parts of the Windows Runtime. For example, you can expect a post in the near future on the new Settings contract.

Don’t Forget!

Parking Tickets

The current approach for reminders works on the assumption that you are using a “pay-and-display”-style car park where you pay in advance to park for a certain amount of time.

Another option would be to track how long you’ve been parked and calculate what your current parking fee is for the shopping centre-style parking where you pay on exit.

If you’re interested in this second model then it would be great if you could give me your feedback over on UserVoice.

One of the many (500+ apparently) new features in Windows Phone 7.1 (codenamed Mango) is the ability to set reminders from your application. I’ve been working on the Mango-enabled version of Car Finder and thought it would be great if the user could set a reminder for when their parking ticket is due to run out.

Get to the API Already!

Ignoring the user interface aspects for now, actually creating a reminder is fairly simply and involves using the ScheduledActionService class. This class is actually the base for  Alarm, Reminder, PeriodicTask, and ResourceIntensiveTask, so it’s quite an important class, but I’ll cover alarms and background agents another time.

I’ll quickly summarise how you use the API, and then give you my helper class afterwards, so don’t worry about the details for now.

Alerts.DarkCreating a Reminder

Creating a new reminder is as simple as calling the Add method and passing a ScheduledAction instance. The ScheduledAction instance for a reminder is a Reminder and contains the time for the reminder to occur, the title and content of the reminder, the URI to navigate to if the reminder is tapped, and how the reminder occurs (if at all). The Reminder also has a name, which is used to identify it in the ScheduledActionService.

Deleting a Reminder

Deleting a reminder simply involves calling the Remove method and supplying the name of the reminder that you want to remove.

Getting a Reminder

You can get the details of an existing reminder by using the Find method and supplying the name of the reminder that you want to get. Handily, this gives you the full Reminder instance that you set when you created the reminder.

The ReminderManager Class

So, that’s (briefly) how you manage reminders, so here’s my helper class that achieves all of the above.

As with my EnterKeyHandler, this code is available as part of the Windows Phone 7 from the Trenches repository at BitBucket. It will also be available (as the EnterKeyhandler already is) on the WP7 Contrib project.

namespace DerekLakin.Common
    using System;
    using Microsoft.Phone.Scheduler;

    /// &lt;summary&gt;
    /// Provides a static helper class for managing reminders.
    /// &lt;/summary&gt;
    public static class ReminderManager
        /// &lt;summary&gt;
        /// Adds a new reminder.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;name&quot;&gt;The name of the reminder.&lt;/param&gt;
        /// &lt;param name=&quot;title&quot;&gt;The title of the notification.&lt;/param&gt;
        /// &lt;param name=&quot;body&quot;&gt;The body of the notification.&lt;/param&gt;
        /// &lt;param name=&quot;beginTime&quot;&gt;The time of the reminder.&lt;/param&gt;
        /// &lt;param name=&quot;navigationUri&quot;&gt;The URI to be passed to the application on launch.&lt;/param&gt;
        /// &lt;param name=&quot;recurrence&quot;&gt;The recurrence of the reminder.&lt;/param&gt;
        /// &lt;returns&gt;The new &lt;see cref=&quot;Reminder&quot;/&gt; instance.&lt;/returns&gt;
        public static Reminder AddReminder(
            string name,
            string title,
            string body,
            DateTime beginTime,
            Uri navigationUri,
            RecurrenceInterval recurrence = RecurrenceInterval.None)
            if (HasReminder(name))

            var reminder = new Reminder(name)
                BeginTime = beginTime,
                Content = body,
                NavigationUri = navigationUri,
                RecurrenceType = recurrence,
                Title = title

            return reminder;

        /// &lt;summary&gt;
        /// Gets the reminder with the specified name.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;name&quot;&gt;The name of the reminder.&lt;/param&gt;
        /// &lt;returns&gt;A &lt;see cref=&quot;Reminder&quot;/&gt; instance if found; otherwise &lt;c&gt;null&lt;/c&gt;.&lt;/returns&gt;
        public static Reminder GetReminder(string name)
            var reminder = ScheduledActionService.Find(name) as Reminder;
            return reminder;

        /// &lt;summary&gt;
        /// Determines whether there is a reminder with the specified name.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;name&quot;&gt;The name of the reminder.&lt;/param&gt;
        /// &lt;returns&gt;
        ///&lt;c&gt;True&lt;/c&gt; if there is a reminder with the specified name; otherwise, &lt;c&gt;false&lt;/c&gt;.
        /// &lt;/returns&gt;
        public static bool HasReminder(string name)
            var reminder = GetReminder(name);
            return reminder != null;

        /// &lt;summary&gt;
        /// Removes the reminder with the specified name.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;name&quot;&gt;The name of the reminder.&lt;/param&gt;
        public static void RemoveReminder(string name)
            if (HasReminder(name))


Using it in Anger

In Car Finder, I have a method that creates a reminder and it looks (more-or-less) like this:

private void CreateReminder()
    // NOTE: The ReminderManager handles removing an existing reminder of the
    //       same name if one exists.
    catch (Exception ex)
        this.IsReminderSet = false;

In the constructor for the view model, I do a  check to see if a reminder exists and update the local properties accordingly:

/// &lt;summary&gt;
/// Initializes a new instance of the &lt;see cref=&quot;MainViewModel&quot;/&gt; class.
/// &lt;/summary&gt;
/// &lt;param name=&quot;locationManager&quot;&gt;The location manager.&lt;/param&gt;
/// &lt;param name=&quot;settings&quot;&gt;The application-wide settings.&lt;/param&gt;
/// &lt;param name=&quot;resourceClient&quot;&gt;The resource client.&lt;/param&gt;
public MainViewModel(
    LocationManager locationManager,
    Settings settings,
    IHandleResources resourceClient)
    this._locationManager = locationManager;
    this._resourceClient = resourceClient;
    this._settings = settings;

    // ...

    if (ReminderManager.HasReminder(Constants.ReminderKey))
        var reminder = ReminderManager.GetReminder(Constants.ReminderKey);
        if (reminder.BeginTime &gt; DateTime.Now)
            this._reminderTime = reminder.BeginTime;
            this._isReminderSet = true;
            this._reminderTime = DateTime.Now;
            this._isReminderSet = false;
        this._reminderTime = DateTime.Now;
        this._isReminderSet = false;

When the toggle switch to set a reminder is cleared, I remove the reminder like so:

public bool IsReminderSet
        return this._isReminderSet;

        if (this.UpdateProperty(&quot;IsReminderSet&quot;, ref this._isReminderSet, value))
            if (this._isReminderSet)

That’s pretty much all there is to it. I hope you find it useful.

Creating Copyable Read-Only Text

Ignoring any debates or discussions about when it’s going to arrive if you haven’t got it already, but the recently-released update for Windows Phone 7 (WP7) code-named NoDo (apparently short for No Donuts) brought the much discussed copy and paste feature.

How Does it Work?

The copy and paste feature has been available in the developer tools since December 2010, so we already know that the copy and paste feature works in the following scenarios:

  • TextBox
  • PasswordBox
  • WebBrowser control, but only for TextBox elements on a web page, NOT all text.
  • Internet Explorer(IE), for any text not just TextBox elements.

IE vs. WebBrowser Control

I’m not going to go into why the WebBrowser control only supports this feature for HTML textboxes, but IE supports it for plain text as well (mainly because I don’t know), but if Brandon Watson or Charlie Kindel read this, I’d love to hear an explanation. For now we just have to deal with this fact and move on. Hopefully, in time this feature will be improved upon in a future release.

copyTo copy a word simply tap on that word and it gets highlighted with the copy icon above it. You can extend the selection to more than one word by dragging the selection left or right accordingly. Once you’ve got the selection right, just tap the copy button. This results in the Paste icon being displayed at the top of the keyboard (SIP) at the bottom of the page. You can then tap any other supporting control to change focus, and then tap the Paste icon to paste the copied text. At this point, the Paste icon disappears, but don’t worry, if you want to paste the same text again somewhere else just wipe left to right where the Paste icon used to be and it will re-appear.


The copy and paste feature is also a global feature, so you can copy text in one application, open a new application, and then paste the copied text. This has particular advantage for applications that provide integration with web services that don’t support OAUTH or a similar convenient authentication mechanism and require an API key. You can navigate the user to the appropriate web page and instruct them to copy, and then paste their API key into your application.

So, What’s the API for Copy and Paste?

There is absolutely no API for the copy and paste feature (for now at least). I’m sure the stock answer is something to do with security, but we’ve got a clipboard API for “full fat” Silverlight and desktop applications, so I’m sure it will come in time.

If you already have an application in the Marketplace that has TextBox, PasswordBox, or WebBrowser controls in it, then you do not need to do anything to that application for it to get copy and paste support. Equally, you don’t need to do anything to enable copy and paste in new applications either. The copy and paste feature is an operating system update that users get on their devices and does not require an update to your code. If, however, you have areas of your application that you want to be read-only, but you want the user to be able to copy them (such as an API key), then you can use a TextBox with the IsReadOnly property set to true to achieve this.

The CopyTextBlock Style

Although it’s simple enough to set IsReadOnly to true on a regular TextBox, this doesn’t provide a great user experience for the user because it still looks like a TextBox. If you want a TextBlock that the user can copy from, then you can use the following Style for a TextBox instead, which not only makes it look like a TextBlock, but also removes 75% of the visuals, so is more efficient.

&lt;Style x:Key=&quot;CopyTextBlock&quot; TargetType=&quot;TextBox&quot;&gt;
    &lt;Setter Property=&quot;Background&quot; Value=&quot;Transparent&quot;/&gt;
    &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;{x:Null}&quot;/&gt;
    &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;0&quot;/&gt;
    &lt;Setter Property=&quot;FontFamily&quot;
            Value=&quot;{StaticResource PhoneFontFamilyNormal}&quot;/&gt;
    &lt;Setter Property=&quot;FontSize&quot;
            Value=&quot;{StaticResource PhoneFontSizeNormal}&quot;/&gt;
    &lt;Setter Property=&quot;Foreground&quot;
            Value=&quot;{StaticResource PhoneForegroundBrush}&quot;/&gt;
    &lt;Setter Property=&quot;IsReadOnly&quot; Value=&quot;True&quot;/&gt;
    &lt;Setter Property=&quot;SelectionBackground&quot;
            Value=&quot;{StaticResource PhoneAccentBrush}&quot;/&gt;
    &lt;Setter Property=&quot;SelectionForeground&quot;
            Value=&quot;{StaticResource PhoneTextBoxSelectionForegroundBrush}&quot;/&gt;
    &lt;Setter Property=&quot;Margin&quot; Value=&quot;0&quot;/&gt;
    &lt;Setter Property=&quot;Padding&quot; Value=&quot;0&quot;/&gt;
    &lt;Setter Property=&quot;Template&quot;&gt;
            &lt;ControlTemplate TargetType=&quot;TextBox&quot;&gt;
                &lt;Grid Background=&quot;Transparent&quot;&gt;
                        &lt;VisualStateGroup x:Name=&quot;CommonStates&quot;&gt;
                            &lt;VisualState x:Name=&quot;Normal&quot;/&gt;
                            &lt;VisualState x:Name=&quot;MouseOver&quot;/&gt;
                            &lt;VisualState x:Name=&quot;Disabled&quot;/&gt;
                            &lt;VisualState x:Name=&quot;ReadOnly&quot; /&gt;
                        &lt;VisualStateGroup x:Name=&quot;FocusStates&quot;&gt;
                            &lt;VisualState x:Name=&quot;Focused&quot; /&gt;
                            &lt;VisualState x:Name=&quot;Unfocused&quot;/&gt;
                    &lt;ContentControl x:Name=&quot;ContentElement&quot;
                                    Margin=&quot;{TemplateBinding Margin}&quot;
                                    Padding=&quot;{TemplateBinding Padding}&quot;
                                    VerticalContentAlignment=&quot;Stretch&quot; /&gt;