Archive for the ‘Windows 8’ Category

Create Windows 8.1 Store app from blank template using simple MVVM pattern

March 24, 2014 5 comments

Create new project in VS 2013 using “Blank App” template



Make the ViewModel bindable

Add a new directory ViewModels and add a new class BaseViewModel.cs insde this directory with this content inside the namespace:


public class BaseViewModel : INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(String propertyName)
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));

    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        return true;


Download source from here

Add another class file called MainViewModel.cs with this content inside the namespace:

public class MainViewModel : BaseViewModel
    private string firstname = String.Empty;
    public string Firstname
        get { return firstname; }
        set { SetField( ref firstname, value ); }

    private string lastname = String.Empty;
    public string Lastname
        get { return lastname; }
        set { SetField(ref lastname, value); }


This way the properties in MainViewModel will automatically be able to databind in both directions.


Create a singleton for central access to the ViewModel

Now we must find a way to access the ViewModel from every place inside the app.

This can be done using a singleton pattern like this in app.xaml.cs:


private static MainViewModel myMainViewModel = null;
public static MainViewModel MyMainViewModel
        if (myMainViewModel == null)
            myMainViewModel = new MainViewModel();
        return myMainViewModel;


Define the UI

Now add a few controls to Mainpage.xaml.cs (red block)



Setting the DataContext

in Mainpage.xaml.cs inside the ctor:



Please note:

Setting the DataContext in the XAML-file using <Page.Resources> does create a new instance of our MainViewModel class each time we open the MainPage, which is not what we want.

Therefore this statement for setting the DataContext is NOT USED here!

See the section “Adding designtime support..” below!


<!-- Does create a new instance every thime, because it's not using our singleton -->
    <ViewModels:MainViewModel /> NOT USED HERE !!



Saving data when the OS terminates / suspends the app

Now add saving and loading to LocalSettings or RoamingSettings using code like this in the OnSuspend event:


private void OnSuspending(object sender, SuspendingEventArgs e)
    var deferral = e.SuspendingOperation.GetDeferral();
    //TODO: Save application state and stop any background activity
        = Utility.SerializeToString(App.ViewModel);

Helper class for serialization / Deserialization

public static string SerializeToString(object obj)
    XmlSerializer serializer = new XmlSerializer(obj.GetType());
    using (StringWriter writer = new StringWriter())
        serializer.Serialize(writer, obj);
        return writer.ToString();

public static T DeserializeFromString<T>(string xml)
    XmlSerializer deserializer = new XmlSerializer(typeof(T));
    using (StringReader reader = new StringReader(xml))
        return (T)deserializer.Deserialize(reader);




Reload data after app was suspended

Then make sure, that when the program starts up after it was supended through the OS, that it’s loading the last data using code like this in the OnLaunched event:

if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
    //TODO: Load state from previously suspended application
    if (ApplicationData.Current.LocalSettings.Values[Constants.LocalStorage.VIEWMODELDATA] != null)
        var serializedData 
            = ApplicationData.Current.LocalSettings.Values[Constants.LocalStorage.VIEWMODELDATA] as string;
        App.ViewModel = Utility.DeserializeFromString<MainViewModel>(serializedData);



Adding designtime support / Intellisense for binding statements

using Blend:

Open MainPage.xaml in Blend and click on “Set design-time DataContext” in the right lower corner:



Select DesignInstance in the following dialog like this:




Create demo data for design time


Create dummy data in the ctor of the ViewModel and decide whether its running in design mode using:

if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)






Categories: Windows 8.1

Tracing HTTP with Fiddler

October 6, 2012 Leave a comment

Fiddler is a great tool for debugging HTTP traffic between a HTTP client and a HTTP server.

It’s free and can be downloaded from here:

Debugging with localhost

Fiddler is acting as a local proxy and enables itself for all WinInet based communication after startup.

However, there are some things to remember when debugging traffic to and from a local server, because depending on the .NET framework version, proxy usage is disabled in code.

Example: The traffic from this site should be captured: http://localhost/MySite/MyPage.aspx

There are a few workarounds, which should help to solve this situation:

