Blog

  • Pontoon – Available Functionality

    As with the Universal Windows Platform itself, Pontoon has a rich API which supports functionality which may not be available on all platforms. There are two reasons for this – either the platform doesn’t natively support the feature or I just haven’t got around to implementing it yet.

    There is a simple mechanism to test for functionality at runtime – and as with the rest of the API it’s the same as UWP – InTheHand.Foundation.Metadata.ApiInformation. Using this class you can check for the availability of types, properties, methods etc. via name. The only difference being that all classes have the root InTheHand namespace.

    Currently there are a number of APIs which aren’t available on all platforms. Today’s release adds Accelerometer and Gyroscope for Windows (except Win32) and iOS. Another new API is LaunchFolderAsync on the Launcher class which is only present on Windows UWP and Win32 platforms – you would check for this using IsMethodPresent.

    As always I welcome all constructive feedback – please use GitHub to raise any issues.

    NuGet: https://www.nuget.org/packages/InTheHand.Pontoon/

    GitHub: https://github.com/inthehand/Pontoon

    Docs: http://inthehand.github.io/

  • Introducing Pontoon – A flexible bridge to the Universal Windows Platform

    I first created the “Charming” libraries for Windows Phone in order to add some APIs which were added to Windows 8 but not available on phone. Many of the early ones replicated the “Charms” related functionality (Sharing/Search/Settings) hence the silly name.

    When I created version 9 about a year ago I consolidated lots of separate libraries into just two – InTheHand and InTheHand.UI. The latter contained UI specific functionality such as MessageDialog, ToastNotification and ApplicationSettings. Following this I extended the library with support for iOS and Android using Xamarin and exposing the same UWP style API.

    As I’ve been doing Xamarin development recently I’m constantly having to look for or write wrappers for native APIs to use across platforms. You sometimes find libraries which claim to provide a cross-platform API but actually only support iOS and Android. I looked at the large codebase I already had and thought about other areas which could be implemented across all the Windows and Xamarin platforms. Among the Windows platforms I added Win32 support so you can use these same APIs from Console, WinForms or WPF applications on versions prior to Windows 10. Since a lot of desktop apps still support Windows Vista and 7 this was very important to provide future code compatibility with Windows 10.

    I’d toyed with changing the name before because it’s now irrelevant in an OS which no longer has the concept of Charms. I thought about the Windows 10 “bridges” – to take Desktop Apps, iOS and Silverlight to UWP and thought what I have here is effectively another bridge. It’s a flexible one though and it also works in both directions. You can code C# on numerous platforms and that code will be instantly portable to UWP. You can also use your UWP knowledge to easily target some of the more fiddly aspects of Xamarin platforms consistently. If you consider a Xamarin Forms application which might target iOS, Android and Windows once you step beyond laying out forms with the built in controls and basic page navigation there is no common API to work with Settings, Files, Geolocation, Network connectivity and more. If you are able to find a NuGet library which supports all the platforms you need you’ll have to learn a whole new API too. One word which kept springing to mind with the concept of a flexible bridge is Pontoon and so this is what I chose. Wikipedia says “A pontoon bridge, also known as a floating bridge, uses floats or shallow-draft boats to support a continuous deck for pedestrian and vehicle travel”. Although I renamed the GitHub repository this is a direct continuation of the Charming codebase but there will be a few breaking changes hence the new NuGet package and major version change.

    If you are interesting in contributing to the library please do get in touch. There are a number of open issues which are still to be addressed and many more API areas which would make sense to implement in this way. I’ve consciously avoided most UI areas because this is something you’ll need to approach differently for each platform (unless you use Xamarin Forms) and I didn’t want introduce any additional dependencies. There are some UI elements such as StatusBar, MessageDialog, Toast/Badge notifications, CameraCaptureUI etc. I consider these to be part of the “Chrome” rather than your app UI – they will all have a very different look and feel depending on the platform but perform the same functions.

    I’m still working on a sample application. I’ll probably use Xamarin Forms in order to create a simple UI to surface as much of this functionality as possible.

    As always I welcome all constructive feedback – please use GitHub to raise any issues.

    NuGet: https://www.nuget.org/packages/InTheHand.Pontoon/

    GitHub: https://github.com/inthehand/Pontoon

    Docs: http://inthehand.github.io/

     

  • Latest Version of InTheHand.Core

    I’ve just updated the NuGet package for InTheHand.Core. This adds a VibrationDevice which works across all Xamarin Platforms (hardware permitting) and fixes a bug with PowerManager.RemainingChargePercent on iOS. The library now has 18 namespaces full of UWP APIs for all Xamarin platforms (and this doesn’t count the sister library InTheHand.UI). Check it out here:-

    https://www.nuget.org/packages/InTheHand.Core/

  • Interactive Toasts and Windows Phone 8.1

    Windows 10 brings a whole range of new APIs and functionality for building apps. However in the phone space it’s important to be mindful that there are a lot more Windows Phone 8.1 devices in use than Windows 10. Many (but not all) will get an update to Windows 10. A lot of clients are keen on supporting 8.1 to cover the largest group (as an 8.1 app will just run on 10). Of course your users on Windows 10 may miss out on cool features in this way unless you are prepared to maintain both 8.1 and 10 versions of your app. There are a number of areas of the Charming Apps libraries which support “lighting-up” of functionality. That means exposing Windows 10 APIs to Windows 8.x projects. In some cases this is a remapping of existing functionality from an old-style API to one which is source compatible with UWP. In other cases there is functionality which is just not there on 8.x but you can make it available when your app is run on a Windows 10 device.

    In order to support this a bit of Reflection is required but we’ve hidden that messy stuff for you – you just call the same APIs and get graceful failure or the “light-up” experience when running on Windows 10. For many of these APIs the Charming Apps library provides iOS and Android implementations while exposing the same UWP API surface. There are a number of possible ways of detecting whether the device at runtime is running Windows 10. One of these is to use:-

    if (InTheHand.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 1))

    Another is to check:-

    InTheHand.Environment.OSVersion.Version

    (caveat – On 8.x we can return only Major.Minor.0.0 versions)

    One of the new features in Windows 10 is the interactive toast notification. There is no API change to set these locally – it just requires a different XML template. So once you’ve checked your OS version you can switch between a traditional dumb toast or an interactive one such as:-

    string xml = "<toast launch="yourstring"><visual><binding template="ToastGeneric" ><text>Big text</text><text>smaller text</text></binding></visual>"
                        + "<actions><input id="time" type="selection" defaultInput="2"><selection id="1" content="Breakfast"/><selection id="2" content="Lunch"/><selection id="3" content="Dinner"/></input>"
             	    + "<action activationType="foreground" content="Primary Action" arguments="primary"/><action activationType="foreground" content="Secondary Action" arguments="secondary"/></actions>"
                        + "</toast>";

    Notice that I’ve specified foreground activation. In a UWP project you’d also have the option of background activation where a background task is launched to carry out an action. In the case of foreground activation the system calls your app’s OnActivated method. However this is where it gets a bit more fun. The ActivationKind is not specified in Windows Phone 8.1, nor is the ToastNotificationActivatedEventArgs which is passed through. However the value of ActivationKind.ToastNotification is documented as 1010. The event args contains two items of interest, the Argument – the action which was selected and UserInput which is a string keyed dictionary of input id and selection id or input id and text entered in the case of a text field. I’ve added the following code in my OnActivated method to build up a string containing these values which can be passed to the applications main page using rootFrame.Navigate:-

    	    string navigationParameter = null;
    
                switch (args.Kind)
                {
                    case (ActivationKind)1010: //ToastNotification:
                        StringBuilder sb = new StringBuilder();
                        sb.Append(args.GetType().GetRuntimeProperty("Argument").GetValue(args).ToString());
                        IDictionary<string,object> selections = (IDictionary<string,object>)args.GetType().GetRuntimeProperty("UserInput").GetValue(args);
                        if (selections.Count > 0)
                        {
                            sb.Append("?");
                            foreach (KeyValuePair<string, object> pair in selections)
                            {
                                sb.Append(pair.Key + "=" + pair.Value.ToString() + "&");
                            }
    
                            //remove trailing &
                            sb.Length -= 1;
                        }
                        navigationParameter = sb.ToString();
    
                        break;
                }
    This is just another way of adding value to the user while still maintaining a Windows Phone 8.1 codebase. If you later update your app to Windows 10 it’s very easy to do without much alteration to your code. You don’t even have to go as far as adding interaction to your toasts but you could use this technique of detecting the OS version and simply use the new toast templates.
    There are other areas of the Charming Apps libraries which “light-up” when running on Windows 10. For example there is a UWP style Clipboard API which just works on Windows 10 whereas the separate Clipboarder app is required for Windows Phone 8.1 (not Silverlight).

     

  • Charming Apps – Latest Version

    It’s been a few months since I did a NuGet release but lots has been going on in the code in the mean time. The focus this year has been less about harmonising Windows APIs across versions (although that’s still there of course), but widening the functionality to the Xamarin platforms. The result is that the vast majority of the APIs are now available across Android, iOS, Windows (UWP and 8.1) and Windows Phone (8.0, 8.1 Silverlight and 8.1 WinRT). In many cases I’ve added “light-up” support allowing Windows 10 functionality to be called from Windows (and Phone) 8.1 projects. This means you can write for maximum compatibility but take advantage of new features where available. The two packages are:-

    https://www.nuget.org/packages/InTheHand.Core/

    and

    https://www.nuget.org/packages/InTheHand.UI/

    As the name suggests the UI library separates out stuff which uses UI and so you can just use the former in a background task without worrying about dragging in UI dependencies.

    The APIs are all modelled on UWP, the only difference being the root namespace is InTheHand rather than Windows and async methods return Task<T> rather than IAsyncOperation<T>.

    The Core library features many namespaces around ApplicationModel – Interrogate app package metadata, make calls, send SMS and Emails, interact with Clipboard and Sharing. Beyond this are classes which take away the need to know which APIs to call on which platform – interrogate display properties, check network connectivity, read and write files and settings. This version extends the support for settings by supporting roaming settings on iOS just like Windows does – except these settings are roamed across the iCloud infrastructure rather than OneDrive. It’s important to add here that these settings only roam for devices on that specific platform type – Windows and iOS roaming data exist in separate worlds so data roamed from your iPhone Xamarin app won’t roam to your Windows laptop.

    AnalyticsInfo is available and can report the OS version on iOS/Android and Windows 10. This is supported in the 8.1 libraries if running on the newer OS version. DisplayRequest allows your app to ask the device to keep the screen on – for example for a reader or video player. PowerManager gives you battery information.

    Over in the InTheHand.UI library there are Badge and Toast notification APIs (Badge is not supported on Android). BadgeNotificationCreator and ToastNotificationCreator helper classes make it easy to create these notifications without having to deal with XML templates on Windows. A MessageDialog and a StatusBar which allows you to toggle a standard busy animation. On Windows there is also a unified SettingsPane API which uses the best available appearance depending on platform.

    Going forwards I’m looking at removing the Windows Phone 8.0 (and possibly 8.1 Silverlight) target to simplify things and would be interested in any feedback on that. As always all the code is on GitHub:-

    https://github.com/inthehand/Charming

  • Xamarin Forms Navigation Awareness

    Xamarin Forms offers a NavigationPage control which allows you to do linear navigation and integrates with the native Back button on Android and Windows. However from the individual Page it isn’t possible to tell how you arrived at the page. I had a situation in a project where I needed to know whether a page appeared via a forward or backward navigation. The Page control doesn’t have an equivalent to the OnNavigatedTo / OnNavigatedFrom methods that Windows has.

    I therefore came up with an implementation by writing a custom NavigationPage and adding an interface which a Page could optionally implement to expose the OnNavigatedTo / OnNavigatedFrom methods.

    To add the functionality you merely need to replace the code (probably in App.cs) which initializes your NavigationPage to e.g.

    MainPage = new InTheHand.Forms.NavigationPage2(new FirstPage());

    Then in the page you add the interface:-

    public partial class FirstPage : ContentPage, IPageNavigation

    An add an implementation of these methods. Visual Studio can generate these for you but remember by default these will throw NotImplementedExceptions

    public void OnNavigatedTo(InTheHand.Forms.NavigationEventArgs args)
    {
       switch (args.NavigationMode)
       {
          case NavigationMode.New:
             StatusLabel.Text = "Navigated forward to this page from " + (args.Page == null ? "<unknownpage>" : args.Page.GetType().ToString());
             break;
    
          case NavigationMode.Back:
             StatusLabel.Text = "Navigated backward to this page from " + (args.Page == null ? "<unknownpage>" : args.Page.GetType().ToString());
             break;
       }
    }

    The sample project on GitHub demonstrates a simple scenario with three pages and multiple ways of navigating between them. Each shows a status label showing how the user navigated to the page. Because it hooks into the NavigationPage it isn’t linked to any controls you set up to programmatically navigate, nor does it matter if a back navigation was initiated by a hardware back button, or a programmatic navigation.

  • Xamarin Release 7 Moved my Cheese/Apple

    I have a Xamarin project which outputs Windows, iOS and Android apps. Since the latest Xamarin update I just couldn’t get it to build my IPA file. It told me to check the project configuration – I haven’t changed the configuration and it all looks fine…

    When the project was created several Solution configurations were created – AppStore, AdHoc along with the usual Release/Debug. This was always a pain as you’d have to switch from Release to AppStore to build the iOS version for release. It turns out what has changed in this release is that Release now builds a store-ready IPA file and the AppStore configuration is now broken (and therefore redundant). By switching to Release I was able to build and submit a signed IPA to the store. The only other change is that IPA files are now output into timestamped subfolders on the build machine. You can use the “Show IPA file on Build Server” to display the actual location in Finder.

  • Tap, Tap, Tap, Tap, Bang!

    There are limitations to the write-once run everywhere approach of Xamarin Forms. One of these is the subtle difference in Button behaviour across platforms. One of our testers pointed out that you could rapidly tap a Button on Android and the handler would be called multiple times. Since the Tap was initiating a page navigation this would lead to multiple copies of the page being added to the back-stack.

    The workaround necessary is simply to add a timeout to ensure that the Tap event is not handled more frequently than a specified timeout. We chose 500ms but your use-case may vary. I created a renderer derived from the built-in ButtonRender and searched a way to intercept tap events. It turns out that a lot of the methods which can be overridden are never called but I found a solution through the excitingly named OnFilterTouchEventForSecurity. The resulting renderer code is included in the following Gist and can be added to your Android project to enforce this behaviour.


    using Android.Views;
    [assembly: Xamarin.Forms.ExportRenderer(typeof(Xamarin.Forms.Button), typeof(InTheHand.Forms.Platform.Android.SingleTapButtonRenderer))]
    namespace InTheHand.Forms.Platform.Android
    {
    public sealed class SingleTapButtonRenderer : Xamarin.Forms.Platform.Android.ButtonRenderer
    {
    bool justClicked = false;
    public override bool OnFilterTouchEventForSecurity(MotionEvent e)
    {
    if(e.Action == MotionEventActions.Up)
    {
    if(justClicked)
    {
    return false;
    }
    else
    {
    justClicked = true;
    global::System.Threading.Tasks.Task.Run(async () =>
    {
    // reset after a timeout
    await global::System.Threading.Tasks.Task.Delay(500);
    justClicked = false;
    });
    }
    return true;
    }
    return base.OnFilterTouchEventForSecurity(e);
    }
    }
    }

  • Xamarin Free For All!

    Yesterday Microsoft announced that the Xamarin platform (the ability to run C# apps on iOS and Android) would be free with all versions of Visual Studio 2015 Update 2. This is great news and takes away a barrier for developers to use their .NET skills to write cross-platform apps.

    We’ve had a number of free libraries for Xamarin for a while so I just wanted to post a quick reminder:-

    Charming Apps – Provides consistent UWP style APIs you can call across iOS, Android and Windows platforms for many common tasks. From reading the app manifest properties at runtime through to UI elements and integration with platform functions like SMS, Email etc.

    Xamarin Forms Maps Windows Renderers – Currently Xamarin Forms Maps only has renderers for iOS, Android and Windows Phone Silverlight. This package adds renderers for WinRT and UWP platforms.

    Device Picker – Currently only supporting Windows platforms this adds a UWP style device picker to Windows Phone 8.1 and Windows 8.1 projects.

    We’re continuing to extend the Charming apps libraries and will monitor as Xamarin Forms evolves…

  • Xamarin Forms Maps Windows Renderers

    It’s possible that with last week’s announcement Windows may no longer be the Cinderella alongside iOS and Android in the Xamarin Forms world. For the moment there are gaps to be filled and one of these is in Maps support.

    Xamarin Forms Maps has only (so far) shipped with a renderer for Windows Phone Silverlight apps. Some time ago I released a Windows Phone 8.1 Renderer via NuGet. The source is on GitHub here. Subsequently Windows 8 and Windows 10 support has been added. The latest stable NuGet package includes the Windows Phone 8.1 and Windows 10 UWP renderers. I decided not to include Windows 8.1 because it is a more complicated deployment as it requires the Bing Maps Extension SDK and has to be built for a specific architecture rather than a single “Any CPU” library.

    This new version is built against the latest Xamarin Forms Maps component (v2.1.0). It has some bug fixes around MoveToRegion and Clicked events for Pins. A future update will add support for IsShowingUser. Once again a single line of code is required in your Windows project App.xaml.cs to initialize the support, after which the map renderer and geocoder will just work:-

    InTheHand.FormsMaps.Init(<maps_token>);

    The token can be substituted with null for debugging purposes (the map control will display a banner).