Martin Suchan – BloQ Just another WordPress site

23Mar/150

How to build Windows 10 Universal Apps today, with a trick

Since the first version of Windows 10 Technical Preview was released for Windows Insiders, developers were asking, how to start developing new Universal Apps for this plaform. Unfortunately Windows 10 SDK is not yet available and it's expected to be released earliest around the time of Microsoft Build conference at April 29.
Edit, just when I finished my article, the beta SDK for developing Windows 10 Universal apps was released.

But there are ways already, how to build and test apps with Windows 10 API in Visual Studio 2013, without Windows 10 SDK.

Before we start, these are some prerequisites you need to have:

  • PC/Notebook/Tablet or Virtual Machine with Windows 10 Technical Preview installed.
  • Installation of Visual Studio 2013 Update 4 on it. The free Community edition would work just fine

First a bit of theory, Windows Store apps are based on Windows Runtime API. Metadata files for accessing this WinRT API are located in the C:\Windows\Sytem32\WinMetadata folder as .winmd files. The folder is same both on Windows 8, 8.1 or 10. Note that these files don't contain the actual API implementation, only metadata describing the actual API. You can open these files in any standard .NET disassembler like JetBrains dotPeek or Telerik JustDecompile to browse the API types and method/property signatures.

 

metadata

 

Even though Windows 10 TP already contains winmd files describing new Windows 10 API, it's not possible to use it directly when creating new Windows 8.1 App in Visual Studio, because Visual Studio uses another Windows.winmd reference library when compiling the project. This reference file is located in this folder: C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral.

Accessing Windows 10 API using reflection

First, the easier and risk-free method, how to access and test the new API.

For the start open on your Windows 10 machine Visual Studio 2013 and create new Blank Windows 8.1 app. Open the MainPage.xaml.cs, add this code to the bottom, add missing usings and run it in a windowed mode.

protected override void OnNavigatedTo(NavigationEventArgs ea)
{
    try
    {
        ApplicationView v = ApplicationView.GetForCurrentView();
        IEnumerable allProperties = v.GetType().GetRuntimeProperties();
        PropertyInfo titleBar = allProperties.FirstOrDefault(x => x.Name == "TitleBar");
        if (titleBar == null) return;
        dynamic titleBarInst = titleBar.GetMethod.Invoke(v, null);
        Color bgColor = Colors.Red;
        Color fgColor = Colors.Yellow;
        titleBarInst.BackgroundColor = bgColor;
        titleBarInst.ForegroundColor = fgColor;
        titleBarInst.ButtonBackgroundColor = bgColor;
        titleBarInst.ButtonForegroundColor = fgColor;
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
    }
    base.OnNavigatedTo(ea);
}

As you can see, you have just customized the Windows 10 App TitleBar, from inside your Windows 8.1 app using reflection. Similarly you can access other Windows 10 API too, just open any Windows.xxx.winmd file in your favorite disassembler, find a new interesting API and go for it.

 

redyellow

 

Another example, how to use the new Battery API:

public static event EventHandler RemainingChargePercentChanged;
public static event EventHandler PowerSourceChanged;
 
private const string PowerManagerTypeName = "Windows.System.PowerManager, Windows.System, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime";
private static readonly PropertyInfo remainingChargePercentProperty;
private static readonly PropertyInfo batteryStatusProperty;
 
static BatteryHelper()
{
    try
    {
        Type powerManagerType = Type.GetType(PowerManagerTypeName);
        if (powerManagerType == null) return;
 
        remainingChargePercentProperty = powerManagerType.GetRuntimeProperty("RemainingChargePercent");
        batteryStatusProperty = powerManagerType.GetRuntimeProperty("BatteryStatus");
 
        EventInfo remainingChargePercentChangedEvent = powerManagerType.GetRuntimeEvent("RemainingChargePercentChanged");
        AssignEvent(null, remainingChargePercentChangedEvent, (EventHandler<Object>)RemainingChargePercentChangedHandler);
 
        EventInfo batteryStatusChangedEvent = powerManagerType.GetRuntimeEvent("BatteryStatusChanged");
        AssignEvent(null, batteryStatusChangedEvent, (EventHandler<Object>)BatteryStatusChangedEventHandler);
 
        Available = remainingChargePercentProperty != null && batteryStatusProperty != null;
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.ToNiceString());
        Available = false;
    }
}
 
