Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Announcing a new user group

Dear Slovenian developers and UI enthusiasts, mark your calendars for 8th of November 2011 as that’s the day we’re launching a new user group targeting the UI/UX professionals.

SIUX LogoSIUX – Slovenian UX User Group – a sister user group (or a Siamese twin group as we fondly call it Smile) of now years-running SLODUG, Slovenian Developers User Group (SLODUG), where we’ll focus on technologies and areas like WPF, Silverlight, HTML5, Kinect, Windows Phone, Windows 8; talk through their visual and interaction design aspects; explore user interface examples, usability and related factors.

SLODUG and SIUX will share their members and meeting place. As mentioned, the first, inaugural meeting, will take place on Tuesday, 8th of November 2011, starting at 17h. Two talks are scheduled for the meeting: Developing for XBox Kinect by Sašo Zagoranski and Metro: the UI of the future?  by me. The meeting will take place in Microsoft Lecture room at Šmartinska 140.

Full agenda:

17:00: Intro & announcements
17:15 – 18:00: Developing for XBox Kinect, Sašo Zagoranski / Semantika d.o.o.
18:15 – 19:00: Metro: UI of the future?, Andrej Tozon / ANT Andrej Tozon s.p.
19:00: Discussion over pizza &  beer

We’re also looking for speakers – if you’re interested or  know anybody from the field, please contact me and we’re schedule your talk in one of our next meetings.

Hope to see you!

Until then, you can follow us on Twitter or join our Facebook group.



New Windows Phone App: MapSnapper

My latest Windows Phone application was published to the marketplace a few days ago:

MapSnapper is a simple utility application that utilizes static Bing maps feature to capture a favorite piece of Earth with your Windows Phone.

In its essence, the application lets you navigate a map of the world, using aerial or roads view, zoom in and out until you find  that perfect place you wanted to take a snap of. After taking a snap, the application serves you with not a bitmap image of the snapped location, but the link to a static Bing image that will correspond to the specific view you were looking at when taking a snap. You can specify the dimensions of the final snap and share the link through the email.

MapSnapper_10-10-2011_9.27.36.416   MapSnapper_10-10-2011_9.27.47.822

I developed the application because I needed to get to a number of specific links to certain Bing static images for some other application I’m doing. This application helped me a lot so I decided to make it public. It’s free and you can download it from the Windows Phone marketplace right now!

 

  Get MapSnapper

 

 

Please let me know if you find the application useful.



Windows 8 Metro declarations: User Tile Provider

This blog post is part of my Windows 8 metro-style application declarations series. Read more about declarations in the introductory post about application manifest.

User Tile Provider declaration allows you to register your application as a user tile provider. That means that user will be able to use your application to change her user tile.

One of many ways of changing the user tile can is by clicking your personal tile (avatar) on Windows 8 Start screen – four options are currently displayed, one of them is “Change user tile”:

image

Selecting the first option will take you to Control Panel’s Personalize page, set on User Tile:

image

2 options for changing the tile already available: the user can browse through her pictures and select the one that she likes or she can take a new one with the help of her web cam.

Your own application as a user tile provider

As with other declarations, you declare your application as a user tile provider in the application manifest. The easiest way to do that is through the manifest editor. You’ll see that when you add the User Tile Provider declaration to the Supported Declarations list, there are no declaration specific options to be set.

image

That’s good. After setting the declaration, run or just deploy your application and return to the Control Panel. You should now be looking at something like this:

image

Your application is now registered as the official user tile provider and by clicking on the application tile it will be launched.

And fail.

Of course, there is some wiring you have to do in your code to make this work properly.

Wiring the application logic

There isn’t a special kind of activation reserved for this type of activation, it’s activated through the special Protocol activation - I covered Protocol activation before – if you set up Protocol activation as described in that blog post, you can check for specific protocol in the OnProtocolActivated handler; you’ll see that Uri, passed in through provided arguments, looks something like UserTileProvider://, so you just have to check for a particular protocol to see how or why your application was invoked:

private void OnProtocolActivated(ProtocolActivatedEventArgs args)
{
    if (args.Uri.Scheme == "usertileprovider")
    {
        PhotoView page = new PhotoView();
        page.SetProfileImage();
        Window.Current.Content = page;
        Window.Current.Activate();
        return;
    }

    // ... other protocol handlers
}

Here I’m bringing up a new PhotoView page (also discussed in my previous blog post) whenever my application is invoked for choosing a user tile.

Changing the user tile

OK, so application now responds to the user tile change call. But how do we actually change the tile? Well, there’s an API for that. You can get and set current user tile through asynchronous GetUserImageAsync() and SetUserImageAsync() methods of the UserInformation object.

In my demo application, I get the user tile from her profile, rotate it by 90° and display it to the user:

image

After user taps (selects) the image, she is first prompted for confirmation:

image

And if user confirms that (she can opt out by clicking somewhere outside of the dialog), the new image is set as her new user tile.

image

Quick tip: if you're using your Windows Live ID as your Windows 8 login, changing your user tile will change your general Windows Live display picture as well (in Windows Live Messenger, Live Profile, etc.)

