1. Your Metro-style app needs protection and here is why
2. Simplest approach to protecting advertisements in your Windows 8 app
3. Preventing unauthorized modifications of XAML files in Windows 8 apps with XamlIntegRT

Here is a screenshot of app running on my tablet:

App with advertisements

And here is the same app a couple of minutes later:

App without advertisements

What’s happened? Where is Gears of War Ad?

As I posted before, app assemblies, non-compiled XAML and html pages are easily accessible for users. Windows 8 RTM doesn’t bring anything new for apps protection. Neither special knowledge nor tools are required to open app’s package in WindowsApps folder, find .xaml page with advertisements and remove AdControl elements. Your grandma can do it between backing a cake and knitting socks given good instruction.

Even more, I spent just ten extra minutes and created a tool that automatically scans all installed Windows 8 apps and removes all Ad controls.

How can this simple hack be avoided? Probably the easiest solution is to create AdControl in code behind:


var adControl = new AdControl 
       {
          ApplicationId = "test_client", 
          AdUnitId = "Image_300x250"
       };

adControl.SetValue(WidthProperty, 300);
adControl.SetValue(HeightProperty, 250);
            
AdGrid.Children.Add(adControl);

Discovering data formats supported by Windows 8 share contract target apps

Windows 8 apps run in sandboxed environment where all direct communications between apps are prohibited. Instead, Windows 8 provides several mechanisms to facilitate indirect communications – protocols, file type associations and share contracts.

All these mechanisms allow transferring data between independent apps – in most of the cases developers don’t care about data source or destination. However, occasionally there is a need to support communications with a particular app. In this case all protocols, associations and contracts supported by target app need to be identified.

Declared protocols and file type associations can be determined through Control Panel:

Set Program Associations

Unfortunately, Windows 8 does not provide any UI to discover share targets’ data formats. The only way is to go through manifest files for the installed apps and search for data format declarations. Some of these files are not well formatted so I decided to automate the task and created a small utility, AppXplorer:

AppXplorer

This application lists all the installed apps and allows discovering supported protocols, file type associations, shareable data formats and file types.

You can download compiled executable or build it by yourself from source code (.NET 4.5/WPF).

New in Windows 8 RTM: out of the box implementation of in-app type-to-search feature

Search is one of the key features of Windows 8 and can be invoked at any time using Search charm. Additionally, Start screen behaves similar to Windows 7 Start menu and starts searching when user typed something. Like in Windows 7, you can press Windows key, type something and the search results will immediately appear on the screen. It’s a nice feature and some apps can benefit from this approach too.

While you can implement type-to-search scenario in your app by yourself (by catching KeyPress and invoking Search pane), Windows 8 RTM provides standard implementation for this scenario:


SearchPane.GetForCurrentView().ShowOnKeyboardInput = true;

That’s it. By setting this property you instruct system to automatically route all keystrokes to Search, so the current view behaves similar to Start screen.

It is important to understand, that system will intercept every key press. Even if active view contains an EditBox and this EditBox is in focus, all entered characters will be routed to Search pane and the EditBox will stay empty.

Value of ShowOnKeyboardInput can be set at any time and you can switch on / switch off search functionality over and over again.

Extending WinRT: how to avoid constrains and expose C# objects hierarchy from WinMD library

Windows 8 programming model allows extending WinRT by implementing WinRT components. These components can be created by using any supported language (JS, C#, VB, C++) and can be consumed by all these languages as well.

Visual Studio provides WinRT library project template, thus creation of your first WinRT component is matter of seconds. Gradually, you will find that your code should follow some rules to stay compatible with WinRT. Most of these rules are not deal breaker, but sometimes they can make you scratch your head a bit.

For example, one of the rules for C# states that all public classes (except XAML controls) must be sealed and custom WinRT-enabled class cannot be inherited from another custom WinRT class. But what can be done to expose a complex hierarchy of objects via WinRT?

Here is the solution. Unlike for classes, inheritance is allowed for public interfaces. At the same time there are no restrictions for private classes, so a combination of public interfaces and hierarchy of private classes can be used.

To demonstrate this approach I will use hierarchy of three classes – Publication (base class), Book and Magazine (are derived from Publication).

First, I need to introduce interfaces:


public interface IPublication
{
   string Publisher { get; set; }
   string Name { get; set; }
}

public interface IBook : IPublication
{
   string Author { get; set; }
}

public interface IMagazine : IPublication
{
   string Category { get; set; }
}

Then I can implement these interfaces (note that classes are private):


class Publication : IPublication
{
   public string Publisher { get; set; }
   public string Name { get; set; }
   // ...
}

class Book : Publication, IBook
{
   public string Author { get; set; }
   // ...
}

class Magazine : Publication, IMagazine
{
   public string Category { get; set; }
   // ...
}

But now my WinRT library exposes only interfaces and I need to provide some mechanism to instantiate objects that implement these interfaces. For example PublicationFactory:


public sealed class PublicationFactory
{
   public IBook CreateBook()
   {
      return new Book();
   }

   public IMagazine CreateMagazine()
   {
      return new Magazine();
   }
}

As the result I have WinRT library that exposes structured hierarchy of classes and allows Metro-style apps using this library to take all the advantages of object oriented design.

Download sample project - WinRTLibrary.zip

Share contract and custom data. Do you need a reference implementation for schema.org formats?

Windows 8 style apps can use contracts to interact with each other. For example Share contract allows sharing of various data between totally independent apps. As long as app follows Share target contract it can receive text, HTML, links, files, images and custom data. For source apps sharing data in the standard formats is pretty straight forward – DataPackage class provides corresponding functions SetText(), SetUri(), etc. All what you need is to call function and target app will get the data.

Custom data is a different story.

DataPackage.SetData() accepts two parameters – format id and data object. You can use your own “my-super-data” format id but nobody knows about this format and no one application will be able to receive your shared data. That’s why Microsoft suggests using for data sharing formats defined by schema.org (e.g. http://schema.org/Book) – by doing this you can be sure that at least some of apps will know about your package format. But still there is a problem - schema.org format definitions allow multiple implementations. For example book information can be represented using xml or JSON and both packages will be valid according to the Book schema definition. That means the situation when two apps support the same format but are not able to actually share data is quite possible.

One of the ways to solve the problem is to have a commonly used library to represent data packages in uniform way. How it could looks like in code?

Source app, JS


function dataRequested(e) {
   var request = e.request;

   var book = Transhipment.SchemaFactory.create(Transhipment.Schema.book);
   book.name = "The Catcher in the Rye";
   book.image = "http://sourceurl.com/catcher-in-the-rye-book-cover.jpg";

   request.data.properties.title = "Sample book";
   request.data.properties.description = book.name;
   request.data.setData(book.type, book.stringify());
}

Target app, C#


public async void Activate(ShareTargetActivatedEventArgs args)
{
   var data = await args.ShareOperation.Data.GetDataAsync(Schema.Book);
   if (data != null)
   {
      var book = SchemaFactory.Parse(data.ToString()) as IBook;
      if (book != null)
      {
         DefaultViewModel["BookName"] = book.Name;
         DefaultViewModel["BookgImage"] = book.Image;
      }
   }
}

How it looks like without using such library: MSDN - Using schema-based formats.

I already have some bits that I coded to verify the idea and here the question.

Let me know your opinion.

Windows 8 Camp is over. What’s next?

Last week I had a chance to speak at Windows 8 Camp hosted by Canada’s Technology Triangle .NET User Group. In this post I’d like to share some useful links to help attendees to learn more about Windows 8 app development.

Start by downloading Windows 8 Camp in a Box. This download contains two self-extracting archives with presentations and JavaScript and C# versions of hands-on labs from the camps.

Camp’s resources provide great introduction to Windows 8 development but if you need more information please visit dev.windows.com. This portal contains tons of materials related to Windows 8 app development including:

If you have a question but cannot find an answer in the documentation, you can always get advice in one of the developer forums.

Do you have your great app ready? It’s time to publish it – send app description to Win8CDN@Microsoft.com (if you are based in Canada, otherwise contact your local DPE evangelist) to schedule the app review. This is your chance to discuss the app with a Microsoft Service Engineer, to run it through the series of quality tests and to get a token that will let you register a Windows Store developer account.

Don’t forget to stay connected to get the latest Windows 8 news and feel free to contact me with your questions on Windows 8 app development.

Mixing themes in XAML Metro apps

For Metro-style apps created using XAML, Windows 8 SDK provides three predefined themes - light, dark and high contrast.

Two of three themes – light and dark - can be selected programmatically by assigning Application.RequestedTheme property:


<Application
    x:Class="GridAppTest.App"
    RequestedTheme="Light"
    ...

High contrast theme automatically activated by Windows once corresponding option is selected in Control Panel.

Predefined themes provide look and feel for standard controls only but if you have some custom controls you can extend themes:


<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Default">
                <SolidColorBrush x:Key="TestControlBackground">#FF000000</SolidColorBrush>
            </ResourceDictionary>
            <ResourceDictionary x:Key="Light">
                <SolidColorBrush x:Key="TestControlBackground">#FFDEDEDE</SolidColorBrush>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Common/StandardStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Developing my apps, I found that pure themes are rarely used. For example I tend to have dark themed main UI and light input pages. WinRT does not provide mechanism to apply themes to individual pages, so by default such mixed UI will looks similar to the following screenshot:

All controls are invisible. Fortunately we work with XAML and there is an obvious solution – to re-style controls. But I am lazy and don’t want to type style name every time I need to add control to UI. Also I always use input controls on a light background so I don’t even need two different styles. In this case a different approach can be used.

Let’s modify buttons to make them visible on white background when dark theme is switched on.

First, open C:\Program Files (x86)\Windows Kits\8.0\Include\winrt\xaml\design\themeresources.xaml and search for “Light” ResourceDictionary declaration.

Than copy all SolidColorBrush object definitions associated with buttons


<SolidColorBrush x:Key="ButtonBackgroundThemeBrush" Color="#B3B6B6B6" />
<SolidColorBrush x:Key="ButtonBorderThemeBrush" Color="#33000000" />
<SolidColorBrush x:Key="ButtonDisabledBackgroundThemeBrush" Color="#66CACACA" />
<SolidColorBrush x:Key="ButtonDisabledBorderThemeBrush" Color="#1A000000" />
<SolidColorBrush x:Key="ButtonDisabledForegroundThemeBrush" Color="#66000000" />
<SolidColorBrush x:Key="ButtonForegroundThemeBrush" Color="#FF000000" />
<SolidColorBrush x:Key="ButtonPointerOverBackgroundThemeBrush" Color="#D1CDCDCD" />
<SolidColorBrush x:Key="ButtonPointerOverForegroundThemeBrush" Color="#FF000000" />
<SolidColorBrush x:Key="ButtonPressedBackgroundThemeBrush" Color="#FF000000" />
<SolidColorBrush x:Key="ButtonPressedForegroundThemeBrush" Color="#FFFFFFFF" />

And finally paste all the brushes into your resource dictionary. You can repeat it for other controls to achieve result similar to the following:

Of cause it will work only if all your controls are used with the same background. Otherwise, you have no other choice but to re-style controls.

Your Metro-style app needs protection and here is why

1. Your Metro-style app needs protection and here is why
2. Simplest approach to protecting advertisements in your Windows 8 app
3. Preventing unauthorized modifications of XAML files in Windows 8 apps with XamlIntegRT

With the introduction of Windows Store, capabilities and sandboxed execution environment for apps Windows 8 provides good virus, malware and spyware protection for users.

On the other hand, commercial software developers want to protect their product from unlicensed use, unauthorized copying and stealing of the intellectual property. Windows Store resolves some of these concerns, but is it enough for developers?

When user installs the new application, the app package goes to a special folder - C:\Program Files\WindowsApps\ and if you will try to open this folder you will see the following message:

It looks good so far. I don’t want anybody to have access to my app package and access denial is exactly what I expected. But what if I start cmd.exe as an Administrator and go to the same WindowsApps folder? All apps are now available for me:

Does not look like a big deal - users had access to application files for decades. But there is a difference between native Windows application or even WPF application and WinRT app. Let’s go one folder deeper:

In addition to executable file and assemblies, the folder contains non-compiled XAML pages and all the resources, including images and data files belonging to the project. This could be good for the developers who learn XAML, but app’s developers may disagree.

So, the resource files that can contain proprietary data or intellectual property can be easily accessed and used independently from the app. I hope it will be fixed before the Windows 8 release but for now you need to be aware of this fact and should think about the data protection.

File system places accessible through WinRT API

In the previous posts I described the restrictions in file system access dictated by Windows 8 for WinRT apps. With user’s help and by using file and folder pickers your app can get an access to any file system object, but there is a limited number of folders accessible for the app via direct API calls. Here I want to summarize information about these folders.

Local app data

Local data folder allows you to store any application-related files. The folder is private and isolated so any other Metro apps are not allowed to access the stored files.

The folder will be completely erased if the app is uninstalled.


// C#
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

// XAML
<Image Source="ms-appdata:///local/myFile.png"/>

Roaming app data

Roaming folder provides you a way to store the files and synchronize them across multiple systems associated with the same Live ID (Microsoft Account).

Roaming folder size is limited and can be determined by using ApplicationData.Current.RoamingStorageQuota and ApplicationData.Current.RoamingStorageUsage variables. If folder size exceeds the quota, Windows suspends data synchronization.


// C#
StorageFolder roamingFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;

// XAML
<Image Source="ms-appdata:///roaming/myFile.png"/>

Temporary app data

Temporary folder can be used to store the app’s temporary data.

Files stored in the folder can be removed at any time by system or by user via Disk Cleanup.


// C#
StorageFolder tempFolder = Windows.Storage.ApplicationData.Current.TemporaryFolder;

// XAML
<Image Source="ms-appdata:///temp/myFile.png"/>

App installed location

Metro-style apps can access all the files included in the package and installed to the target system.


// C#
StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

// XAML
<Image Source="ms-appx:///myFile.png"/>

Downloads folder

User’s Downloads folder is available for your app if you need to save downloaded files.

This folder is available in write-only mode. Your app can use it to save files but it is not able to read the files downloaded by other apps.


StorageFolder tempFolder = Windows.Storage.DownloadsFolder;

Documents library

User’s documents folder.

To be able to access this folder you need to specify Document Library capability in the app’s manifest. Additionally, File Type Association must be declared for the each document type that will be accessed by the app.


StorageFolder folder = Windows.Storage.KnownFolders.DocumentsLibrary;

Music library

User’s music folder.

To be able to access this folder you need to specify Music Library capability in the app’s manifest.


StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;

Pictures library

User’s pictures folder.

To be able to access this folder you need to specify Pictures Library capability in the app’s manifest.


StorageFolder folder = Windows.Storage.KnownFolders.PicturesLibrary;

Videos library

User’s videos folder.

To be able to access this folder you need to specify Videos Library capability in the app’s manifest.


StorageFolder folder = Windows.Storage.KnownFolders.VideosLibrary;

Removable devices

WinRT provides access to files and folder located at the removable devices such as USB sticks and external hard drives using RemovableDevices folder.

To be able to access this folder you need to specify Removable Storage capability in the app’s manifest. Additionally, File Type Association must be declared for the each file type that will be accessed by the app.


StorageFolder folder = Windows.Storage.KnownFolders.RemovableDevices;

See also Working with external storage devices from Windows 8 apps

Home group

HomeGroup folder allows you to access files and folders shared by other home computers.

Your application must to declare at least one library access capability (Pictures, Music or Videos) to be able to use this location. Shared Documents Libraries are not available for the Metro apps even if the corresponding capability is declared in the manifest.


StorageFolder folder = Windows.Storage.KnownFolders.HomeGroup;

Media Server devices

MediaServerDevices folder allows you to access files and folders shared by network media servers.

Your application must to declare at least one library access capability (Pictures, Music or Videos) to be able to use this location. Shared Documents Libraries are not available for the apps even if the corresponding capability is declared in the manifest.


StorageFolder folder = Windows.Storage.KnownFolders.MediaServerDevices;

Converting WordPress blog into statically generated site with help of Pretzel

WordPress is a good blogging engine and I was satisfied with it until a moment when I decided to have my own theme applied uniformly across the site. And here I decided to try something new, for example static site generation.

One is the most popular static site generators is Jekyll. It is a Ruby-based tool that accepts markdown text files and transforms them into HTML pages through liquid templating engine. As a result of running Jekyll on your local system you will have a fully generated site composed from static HTML pages that can be hosted in any environment. Such site does not require powerful system to be executed, can be easily migrated from host to host and is version control friendly.

If .NET environment is more familiar for you, you can try Pretzel – a C#-based project inspired by Jekyll. Pretzel is a command line utility that can prepare a site skeleton, compiles it and helps you to test the site before uploading it to the host.

First what you need to do for the new site is to prepare site structure. Pretzel supports two templating engines – liquid and Razor – and, for example, to create a site that will use Razor you need to execute

Pretzel.exe create site_name -t=razor

It will create a default site with sample data. For the default site Pretzel generates four folders and five files:

If you will open any generated post or any page file, in the beginning of all these files you will see a similar section. This is a YAML front matter block – it is used to initialize predefined variables or to pass your custom data to the templating engine.

One of the most important variables is a layout – it defines what layout should be used to generate this page. Pretzel is trying to stay compatible with Jekyll and you can check Jekyll documentation to see what additional variables are available.

Now you can compile the site with

Pretzel.exe bake site_name

During compilation Pretzel goes through all the files in your site folder and transforms them. First all .md files are translated into HTML. After that Pretzel combines all HTML files with layouts to get the pages. And finally it copies all non-transformable files like images or CSS into the output folder. If you already tried to compile the site you will see _site folder – this is a compiled representation of your site. And now is time to test the newly created site

Pretzel.exe taste site_name -p=7878

Migration WordPress blog to Pretzel

Site generated by Pretzel is fully static and if you use standard WP commenting system you will need to switch to some third party commenting engine. It could be IntenseDebate, Disqus or Facebook plugin – it’s up to you. Switching to Disquis is easy and painful, just install WP Disqus plugin and follow the instructions and all the comments will automatically migrated.

Next you need to export your current blog posts from WordPress dashboard. Use generated file to import the posts to you new site:

Pretzel.exe import -i=wordpress -d=site_name -f=WPExport.xml

Import function does not create site – you need to create a site and import the post afterwards. After that you can create your layouts and associate them with the posts.

Tips & tricks

Partial views

Razor template engine supports partial views. You can put .cshtml or .html files in _includes folder and reuse them with help of @@Include("include_name")

URLs

Most likely you want to keep your post’s and page’s URLs. The default schema is different from the one used by WordPress but you can control it using permalink parameter in YAML front matter. For example

permalink: /blog/:year/:month/:day/:title/index.html in 2012-04-19-atdd.md

will instruct Pretzel to generate /blog/2012/04/19/atdd/index.html that is identical to post’s URL in WordPress.

Permalink parameter can be applied to any page, not only blog posts. For example to my RSS feed is linked to /blog/feed/index.html.

RSS

Pretzel generates a template for your blog feed but it should be tuned – you need to setup domain name and author name. Also Pretzel does not track posts’ publication time and if you will use RSS template as is, after the site publication your subscribers will see all previous posts in the feed. It can be avoided by adding a pub time variable to each post and by using this variable in the RSS template. Unfortunately for me, I made a mistake in time format and ended with the repopulated RSS feed.

Tags and categories

Pretzel does not generate tag clouds and any archive pages, as well as sitemap – it is your responsibility.

To display list of the categories for the post I use the following code:


@@foreach(var category in post.Categories)
{
   <a href="/blog/category/@@Filter.Slugify(category)" class="tag">@@category</a>
}

If you will check Pretzel sources (at least at a publication date) you will not see Filter.Slugify function – this change request is not yet accepted and if you’d like to see how it work please look my fork of Pretzel.

Here is the code to list all the categories


@@foreach(var category in Model.Site.Categories)
{
   <div>
      <a href="/blog/category/@@Filter.Slugify(category.Name)">@@category.Name (@@category.Posts.Count())</a>
   </div>
}

And again, Pretzel does not create categories pages for you – you need to do it manually.

Pagination

You can paginate blog index page to show, for example 10 post per page, and this behavior is also controlled in front matter:


paginate: 10
paginate_link: /blog/page/:page/index.html

This instructs Pretzel to split posts into pages by 10 and to generate index pages as /blog/page/2, /blog/page/3 and so on.

Inside of the layout you can iterate through the posts available for the current page:


@@foreach(var post in Model.Paginator.Posts)
{  
   @@Raw(post.Content)
}

For navigation all the pages can be linked together


@@if(!String.IsNullOrEmpty(@@Model.Paginator.NextPageUrl))
{
   <a href="@@Filter.PrettifyUrl(Model.Paginator.NextPageUrl)">previous posts</a>
}

So, as you can see, Pretzel is not a full featured CMS solution that can be used out-of-the box by everybody. It requires some programming skills and tuning efforts.

Pretzel is still in development and there are many things that can be added in the future but even in the current state it is stable and useful in the field.

Next posts Previous posts