Coding4Fun toolkit 2.1.0 released #WinRT #wpdev #windev

c4f

This is the 3rd iteration of toolkit updates I am pushing out. Like the other 2, this one builds on Windows Runtime WinRT app support for Windows Platform development.

This release also brings WinRT support close to what Silverlight version supported and finally drops support for Silverlight apps. The SL version is still available on nuget but it is unlikely to receive any updates.

SuperSlider (ColorSlider + ColorPicker) has a gotcha and its gonna need some clever work. Internally it uses code that monitors movement for updates and movements to prevent scrolling when the control is contained within Pivot, Hub or FlipView containers however lack of Touch class has forced me to use PointerPressed / PointerMoved and PointerReleased for these and in my tests, Pivot does not bubble those events and control doesn’t work correctly. Keep this in mind

Sample apps available in stores will be updated to reflect the changes

258x67_WP_Store_cyan WindowsStore

Control Windows Phone 8.1 Windows 8.1
RoundButton
ToggleButton
OpacityButton
Tile
ImageTile
ChatBubble
ChatBubbleTextBox
ColorHexPicker
ColorPicker
ColorSlider
AboutPrompt ×
InputPrompt ×
MessagePrompt ×
ToastPrompt ×
PasswordInputPrompt ×
MetroFlow
Overlay
SuperSlider
SuperImage

Happy coding

Advertisement

Coding4Fun v2.0.9 released #wpdev #windev #winrt

Coding4Fun toolkit v2.0.9 for Windows Platform dev has been released and packages are available for download from Nuget.

This update builds additional support for Windows Runtime on Windows Phone 8.1 and Windows 8.1. Controls added to this release include

  • MetroFlow control (Windows 8.1 and WP 8.1)
  • Prompts (Toast, User, Message, Input, PasswordInput) for WP 8.1
  • BrushToBrushConverter now allows use of parameter to set output Opacity.

AppBarPrompt requires additional work the port wasn’t successful first time around. For issues there’s codeplex.

Happy coding

WinRT and application view wide Pointer event monitoring #wpdev #windev

It seems like every year I go through same technical difficulties. Last year I blogged about WinRT and pointer manipulation #win8dev #winrtdev

One of the underlying classes detects manipulation by user by means of Touch class. This class never made it to WinRT XAML and I have been messing around for a few days now… until something finally sunk in..

CoreWindow exposes following events

PointerEntered Occurs when a pointer moves into the bounding box of the Windows Store app.
PointerExited Occurs when the pointer moves outside the bounding box of the Windows Store app.
PointerMoved Occurs when a pointer moves within the bounding box of the Windows Store app.
PointerPressed Occurs when a mouse button is clicked, or a touch or pen contact is detected, within the bounding rectangle of the Windows Store app.
PointerReleased Occurs when a mouse button is released, or a touch or pen contact is lifted, within the bounding rectangle of the Windows Store app.

These events work exactly like Touch.TouchFrameReported and get bubbled up no matter which UIElement is tapped.

Time to continue porting

Coding4Fun v2.0.8 released on Nuget #wpdev #win8dev

Earlier this week I mentioned that I was working on a release of Coding4Fun toolkit. It has now achieved parity with Windows 8.1 version (which was somehow never released).

As of now, a stable release v2.0.8 is now available. The changes include

  • Support for Windows 8.1
  • Support for Windows Phone 8.1 (WinRT app not SL8.1)
  • WP8 Silverlight continues to be supported as before
  • Dropped WP7 and Windows 8

In addition to Coding4Fun.Toolkit.Audio and Coding4Fun.Toolkit.Storage which is supported in both Win8.1 and WP8.1, the Coding4Fun.Toolkit.Control has the following controls

  • Tile
  • SuperImage
  • ImageTile
  • ColorHexagonPicker
  • ChatBubble
  • ChatBubbleTextBox
  • RoundButton
  • RoundToggleButton
  • OpacityToggleButton

The source as usual is on http://coding4fun.codeplex.com, packages are on Nuget

WindowsPhone 8.1, NavigationBar and Silverlight apps #wpdev

With Windows Phone 8.1 Microsoft drastically changed on of the basic chassis requirements in Windows Phone since day 0. The hardware buttons at the bottom of the phone. There were many reasons and one of them was the ability to use same chassis for both Android and Windows Phone devices. This many cited was very important smaller OEMs that recently signed up to Windows Phone ecosystem.

WP7 resolutions:

  • 800 x 480