private static void AssignEvent<T1>(object instance, EventInfo runtimeEvent, T1 handler)
{
    Func<T1, EventRegistrationToken> add = a => { return (EventRegistrationToken)runtimeEvent.AddMethod.Invoke(instance, new object[] { a }); };
    Action remove = a => { runtimeEvent.RemoveMethod.Invoke(runtimeEvent, new object[] { a }); };
 
    WindowsRuntimeMarshal.AddEventHandler(add, remove, handler);
}

Again it works, but it's not exactly convenient. Lot of boilerplate code just for accessing simple singleton and attaching two event handlers. But there is a better way, how to test the new API.

Replacing the reference Windows.winmd file

It's possible to replace the reference Windows 8.1 Windows.winmd file altogether with a file containing merged Windows 10 winmd files. Visual Studio then loads this new modified Windows.winmd file thinking this is the reference API available in Windows 8.1 apps. You can then directly use all new API in your Windows 8.1 and it should work as long you run the app on same version of Windows 10, where you created the new reference Windows.winmd file. So how to get this reference Windows.winmd file?

We have to use mdmerge.exe tool for merging the content of WinMetadata folder into single file. This can be done with:

mdmerge -i c:\Windows\System32\WinMetadata\ -o c:\temp\windows.winmd /n 1

This executes mdmerge the with -i parameter - the input folder with windows metadata files, -o parameter - output folder for the result file, and -n parameter - indication that only one winmd file should be created with everything from the input inside. Note the mdmerge tool is located in the C:\Program Files (x86)\Windows Kits\8.1\bin\x64 folder. For easier use you can add this path to Path system variable.

If you run this command directly in cmd.exe, you may find, that it throws various mdmerge exceptions:

 

Microsoft Windows [Version 10.0.9926]
(c) 2015 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>mdmerge -i c:\Windows\System32\WinMetadata\ -o c:\temp\windows.winmd /n 1
Microsoft(R) Metadata Merge Utility Version 8.0.23.

Processed input metadata file c:\Windows\System32\WinMetadata\\Windows.ApplicationModel.winmd.
MDMERGE : error MDM2006: c:\Windows\System32\WinMetadata\\Windows.ApplicationModel.winmd does not appear to be a valid Windows Runtime metadata file
MDMERGE : error MDM2005: Unable to open metadata file c:\Windows\System32\WinMetadata\\Windows.ApplicationModel.winmd.
Processed input metadata file c:\Windows\System32\WinMetadata\\Windows.Data.winmd.
MDMERGE : error MDM2006: c:\Windows\System32\WinMetadata\\Windows.Data.winmd does not appear to be a valid Windows Runtime metadata file
MDMERGE : error MDM2005: Unable to open metadata file c:\Windows\System32\WinMetadata\\Windows.Data.winmd.
Processed input metadata file c:\Windows\System32\WinMetadata\\Windows.Devices.winmd.
MDMERGE : error MDM2006: c:\Windows\System32\WinMetadata\\Windows.Devices.winmd does not appear to be a valid Windows Runtime metadata file
MDMERGE : error MDM2005: Unable to open metadata file c:\Windows\System32\WinMetadata\\Windows.Devices.winmd.

 

When I used this command few months ago, it worked fine, but when I tried it recently in Windows 10 v9926, it just ended with these errors. Luckily there is a way how to fix it! Windows 10 uses newer Windows Runtime file format, that is not supported in Windows 8.1 mdmerge tool, but we can make the mdmerge tool think it actually supports it. How to do it:

Make a copy of mdmerge.exe named mdmerge2.exe that is located in C:\Program Files (x86)\Windows Kits\8.1\bin\x64. Open this file in a binary editor and look for the string "WindowsRuntime 1.2" and replace it with "WindowsRuntime 1.4". Save the file and run: mdmerge2 -i c:\Windows\System32\WinMetadata\ -o c:\temp\windows.winmd /n 1

 