The code for dealing with images is a bit messy – I got it working but I suspect this will get easier as we progress towards the final runtime bits:

Read the user tile, rotate it by 90° and set as the Image source:

public async void SetProfileImage()
{
    StorageFile file = UserInformation.GetUserImage(UserImageKind.LargeBitmap);
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(await file.OpenAsync(FileAccessMode.Read));
    BitmapTransform transform = new BitmapTransform();
    transform.Rotation = BitmapRotation.Clockwise90Degrees;
    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
    WriteableBitmap bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
    pixelStream = bitmap.PixelBuffer.AsStream();
    pixelStream.Seek(0, SeekOrigin.Begin);
    pixelBuffer = pixelData.DetachPixelData();
    pixelStream.Write(pixelBuffer, 0, (int)pixelStream.Length);
    bitmap.Invalidate();

    Viewer.Source = bitmap;
}

Get the image from Image source, save it to a temporary file, set the user tile and delete the temporary file:

private async void SetUserTile()
{
    WriteableBitmap bitmap = Viewer.Source as WriteableBitmap;

    StorageFile file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync("temp");
    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, await file.OpenAsync(FileAccessMode.ReadWrite));
    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 72.0, 72.0, pixelBuffer);
    await encoder.FlushAsync();
    await Windows.System.UserProfile.UserInformation.SetUserImageAsync(file);
    await file.DeleteAsync();
}

Noticed a lot of asynchronous / await calls? Plenty of those in WinRT Winking smile

There’s still many quirks and missing bits around the User Tile Provider declaration implementation, it’s obviously not complete yet. But the ability to provide users with your own application to change their user tiles just feels overwhelming. I bet we’ll get some pretty creative applications in this space when Windows 8 marketplace ships.



Windows 8 Metro declarations: File Type Associations

This blog post is part of my Windows 8 metro-style application declarations series. Read more about declarations in the introductory post about application manifest.

File Type Associations Declaration is very similar to Protocol Declaration. Similar in a way that it defines an OS-wide declaration that’s used to launch your application. What this declaration does should be familiar to most Windows users as it’s been a part of the system from the very beginning.

Every file extension can be associated with a particular application that can handle the content of such file. Most text editors, for example, know how to handle files with .txt extension , file formats like .jpg, .png, and .bmp, are handled by graphics applications like Paint or PhotoShop, etc.

File Type Associations Declaration lets you declare specific file extension(s) that your application will be able to handle. It can be an existing, well-known extension such as .txt, or you can come up with your very own extension and/or file format and register that. For this example, I’ll declare two extensions – .jpg (well-known graphics format extension, and .jpgx – a made up extension that will serve just as an example for this blog post) - my sample application will display the same photo viewer for both extensions.

Setting up the photo viewer page

I’ve created a new blank page in my application and put the Image control on it. That’ll serve as my simple photo viewer.

I’ve also added a method that will help me set the image. The method takes a parameter of type StorageFile, which is a new class in windows runtime that takes care of wrapping file info and does basic file manipulation.

public async void SetPhoto(StorageFile storageFile)
{
    BitmapImage image = new BitmapImage();
    IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
    image.SetSource(stream);
    Viewer.Source = image;
}

The above snippet shows a very basic way to asynchronously open a file. The stream is set as an image source after the file contents are fully read.

Application activation

Similar to Protocol example from my last post, the application is notified when user launches a file with associated extension, but the API behaves a bit differently here. The OnProtocolActivated method is already built into the Application class and you only have to override it in App class derivate to handle the activation. This behavior is most likely to change in one of the future versions of WinRT, but I currently have no idea whether we’ll get a separate method (OnXXXActivated) for each activation kind, or will there be a single method OnActivated, that will provide the activation kind through one of its parameters. Currently, there’s a weird mixture of both approaches.

Here’s how the overridden OnFileActivated method looks like:

protected override void OnFileActivated(FileActivatedEventArgs args)
{
    PhotoView page = new PhotoView();
    page.SetPhoto(args.Files[0] as StorageFile);
    Window.Current.Content = page;
    Window.Current.Activate();
}

Interesting things to note about the provided FileActivatedEventArgs class are:

  • args.Files contains a collection of files that were used in activation. In this example, I’m only using the first one.
  • args.PreviousExecutionState will tell you the state the application was in before activation. It can be either NotRunning, Running, Suspended and Terminated.
  • args.Verb is the action that was used for activating the app. Should be set to Open.

And that’s it for the code. The last thing is setting up the Declaration in the application manifest.

Application Manifest

image

This is the first part of the File Type Association Declaration Page. DisplayName is a localizable string that will be displayed to the user as associated file a handler and the graphics can be changed by specifying a new Logo. Info Tip should contain the text that will be displayed in a tooltip when user hovers a mouse over the application’s associated file extension. Name is a unique name of the association.

Edit Flags specify what type of security prompt will be displayed to the user when she launches the associated file. OpenIsSafe will show a standard warning dialog, while AlwaysUnsafe will display a security warning dialog.

 image

The second part of the Declaration configuration lets you set the supported file types. You can add as many file extensions as you want your application to handle and you can specify an optional content type for each of them. In the above example, extensions .jpg and .jpgx are registered.

Application Settings section lets you configure application’s entry point settings.

Running the application

Run (or just deploy) your application, then launch a .jpg file of your choice that’s on your disk. The following dialog should appear, asking you to select the default application that will handle that file extension in the future:

image

After selecting your app as the default, it should be launched (or activated if already running) and display the image.

Renaming a .jpg file to (previously unassociated extension) .jpgx and launching that, for example, will give you the following dialog:

image

You can check (and change) the default application for each of the file extensions through the Control Panel. Both .jpg and .jpgx are associated with my demo application:

image

Congratulations, you’ve just created your first file extension handling Metro application Smile



Windows 8 Metro declarations: Protocol

I touched on the Metro-style application declarations in my previous blog entry where I wrote about application manifest. I’m continuing the series with exploring the currently available declarations, starting with Protocol. I’ll be using C# Windows Metro style application samples throughout the whole series.

I imagined an application that would respond to the specific URL requests. Let’s say that invoking a URL like “locx://aerial/47.639747~-122.129731” should show me an aerial map, centered to a geographical point of (47.639747, -122.129731).

Displaying a Map

Let’s first figure out how to display the map. There isn’t any native WinRT maps component yet, so the simplest way to display a map is using Bing maps in a WebView Xaml control. WebView is a control that can display HTML, either passed in by string or by navigating to actual web site. Think of it as a very lightweight WebBrowser control, without all the chrome and other clutter.

So I put a WebView control on the MainPage, made sure it fills the whole page and altered its default constructor a bit:

public MainPage()
{
    InitializeComponent();
    WebView.Navigate(new Uri("http://www.bing.com/maps"));
}

Run the application – it should display a nice map of the world. If you have a touch screen, try manipulating the map with your fingers – it' feels nice Winking smile

Metro-style application can be configured to handle any URL protocol

Back to the subject. Open the application manifest configuration screen and navigate to the Declarations tab. Open the Available Declarations dropdown and select Protocol. The protocol will be added to Supported Declarations list box when you click the Add button.

image

Handling declaration properties for Protocol is pretty simple. You’re only required to name the protocol you want your application to handle. For this example, I’m using “locx”.

An optional custom graphics can be used as an application icon whenever the protocol declaration association needs to be displayed to the user (e.g. Control Panel). If not set, application’s Logo image will be used.

Once configured, open App.xaml.cs and override the OnActivated method. This method will get called whenever application is activated. Because an application can be activated for the various reasons, you have to check against the passed arguments for the specific activation kind.

protected override void OnActivated(IActivatedEventArgs args)
{
    if (args.Kind == ActivationKind.Protocol)
    {
        OnProtocolActivated((ProtocolActivatedEventArgs)args);
    }
}

When application is Protocol-activated, the activation arguments should be of the ProtocolActivatedEventArgs type and it should be safe to cast to that. I’ve created the OnProtocolActivated method to handle those cases separately. Note that some other activation scenarios have their equivalent activation methods already built in.

In the OnProtocolActivated method, you’ll have to resolve the Uri that was used for activation. I declared the following Uri format: locx://[view]/[latitude]~[longitude], where view is either roads or aerial. Here’s the method that parses the Uri and calls a specific constructor of the MainPage. That latitude and longitude should be provided using the currently set culture format (commas vs. dots) so they could be parsed into doubles.

private void OnProtocolActivated(ProtocolActivatedEventArgs args)
{
    string type = args.Uri.Host;
    double lat;
    double lng;

    string[] latlng = args.Uri.LocalPath.Substring(1).Split(new[] { "~" }, StringSplitOptions.RemoveEmptyEntries);

    if (latlng.Length != 2 || !double.TryParse(latlng[0], out lat) || !double.TryParse(latlng[1], out lng))
    {
        Exit();
        return;
    }

    Window.Current.Content = new MainPage(type, lat, lng);
    Window.Current.Activate();
}

In overridden MainPage constructor, a Bing maps query is composed and navigated to. Invariant culture is used to convert latitude and longitude to the proper format.

public MainPage(string type, double lat, double lng)
{
    InitializeComponent();
    string uri = string.Format("http://www.bing.com/maps/default.aspx?cp={0}~{1}&lvl=10&style={2}", lat.ToString(CultureInfo.InvariantCulture), lng.ToString(CultureInfo.InvariantCulture), type.ToLower()[0]);
    WebView.Navigate(new Uri(uri));
}

Activation Registration

A very positive thing about activating declarations is that protocol registration will be done when you deploy the application to your computer. That means you don’t need to run the application (as in – the first time) to register the protocol. You can even choose that your application will only support activation and do nothing when launched the ordinary way.

After deploying, you can test your application by invoking the following link from the command line (or Run prompt):

image

image

Of course application will handle any subsequent protocol requests while it’s already running too.

Metro-style application declarations promise a simple integration with the OS through predefined contracts, Protocol is just one of those extensibility points. I’ll look into others in my next posts.