WP8 resolutions (and scaling factors as reported  by Silverlight apps):

  • 800 x 480     (1.0)
  • 1280 x 720   (1.5)
  • 1280 x 768   (1.6)
  • 1920 x 1080 (2.25)

For Silverlight Windows Phone app (most of the apps that is) the resolution defaults to 800 x 480. This fits nicely with Scaling factor 1.6 which was used by many early Nokia devices. The scaling factor 1.5 however gave 853 x 480. This primarily affected HTC 8 S/X devices and Samsung ATIV S devices only. Later when Lumia 1520 came out, it uses 1020 and that used 2.25 and that also had 853 x 480 res.

What this meant was that WP7 and any WP8 apps that fix their resolution would leave 53 px gap. With my 1Shot camera app, I have a complicated control structure and I ended up fixing many heights and widths.. Not only that I also move certain objects on OrientationChanged using specific values of TranslateX and TranslateY. Last week after a user complaint, I added code to detect 720p and 1080p resolutions and to stretch those by additional 53px. However I never tested this on newer 720p devices that no longer have hardware buttons.

What Windows Phone Dev team did was added another system control like ApplicationBar called NavigationBar. Unlike ApplicationBar, NavigationBar isn’t accessible from within application. Playing with emulator set to show NavigationBar did not show any change in size reported by

double width = Application.Current.Host.Content.ActualWidth;
double height = Application.Current.Host.Content.ActualHeight;

After much complaining around twitter I came across windows phone 8.1 hide NavigationBar post on MSDN Forums. One of the suggestions was using PhoneApplicationFrame.FullScreen. Setting it to true or false made no difference.. none at all. After another round of complains, I came across this post Layout and the Windows Phone navigation bar.. it suggest that SizeChanged event should take care of it and ActualWidth and ActualHeight properties will sort it out.

Being not particularly clever, I thought that Page’s SizeChanged would be fired.. sure it was firing but ActualWidth and ActualHeight were 0.0. Width and Height were NaN so that was useless. Thinking that I could do better than that, I tried using SizeChanged exposed by Application.Current.Host.Content.. nope no difference.. it wasn’t a particularly bright idea.. Yesterday I spent time deliberating whether I should use hardcoded lists to indicate NavigationBar availability or not.. I already do so for high resolution sensors.. nah too much hassle

So today I said.. surely there must be something… on SizeChanged event handler of page, I scanned App.RootFrame.. I found something.. a private field called _visibleRegion correctly showed that 53 px at the botton were not available on 720p emulator when NavigationBar was visible. I think I am clever than most…

private Thickness GetMargin()
{
    Thickness t = new Thickness();

    var field = App.RootFrame.GetType().GetField("_visibleRegion", BindingFlags.Instance | BindingFlags.NonPublic);

    if (field != null)
    {
        object visibleRegion = field.GetValue(App.RootFrame);

        if (visibleRegion != null && visibleRegion is Thickness)
        {
            t = (Thickness)visibleRegion;
        }
    }

    return t;
}

This would get me the right margin and I could just just correct a few bits and bingo.. hahah yah right.. FieldAccessExpcetion eat that you clever git.. Apps don’t run under full trust on phone and I couldn’t reflect to this level. Sigh.. This was hard.. why had Windows Phone team gone way out of their way to piss developers off ?? Having almost lost all hope, I thought, let me try subscribe to Page’s LayoutRoot grid’s SizeChanged event… had a look there.. event handler exposed NewValue and they showed the correct values!!! yay

double gridWidth = e.NewSize.Width > e.NewSize.Height ? e.NewSize.Width : e.NewSize.Height;
double gridHeight = e.NewSize.Width > e.NewSize.Height ? e.NewSize.Height : e.NewSize.Width;

double w = Application.Current.Host.Content.ActualWidth;
double h = Application.Current.Host.Content.ActualHeight;
double hostWidth = w > h ? w : h;
double hostHeight = w > h ? h : w;

bool hasSoftButtons = hostWidth > gridWidth;

Just for your sanity.. I always want Landscape mode so width is always greater than height based on supported resolutions.. so there you have it.. subscribe to LayoutRoot’s SizeChanged and get the right size.. OnResize, the dimensions reflect 800 x 480 resolution and not 853 x 480.

Finally!

Images and Scaling with Windows Runtime #WinRT #WPDev #Windev

With the advent of Windows Phone 8.1, developers have the option of using WinRT native XAML stack as opposed to the Silverlight XAML the only option with early Windows Phone iterations.