Microsoft Windows [Version 10.0.9926]
(c) 2015 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>mdmerge2 -i c:\Windows\System32\WinMetadata\ -o c:\temp\windows.winmd /n 1
Microsoft(R) Metadata Merge Utility Version 8.0.23.

Processed input metadata file c:\Windows\System32\WinMetadata\\Windows.ApplicationModel.winmd.
Processed input metadata file c:\Windows\System32\WinMetadata\\Windows.Data.winmd.
Processed input metadata file c:\Windows\System32\WinMetadata\\Windows.Devices.winmd.

 

If everything works, you'll get new Windows.winmd file with all Windows 10 API merged into one file. Now you better backup the original file located in C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd to a safe location and replace it with the new merged file.

If you now start Visual Studio 2013 or Blend for Visual Studio 2013 and create new Blank Windows 8.1 App, you should be able to use new Windows 10 types in it without any problem and compile and run the project successfully.

 

 

Capture

 

Disclaimer

This is an experimental method how to test new, unfinished Windows 10 API inside Windows 8.1 project. Some new API from Windows 10 might be bugged or not not work at all. Some new API may be changed, replaced or even absent in the RTM version so you should probably not start building huge app depending on those new features. Also using this trick might break your Visual Studio installation so beware, don't do it on your production machine.

Filed under: Uncategorized No Comments
22Mar/150

#WPdev Quick tip – API for accessing Windows Store from your app

Following the previous WPdev quick tip how to initiate Email Compose from your app, here is another API that developer often need:

  • Navigate to Rate and Review dialog for the current app - if you want to initiate app rating from the current user
  • Navigate to Windows/Phone Store to the currently running app - if you want the user to purchase full version of current app or upgrade to a new version
  • Navigate to Windows/Phone Store to all apps published by the current developer - if you want to encourage the user to download other of your apps

Unfortunately all these tasks require different type of API in Windows Phone 7.5/8/8.1 Silverlight apps, in Windows 8.1 apps and another one in Windows Phone 8.1 WinRT apps and since I needed all these methods in my recent Windows Universal App NASA TV Live, I decided to put it all into short article for future use, so here it is:

10Mar/150

#WPdev Quick tip – API for sending emails from your app

When developing Windows Phone or Windows Store app it's often useful to give your user option to send you feedback email or feature request. In this short #WPdev article I'll cover all three different approaches you could use in all current Windows Store platforms.

Windows Phone 7, 7.5, 8 and 8.1 (Silverlight)

Sending emails from original Windows Phone 7+ Silverlight apps is done using the EmailComposeTask:

string to = "my@email.cz";
string subject = "Idea for your app";
string body = "Hi, here's an idea for your cool app...";
EmailComposeTask emailTask = new EmailComposeTask
{
 To = to, Subject = subject, Body = body,
 //Cc = , Bcc = , CodePage = ,
};
emailTask.Show();

When the Show method is called the system dialog appears where you can choose the mail account that will be used for sending the email.

As you can see the usage is really simple, one class and one method is all you need. Note there is no way how to send emails with attachments using this API.
Another problem also is that this API is no longer available when developing Windows 8/8.1 or Windows Phone 8.1 WinRT apps. So what is the alternative?

5Jan/150

Windows Phone 8.1 SDK, 9 month later, what’s new

dd8_evolucewp

The Windows Phone 8.1 SDK was released with a bang at the beginning of April 2014 and the OS update arrived later that year. It brought lot of new to the Windows Phone ecosystem, but also caused a noticeable disarray to the Windows Phone community and to the community of developers as well. Some features in WP8.1 are definitely great and improving, some are just worrisome, and some features in WP8.1 SDK are simply missing, even though they were in WP8.

Let's take a look on the WP8.1 SDK nine months after the original release, what improvements it brought and also what's still not there.