– Use <machinename> instead of localhost ==> http://mymachine/MySite/MyPage.aspx

– Use ipv4.fiddler instead of localhost ==> http://ipv4.fiddler/MySite/MyPage.aspx

– Use ipv6.fiddler instead of localhost ==> http://ipv4.fiddler/MySite/MyPage.aspx

Debugging with IIS 8 Express on Windows 8

There can be even more problems, when using IIS 8 Express on Windows 8.

IIS Express is hardcoded to respond only to requests on localhost.

Therefore ipv4.fiddler does not work in this scenario.

But also this scenario can be solved:

– Use localhost.fiddler instead of localhost ==> http://localhost.fiddler:5057/MySite/MyPage.aspx


Debugging Http traffic to and from immersive / New UI Style apps

Example: When using the new immersive IE, there must be done one more change, because all Win 8 New UI Style apps cannot contact local services by default.

This will work only, if they get an additional server capability, but much better for debugging is to set the app on the excempt list.

Fiddler can help to do this:

image image

This way also the immersive IE browser and every other Windows Store App is able to contact local services via HTTP.

Categories: Debugging, Windows 8

Windows 8 Sharing Contract

September 24, 2012 Leave a comment

Windows 8 Apps support a new type of sharing, which is kind of Clipboard 2.0.

Every app can share data to any other app.

The user is in charge of this sharing, because this enables apps to break out of their sandbox. This looks like this:

User selects an image in the photo app (green), then shares it to e.g. the mail app to send the image via mail.


The sharing target app displays a dialog (red), where the user can add some additional data and then close the dialog to go back to the share source app.

Sharing Source App:

In order to use this sharing contract the share source app must implement this:

private void btnShare_Click_1(object sender, RoutedEventArgs e)
    dtMgr = DataTransferManager.GetForCurrentView();
    dtMgr.DataRequested += dtMgr_DataRequested;

void dtMgr_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
    args.Request.Data.Properties.Title = "Data from Sample Share app";
    args.Request.Data.Properties.Description = "Description from Sample Share app";
    args.Request.Data.Properties.Thumbnail = 
                new Uri("ms-appx:///Assets/SharingIcon.png"));

    // Share Text data

    // Share Uri data
    args.Request.Data.SetUri(new Uri(txtUri.Text));


Sharing Target app:

The sharing target app needs a little bit more effort:

First, a new XAML Page of type "Share Target Contract" must be added.

When you add this page, then the wizard will also take care of adding the declaration "Share Target" to the Package.appxmanifest.

If you use any other page, then this must be done manually!

The declaration does also define, which type of data will be accepted for sharing, which can be any of the default formats in Windows.ApplicationModel.DataTransfer.StandardDataFormats, but also any custom data format

The dialog looks like this:


The wizard does also add the overload function OnShareTargetActivated to App.xaml.cs, which must be done manually, if some other XAML page will be added as target page.


/// <summary>
/// Invoked when the application is activated as the target of a sharing operation.
/// </summary>
/// <param name="args">Details about the activation request.</param>
protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
    var shareTargetPage = new ShareTargetPage();



When using any other XAML page as target page, then make sure, to add the statement


to the top of the target page and make sure, that the UI is 645 px in width.

The header will always be displayed by the system and will take about 80 px in height.

Example for a sharing target page:



The sharing target page must include a function called Activate(), which will deliver the data from the source application, after the user has selected the target app.

args.ShareOperation does contain the data from the source app or allows to fetch data from the source app using e.g. Data.GetTextAsync(), Data.GetUriAsync(),….

After the app is finished with the shared data, it must report back to the source app.

Also this is done on top of the ShareOperation using ReportCompleted()

Optionally the app can return a so called quicklink, which will add a new entry to the share target list and allow the user to select the same target parameters very quickly the next time.

The mail app e.g does remember the last recipient and adds a quicklink to the target selection list.

Example where the list of quick links is marked in red:



/// <summary>
/// Invoked when another application wants to share content through this application.
/// </summary>
/// <param name="args">Activation data used to coordinate the process with Windows.</param>
public async void Activate(ShareTargetActivatedEventArgs args)
    this.shareOperation = args.ShareOperation;

    // Communicate metadata about the shared content through the view model
    var shareData = this.shareOperation.Data;
    var shareDataProperties = shareData.Properties;

    txtStatus.Text = "AppName: " + shareDataProperties.ApplicationName + 
                     "\nTitle: " + shareDataProperties.Title + "\n" +
                     "\nDescription: " + shareDataProperties.Description + 
                     "\nQuicklink: " + shareOperation.QuickLinkId + 
                     "\nAvailable Formats: ";

    for (int i = 0; i < shareData.AvailableFormats.Count; i++)
        txtStatus.Text += "\n - " + shareData.AvailableFormats[i];

    if (this.shareOperation.Data.Contains(StandardDataFormats.Uri))
        txtStatus.Text += "\n\n";
        Uri uri = await this.shareOperation.Data.GetUriAsync();
        if (uri != null)
            txtStatus.Text += "\nUri: " + uri.AbsoluteUri + Environment.NewLine;

    if (this.shareOperation.Data.Contains(StandardDataFormats.Text))
        txtStatus.Text += "\n\n";
        string text = await this.shareOperation.Data.GetTextAsync();
        if (text != null)
            txtStatus.Text += "\nText: " + text + Environment.NewLine;

    if (this.shareOperation.Data.Contains(StandardDataFormats.StorageItems))
        txtStatus.Text += "\n\n";
        IReadOnlyList<IStorageItem> storageItems = null;
        storageItems = await this.shareOperation.Data.GetStorageItemsAsync();
        string fileList = String.Empty;
        for (int index = 0; index < storageItems.Count; index++)
            fileList += storageItems[index].Name;
            if (index < storageItems.Count - 1)
                fileList += ", ";

        txtStatus.Text += "StorageItems: " + fileList + Environment.NewLine;

    if (this.shareOperation.Data.Contains(StandardDataFormats.Html))
        txtStatus.Text += "\n\n";
        string htmlFormat = await this.shareOperation.Data.GetHtmlFormatAsync();
        string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);

        txtStatus.Text += "HTML: " + Environment.NewLine;
        this.MyWebView.Visibility = Visibility.Visible;
        this.MyWebView.NavigateToString("<html><body>" + htmlFragment + "</body></html>");
    if (this.shareOperation.Data.Contains(StandardDataFormats.Bitmap))
        txtStatus.Text += "\n\n";
        this.MyIMageLabel.Visibility = Visibility.Visible;
        MyImage.Visibility = Visibility.Visible;
        IRandomAccessStreamReference imageReceived = 
            await this.shareOperation.Data.GetBitmapAsync();
        IRandomAccessStreamWithContentType stream = 
            await imageReceived.OpenReadAsync();

        BitmapImage bitmapImage = new BitmapImage();
        MyImage.Source = bitmapImage;

    Window.Current.Content = this;

private async void btnShare_Click_1(object sender, RoutedEventArgs e)
    QuickLink ql = new QuickLink()
        Id = "HS42",
        Title = "MyQuicklink",
        SupportedFileTypes = { ".txt", ".jpg", ".bmp", ".gif", 
                               ".docx", ".pptx", ".xlsx", ".pdf", 
                               ".wmv", ".mp3", ".mp4", ".wma" },
        SupportedDataFormats = { StandardDataFormats.Text, 
                                 StandardDataFormats.StorageItems }
    StorageFile iconFile = await Windows.ApplicationModel.Package.Current
        .CreateFileAsync("Assets\\Quicklink.png", CreationCollisionOption.OpenIfExists) 
        as StorageFile;
    ql.Thumbnail = RandomAccessStreamReference.CreateFromFile(iconFile);




Categories: Metro, Windows 8

Windows 8 Theme changing between dark and light

September 23, 2012 Leave a comment

The new UI Style Windows 8 apps support a dark and light theme, which cannot be changed during runtime.

The developer can set it either in code, which must be very early during startup like in the App ctor:


public App()
    Application.Current.RequestedTheme = ApplicationTheme.Light; 


or directly in App.xaml like this:




The Visual Studio designer preview also supports themes. They can be set in the Devices toolbar:



If there should be other values used for the different color settings, then you can add this settings to StandardStyles.xaml

<SolidColorBrush x:Key="ApplicationPageBackgroundThemeBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="ApplicationForegroundThemeBrush" Color="#333333"/>
<SolidColorBrush x:Key="ApplicationSecondaryForegroundThemeBrush" Color="#FF991100"/>
<SolidColorBrush x:Key="ApplicationPointerOverForegroundThemeBrush" Color="#AAAAAA"/>
<SolidColorBrush x:Key="BackButtonBackgroundThemeBrush" Color="#00000000"/>
<SolidColorBrush x:Key="BackButtonForegroundThemeBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="BackButtonPressedBackgroundThemeBrush" Color="#00000000"/>
<SolidColorBrush x:Key="BackButtonPressedForegroundThemeBrush" Color="#CCCCCC"/>
<SolidColorBrush x:Key="BackButtonPointerOverBackgroundThemeBrush" Color="#00000000"/>



Categories: Metro, Windows 8

Windows 8 Lockscreen app

September 18, 2012 Leave a comment

In the new app lifecycle model, all apps, which are not currently in use by the user will be terminated after 10 seconds in the background. This helps to preserve system resources like CPU cycles and battery life. However there are some cases, when apps should run in the background, even if there is no UI visible for the user.

There are different types of scenarios possible and the WinRT library has solutions for this scenarios, which i’ll describe in another post.

There is one special scenario for so called lockscreen apps.

When the user has locked his PC, then certain apps can still interact with the lockscreen and display some status information there.

Only the user can decide, which apps should be visible and active in the lockscreen and the number of apps is limited to seven plus one app for detailed information.

This app can update its tile, all others can only update the badge data. The user defines, which app are on the lockscreen and which single app can update the tile with a detailed status. For this, open the "Personalize" tab in the "Change PC settings" app.



All this apps are then visible in the red marked area in the lockscreen picture below.

The logo and the badge data, which can be a number from 1 to 99 or a symbol from here can be displayed.

The single app, which is able to display detailed information will be shown inside the yellow frame.

It can display tile data in any of this formats, which must be a wide template (2x)



Not every app can be used as lockscreen app. The apps must follow this pattern:

  • Add a badge logo with 24×24 pixel in png format to the Assets folder of the project
  • Add a wide logo with 310 x 150 pixel in png format to the Assets folder
  • Open Package.appxmanifest and select the badge and wide logo
  • Set Lock screen notification to "Badge" or "Badge and Tile text"


A red error logo will remind you, that you must add a background task for this kind of application. This can be done through the Declarations Tab in Package.appxmanifest

  • Select "Baxckground Tasks" from the dropdown and add it to the list.
  • Enter the fully qualified classname into the textbox labeled "Entry point"


On Startup we need to ask, whether the app is allowed to run as lockscreen app.

We can do this e.g. in the OnNavigatedTo() method of the MainPage:

protected async override void OnNavigatedTo(NavigationEventArgs e)
    BackgroundAccessStatus backgroundStatus = 
              await BackgroundExecutionManager.RequestAccessAsync();
    lblStatus.Text = backgroundStatus.ToString();



The user will get this question on the first startup of this app:



If the user allows to run the app in the background, then it will be added to one of the seven lockscreen slots, which can be customize by the user through opening "Personalize" tab from the "Change PC settings" app.

The app will the display one of this states from BackGroundAccessStatus enum:

public enum BackgroundAccessStatus
    // Summary:
    //     The user has not selected "allow" or "don't allow" or
    //     dismissed the dialog without making a choice.
    //     The app cannot perform background activity
    Unspecified = 0,
    // Summary:
    //     The user chose "allow" in the dialog box. 
    //     The app is added to the lock screen,
    //     can set up background tasks, and, if it has the capability, 
    //     can use the real-time connectivity (RTC) broker. 
    //     This means that the app can function while the
    //     device is in the connected standby state.
    AllowedWithAlwaysOnRealTimeConnectivity = 1,
    // Summary:
    //     The user chose "allow" in the dialog box. 
    //     The app is added to the lock screen
    //     and can set up background tasks, 
    //     but it cannot use the real-time connectivity (RTC) broker. 
    //     This means that the app might not function while the device
    //     is in connected standby.
    //     Note that apps that do not specify RTC in their manifest
    //     will always demonstrate this behavior.
    AllowedMayUseActiveRealTimeConnectivity = 2,
    // Summary:
    //     The user chose "don't allow" in the dialog box. 
    //     The app is not added to the
    //     lock screen.After this value has been returned, 
    //     subsequent calls to the RequestAccessAsync method do not present 
    //     the dialog box to the user. They have stated their
    //     preference and it should be honored.
    Denied = 3,

When the app is running, it can update badge data using this code:

private void UpdateBadgeData(string badgeMessage)
    XmlDocument xmlDoc = 

    // using BadgeTemplateType.BadgeNumber or .BadgeGlyph will return:
    //<badge value=""/>

    var node = xmlDoc.SelectSingleNode("/badge");
    node.Attributes[0].NodeValue = badgeMessage;

    BadgeNotification badgeNotification = new BadgeNotification(xmlDoc);
    lblStatus.Text = "Set new badge data to Lockscreen!";


Updating the tile data must take into account, that the logo can be either small or wide.

If the app is on the lockscreen, then its always using the wide tile template, but on the regular start screen, the user can decicde which size should be used.

So both XML-templates must be contained in the update data. The code looks like this:

private void btnSendTile_Click_1(object sender, RoutedEventArgs e)
    //XmlDocument xmlDoc = 
    //   TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideBlockAndText01);

    string template = String.Format("<tile>" + 
    " <visual>" +
    "   <binding template='TileSquareText01'>" +
    "      <text id='1'>{0}</text>" +
    "      <text id='2'>{1}</text>" +
    "   </binding>" +
    "   <binding template='TileWideText01'>" +
              "<text id='1'>{0}</text>" +
              "<text id='2'>{1}</text>" +
    "   </binding>" +
    " </visual>" +
    "</tile>", DateTime.Now.Second.ToString(), txtMessage.Text);
    XmlDocument xmlDoc = new XmlDocument();

    TileNotification tileNotification = new TileNotification(xmlDoc);
    TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
    lblStatus.Text = "Set new Tile logo!";




Categories: Metro, Windows 8

Windows 8 Supporting Snapped view and other views

September 10, 2012 Leave a comment

Windows 8 New UI Style apps are always fullscreen. Except for some special cases, which i’ll discuss here.

If the screen resolution is at least 1366 px in width, then the so called "Snapped View" can be used. To bring a app into snapped view, the user can drag the app from the top to left or right side of the screen, where the app will then snap.

The rest of the screen can be used from another app, which can be either any app from the store or any classic desktop app, even the desktop itself.

This feature is meant for having two applications side by side. Example for this would be the weather app (red), which can be arranged next to the mail app.



The "Snapped" view is defined as 320px in width and the total height of the screen. It can be either placed on the right or on the left side.

The rest of the screen is then called "Filled" view, which is total width – 320 px

And then there is the default view, called "FullscreenLandscape" view and if the device supports rotation, then there is the last view, called  "FullscreenPortrait"

Windows 8 UI certification guidelines require, that at least "Snapped" view is supported, which does not mean, there must be functionality. It would be good enough to display the app logo, just it should look nice and professional.

But even better is, if the app can provide real value in this view. That’s pretty much depending on the app and its usage scenario, but here i’ll show how to switch between theses views.

The real switching is of course done by the user. The app must then act on the users decission and provide the best possible view of its data.

In this example i’ll just use a very primitive UI, which will show how to handle the different view switches.

For this i’ve used the minimalistic app from here and added 4 StackPanels, each for one of the 4 views:


All but the first StackPanel’s are hidden using Visibility="collapsed" attribute.

Each StackPanel does have a unique color and some text, so that it’s easy to see, which one is active. The idea is, that every view does have his own StackPanel and all other Stackpanels are hidden. This change of visibility can be easily done using the VisualStateManager feature, which allows to declaratively define the visibility and lots of other things depending on the view.

We could do this all by hand, but it’s rather annoying and much better to do this in Blend. So let’s open this page in Blend using right click on the MainPage.xaml and select "Open in Blend". This will show the page in Blend like this:

(Make sure, so switch the Window mode to animation using the menu


At the left bottom, we can see all possible views.

Now lets define the visibility changes for each of this views:

Click on Filled, then open the Grid next to the right, so that this will be shown:


When Filled view is active, then we want to make two changes:
– Hide the StackPanelFullscreen

– Show the StackPanelFilled

For this we first select the StackPanelFullscreen, then go to the top right edge of Blend, type in vi to filter for all properties starting with vi and then change the Visibility to Collapsed:


Then we click on StackPanelFilled and set its visibility to visible.

Now we repeat this steps for the view "FullScreenPortrait" and then do the same for the other views.

After this, stop recording by clicking on the top left edge of Blend:



Now Save and go back to Visual Studio, let it reload the changed files and test the application. Now each view should display a different color and text.

image image imageimage

All the magic in Blend is saved into the <VuslaStateManager.VisualStateGroups> section in XAML, where it’s now easy to understand…?

It defines per state all property changes against the default UI definition above


Categories: Metro, Windows 8

Windows 8 ApplicationSettings

September 10, 2012 Leave a comment

Every Windows 8 New UI Style App is sandboxed and by default cannot access the users filesystem.

The only locations where file access is possible, are below the install location of the app itself.

The install location can be fetched using this API:



But this location is read only!

There are other locations for storing application data, local settings and roaming settings.

Roaming settings will be synced automatically to your Microsoft account and will be available on another machine when you log into this machine using the same account and start using the app there.

Syncing is not in realtime, in can take a few seconds. There is one special key, which can be used for a single setting or a composite setting. The special keyname must be "HighPriority". All settings behind this key will be synced with higher priority. This high priority setting can be a maximum of 4kb.

The maximum total size roaming settings (currently 100 kb) can be fetched using


This locations can be accessed using this API’s:

void DemoSettingsApi()
    // Get RoamingStorage Quota
    ulong roamingQuotaInKB = ApplicationData.Current.RoamingStorageQuota;

    // Write local setting
    ApplicationData.Current.LocalSettings.Values["key1"] = txtlocalKey1.Text;
    // Read local setting
    if (ApplicationData.Current.LocalSettings.Values["key1"] != null)
        txtlocalKey1.Text = 

    // Write roaming setting
    ApplicationData.Current.RoamingSettings.Values["key1"] = txtlocalKey1.Text;

    // Read roaming setting
    if (ApplicationData.Current.RoamingSettings.Values["key1"] != null)
        txtRoamingKey1.Text = 

    // Write composite setting
    int zip = 0;
    Int32.TryParse(txtZipCode.Text, out zip);
    Customer c = new Customer() 
        FirstName = txtCustomerFirstname.Text, 
        LastName = txtCustomerLastname.Text, 
        ZipCode = zip 

    ApplicationDataCompositeValue comp = new ApplicationDataCompositeValue();
    comp["LastName"] = c.LastName;
    comp["FirstName"] = c.FirstName;
    comp["ZipCode"] = c.ZipCode;
    ApplicationData.Current.LocalSettings.Values["CurrentCustomer"] = comp;

    // Read composite setting
    if (ApplicationData.Current.LocalSettings.Values["CurrentCustomer"] != null)
        ApplicationDataCompositeValue comp2 = 
            ApplicationData.Current.LocalSettings.Values["CurrentCustomer"] as ApplicationDataCompositeValue;
        txtCustomerLastname.Text = comp2["LastName"] as string;
        txtCustomerFirstname.Text = comp2["FirstName"] as string;
        int? zipCode = comp2["ZipCode"] as int?;
        txtZipCode.Text = zipCode.ToString();




Categories: Metro, Windows 8