One of the differences between WinRT XAML and Silverlight XAML is scaling and like with fonts, & images, scaling can have a significant effect on the look and feel of an app.

The default behavior with Windows Phone 8 was the inherent Silverlight behavior of scaling the image to fit. This meant that unless a high-resolution image was used, the image would end up looking blurred. Windows Runtime takes a different approach.

Windows 8x supports multitudes of screen sizes, resolutions and DPI. Windows Phone now supports 4 resolutions. The way Windows Runtime deals with this is by allowing developer to specify multiple images to match certain scale factors.

Windows Store Apps Windows Phone Store Apps
1.0 (100% no scaling) 1.0 (100% no scaling)
1.4 (140% scaling) 1.4 (140% scaling)
1.8 (180% scaling) 2.4 (240% scaling)

The runtime would determine the scaling factor to use depending upon the screen size, resolution, DPI and the form factor of device in question. The developer is required to supply images for scaling 1; the other scale factors are optional. If they are supplied, they will be used if necessary.

There are two ways of supplying images to support multi-scaling support.

  • Specify image scale within the file name e.g. Image.scale-100.png or Image.scale-140.png
  • Create direct for each image scale and place images inside without specifying scaling like in 1. E.g. scale-100/Image.png or scale-140/Image.png

The attached project includes examples of both ways.

To use this and enable auto-scaling support, you specify the image as specified below

<Image Source="Assets/Iris.png" />
<Image Source="Assets/Iris2.png" />

Occasionally it is necessary to set the images from code. In those instances, one should query the windows runtime to determine the current scaling factor and return appropriate image resource.

var uri = new System.Uri("ms-appx:///Assets/Iris.png");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

This will correctly detect the scaling factor and get appropriate file.

Alternatively, for Windows 8x, we can use DisplayProperties.ResolutionScale to determine current scaling and for Windows Phone, we can use DisplayInformation.RawPixelsPerViewPixel.

Uri uri = null;
#if WINDOWS_PHONE_APP
    var rawpixelperview = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel; 

    var Width = Convert.ToInt32(Window.Current.Bounds.Width * rawpixelperview); 
    var Height = Convert.ToInt32(Window.Current.Bounds.Height * rawpixelperview); 

    if(Width == 480 && Height == 800)
    {
        uri2 = new System.Uri("ms-appx:///Assets/scale-100/Iris2.png");
    }
    else if((Width == 720 && Height == 1280 ) || (Width == 768 && Height == 1280))
    {
        uri2 = new System.Uri("ms-appx:///Assets/scale-140/Iris2.png");
    }
    else
    {
        uri2 = new System.Uri("ms-appx:///Assets/scale-240/Iris2.png");
    }
#else
    switch (DisplayProperties.ResolutionScale)
    {
        case ResolutionScale.Scale100Percent:
            uri2 = new System.Uri("ms-appx:///Assets/scale-100/Iris2.png");
            break;

        case ResolutionScale.Scale140Percent:
            uri2 = new System.Uri("ms-appx:///Assets/scale-140/Iris2.png");
            break;

        case ResolutionScale.Scale180Percent:
            uri2 = new System.Uri("ms-appx:///Assets/scale-180/Iris2.png");
            break;
    }
#endif

var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

It worth noting that images set in xaml and those done codebehind behave differently at least as far as size on screen is concerned. The only way to achieve correct size as visible in xaml is to set size to that of scale 1.0 image.

Supporting Accessibility

Windows Store apps support high contrast mode. The two available options are

  • Black background and white foreground
  • White background and black foreground.

To additionally support these two accessible image formats, you need to provide scale factor 1 images named / placed appropriately. I have excluded the high contrast images from sample as windows phone was using that by default.

Assets/Iris.scale-100_contrast-black.png

Assets/Iris.scale-100_contrast-white.png

or

Assets/scale-100_contrast-black/Iris2.png

Assets/scale-100_contrast-white/Iris2.png

Downloadable sample code can be downloaded here

DLL / Reference hell with #WP8 #SL81 and #WinRT component

Over the last month, I have gone back to “AlarmClock” app (my 3rd Windows Phone app from back in 2011). I have updated it to render time updates on live tile. In fact I am quite proud the mechanism I use. I additionally provided 50 downloadable font packs that users can choose from (purchasable in a set of 10).

Original solution
The update mechanism was initially based on Silverlight Background Task. The tile update mechanism of course updates tile based on local time. However a user reported that when travelling between timezones, the tiles kept showing previous timezone times until the next background task run started pushing new ones based on new local time.

I deliberated on this and came to the conclusion that somewhere something was fishy.. its possible that Tile updates are actually scheduled on UTC as opposed to local time or maybe I just don’t understand it. Either way, I had to fix this issue

Solution 2: Fix for Timezone change
The new windows phone 8.1 introduced a bunch of new WinRT API that included API for Background task including those that run on Timezone change. So I dumped SL based Background Task and went full stream with WinRT component. Added 2 WinRT classs on for Timer and another for Timezone and this worked great.

Another user wanted the clock and tile updates to support multiple Timezones – wanted to pin Hong Kong and Seattle. My app so far only supported local device timezone.

Soluion 3 – Multiple Timezone support

.NET 4.5 comes with TimeZoneInfo class.This provides a nice method GetSystemTimeZones which lists all timezones and make it possible to convert between those. However Windows Phone .NET Runtime does not come with this and there is not suitable WinRT API either. Yay!!
Oren Novotny created a good Win32 wrapper which works on both WP8, WP81, SL81 and WinRT
I fired up Nuget Package Manager and searched for timezone..found Timezone conversion between WinRT and PCL.. Added a reference to the App and reworked it to support user selectable timezone etc. This required me to select target between x86 and ARM – any CPU no longer an option.

Next step?? Add Timezone helper reference to WinRT component. Bang bang bang.. nugget sorted it all out.. that was easy.. modified the background processor to update all tiles with correct timezone times!! nice 🙂 What could possibly go wrong ?

Hit F6, (Old school.. modified VS 2013 to build o F6 like before).. all good. Hit F5… wait for it !!!!

Runtime exception – File not found System.Runtime.InteropService.. quick search showed reference conflict..

Step 1) Set WinRT component to x86 instead of Any CPU.. maybe that will do the trick!!!

Nope far from it… Result System.BadImageFormatException thown when trying to run the app.

Step 2) Download code and make a part of existing WinRT component..

Nope still the same error(s)

While deliberating, realised that I called code from Background Task directly from my app.. 3rd trial

Step 3)

Remove calls to code in Background Task from App
Nuget Reference to App
Code within WinRT component for internal use
App – x86 / ARM target
WinRT component – Any CPU tagt

Bingo.. It all work as advertised!!

Took me day to figure try out various options

App tile transparency for WP8.1 apps #wpdev

One of my popular lines is “Don’t throw shit around.. what goes around comes around!” and rightly so. A few weeks back I was making fun of @dvlup for blogging about how to create transparent tiles for the WP apps 🙂

I know the irony isn’t lost on me. The idea is with WP8 apps, you create tile images which are transparent png with white bits.. if you had a star or a clock that would be white, the rest would be transparent and you used this. This would make your app’s tile transparent and if you had a fancy background, you would see through the tile.

Fast forward today, I was testing WP8.1 update to my alarm clock app. What does it do ? well shows you tile update every minute with a nicely rendered tile. and yes I made the tile transparent. But the tile comes up as grey.. WTH

alarmclock1

so I start looking around and I remember that Windows 8 app manifest had a background color, Open the Package.appmanifest and I find this

<m3:VisualElements
    DisplayName="AlarmClock"
    Square150x150Logo="Assets\SquareTile150x150.png"
    Square44x44Logo="Assets\Logo.png"
    Description="AlarmClock"
    ForegroundText="light"
    BackgroundColor="#464646">

hmmm no alpha value to make it transparent. So I tried to set BackgroundColor to Transparent.. nope.. transparent ? Bingo!!

<m3:VisualElements
    DisplayName="AlarmClock"
    Square150x150Logo="Assets\SquareTile150x150.png"
    Square44x44Logo="Assets\Logo.png"
    Description="AlarmClock"
    ForegroundText="light"
    BackgroundColor="transparent">

alarmclock2
Now if you used transparent png for tiles, your WP 8.1 app’s tiles are transparent.

Image scaling related crashes on 1080p devices #wpdev

Back in March one of the 1Shot camera app users emailed me stating that the app crashes when using he uses digital zoom on Lumia 1520. I couldn’t reproduce the issue on my 1020. I then borrowed a friend’s 1520 and hmm sure I could reproduce it but I couldn’t catch the exception.

So we left it at that.. fast forward on Friday I get a mail back from chap in question and he states that he’s running latest greatest version of preview and the freaky crash is still happening. Luckily I have the 1520 at my desk and decided to put it to good use over the weekend.

So I put VS configuration in Debug mode and I set VS to catch all thrown exceptions. Run app and swipe left right and top bottom and every so often the app crashes.. no exception being caught.. the app just disappears and we are back to home screen. The only clue was the output of debug mode.. The program ‘[4880] AgHost.exe’ has exited with code -1073741819 (0xc0000005) ‘Access violation’.

The sad reality, the debug output is littered with messages starting ‘AgHost.exe’ (CoreCLR: Silverlight AppDomain): A quick check on the net showed that AgHost.exe is used to manage access through identity verification.. great. The error code wasn’t particularly useful either.

In this particular case, the error only occurred when zooming in. My implementation of digital zoom was scaling the preview image for the live view. The only action associated with crash was zooming in and out. As it happens, I detect manipulation delta and compute scale..

private void LivePreviewTapTarget_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
{
    if (!this.viewModel.CaptureInitiated && AppSettings.InternalAppSettings.DragZoom)
    {
        SetDragToScale(e.CumulativeManipulation.Translation);
        e.Handled = true;
    }
}

void SetDragToScale(System.Windows.Point pScale)
{
    double x = Math.Abs(pScale.X);
    double y = Math.Abs(pScale.Y);

    double manipulation = x > y ? pScale.X : pScale.Y;

    bool zoomOut = manipulation >= 0 ? false : true;

    double scale = (this.viewModel.HasHighResolutionCamera ? 0.01 : 0.005) * Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));

    if (zoomOut)
        this.viewModel.ViewScale = initialScale + scale;
    else
        this.viewModel.ViewScale = initialScale - scale;

    System.Diagnostics.Debug.WriteLine("zoomout {0}, scale {1}", zoomOut, scale);
}

My initial thought was that it being a newer SoC, the Xaml Renderer was somehow being proactive somewhere and getting itself in a mess.

Test 1: show less frames and show larger jumps so there is less rendering. For High Res camera I used constant of 0.01.. increase it to 0.05.

The resultant build crashed very very fast. hardly took a swipe or two to head back to home screen.

So I wanted to try the reverse but by laptop decided to shutdown and I was too knackered to continue yesterday.
Earlier today I had a chat with Bill Reiss.. he mentioned that he had some problems with 1520 too and that it had something to do with how large the image becomes on 1080p screen.

So I decided to continue where I left yesterday but with a reduction only for 1080p devices.
Test 2: reduce the multiplication constant to 0.0015 if a 1080p device is detected.
Result: Significant reduction in crashes.. I can still get it to crash but not that often. Here is the changed version

int DeviceScaleFactor = -1;
private void GetScaleFactor()
{
    object physicalScreenResolutionObject;

    if (DeviceExtendedProperties.TryGetValue("PhysicalScreenResolution", out physicalScreenResolutionObject))
    {
        var physicalScreenResolution = (Size)physicalScreenResolutionObject;

        DeviceScaleFactor = (int)(physicalScreenResolution.Width / 4.8);
    }
    else
    {
        DeviceScaleFactor = Application.Current.Host.Content.ScaleFactor;
    }
}

void SetDragToScale(System.Windows.Point pScale)
{
    double x = Math.Abs(pScale.X);
    double y = Math.Abs(pScale.Y);

    double manipulation = x > y ? pScale.X : pScale.Y;

    bool zoomOut = manipulation >= 0 ? false : true;

    if (this.DeviceScaleFactor == -1)
    {
        this.GetScaleFactor();
    }

    double scale = (this.viewModel.HasHighResolutionCamera ? 0.01 : 0.005) * Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));

    if (DeviceScaleFactor == 225)
    {
        scale = 0.0015 * Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));
    }

    if (zoomOut)
        this.viewModel.ViewScale = initialScale + scale;
    else
        this.viewModel.ViewScale = initialScale - scale;

    System.Diagnostics.Debug.WriteLine("zoomout {0}, scale {1}", zoomOut, scale);
}

if the Device scale factor is 225, its a 1080p device and one should exercise caution.

Cineworld – Transparent tiles and Uri Schema

Traditionally Windows Phone allowed Tile images to be transparent or otherwise. With advent of Windows Phone 8.1 and start screen background, devs are pretty hyped up about using transparent images.

For once I myself received a request for cineworld app. so the cycle tile is been done away with (if you have it pinned, cycle tile will continue to update as was before.. ) if you repin you get flip tile with primary background transparent.

I was also asked for Uri Schema for cineworld app. I have added 3.

cineworld:film?1234

cineworld:cinema?22

cineworld:search?xmen days of

the film uri schema takes EDI value.