In this dev article about Windows Phone 8.1 SDK, 9 month later I'll summarize in few bullet points the most interesting features of this OS update and especially what's new for developers.

17Oct/149

How to deploy your own NuGet server on Azure Website in 15 minutes

Let's imagine this typical scenario: You are an indie developer or a company developing apps in Visual Studio. You have already developed and use several own useful libraries across various projects. Right now you are maintaining each of these libraries in separate Git/TFS repository and adding these libraries as submodules to your projects. Because these libraries are hierarchically dependent one on another, it's quite hard to maintain the dependencies and changes properly. You've thought about packaging these libraries as separate NuGet packages, but adding them to public nuget.org gallery is not an option since these libraries contain private knowhow.

In this article I'll demonstrate, how to deploy your own NuGet Server on free instance of Azure Website, secure it with Basic HTTP Authentication, setup this new server so it can be used from Visual Studio, easily create automatic PowerShell scripts for deploying these libraries as NuGet packages to your server, use these NuGet packages in your projects and also how to achieve all this in just couple of minutes!

21Aug/140

New API in Windows Phone 8.1 Update 1

Accessory-App-Windows-Phone-348x620As a part of the "Preview for Developers" program Microsoft just recently released the first larger update for Windows Phone 8.1 called just "Windows Phone 8.1 Update" with OS version number 8.10.14147.180. The original Windows Phone 8.1 was 8.10.12359.845.

According to MSDN blog article this update brings primarily these new end user features:

  • Cortana is now available for couple of new countries
  • Live Folders - native implementation of app folders on the Start screen
  • Option to simply select multiple SMS messages for deleting/forwarding
  • Apps Corner, Private VPN, Store Live Tile, Internet sharing via Bluetooth, customizable snooze time for Alarms and more.

But probably the most interesting feature, that might be part of this update as well, is is the support for notification on accessories, typically on smart watches and other wearables. The best hint for this functionality is already in the phone settings - the new "accessory apps" section.

The second hint is the new available API, that'll be shown in the rest of this article.

27Jul/144

File IO Best Practices in Windows and Phone apps – Part 1. Available APIs and File.Exists checking

Working with files is one of the most common tasks when developing any Windows Phone or Windows apps. In this mini-series of articles I'll show you available APIs in all Windows Phone and Windows versions, caveats when doing task such as checking if specific file exists, getting target file, reading writing data from/to files and also how to effectively extract data from ZIP files, and more.

In the first part of this series I'll discuss available File IO APIs in Windows Phone 8, 8.1 Silverlight, 8.1 XAML, Windows 8 and 8.1 platforms and benchmark all available methods for testing, if target file in Local Folder exists, or not. To my great surprise, the performance of methods in StorageFolder API is dramatically different across different platforms and it's not a good idea to use single approach everywhere.

11Jun/140

Xbox 360 Controller API for Windows Store apps

In Windows Store apps for Windows 8.1 there are four basic input methods - touch, mouse, stylus and keyboard. In most of scenarios these input methods are all you need, but in case you want to offer more natural experience for controlling games on Windows 8.1, you can also add support for Xbox 360 and Xbox One controllers.

In this dev article I'll show you, how to use in any C#/XAML app or game for Windows 8.1 the Xbox 360 Controller API, how to detect presence of such controller and how to poll for current state of all buttons.

25Mar/140

Using Json Design-time data in Windows Phone 8 apps

In my previous article I've shown a new way, how can we use Json file as a data source for design-time data in new Windows 8.1 apps. Luckily, it's possible to use similar approach in Windows Phone 8 apps as well!

15Mar/141

Using Json Design-time data in Windows Store apps

When designing Windows 8.1 apps it's essential to have design-time data available in some way, so we can actually see how the app will look like.

Iris Class described in this great article, that there are several ways, how to achieve this:

  • Using XAML – Design time data source set in XAML
  • Using a ‘standalone’ data source class – Design time data source set in XAML
  • Conditional data source – Design time data source set in code

But what I missed in this aticle is probably the most interesting way, how to use design-time data in Windows 8 apps - using external Json files. Here's a short guide, how to do it: