Categories
Windows Xamarin

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…

Categories
Windows Xamarin

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).

Categories
Windows XAML

UWP and XAML CustomResource Markup

UWP doesn’t support writing custom markup extensions however there is one built in markup extension which is extensible. The CustomResource extension allows you to write XAML such as:-

<TextBlock Text="{CustomResource PortableStringResource1}"/>

In this case PortableStringResource1 is a unique key to refer to a resource in a source of your choosing. There is no out of the box implementation so you need to create your own class which derives from Windows.UI.Xaml.Resources.CustomXamlResourceLoader and provide an implementation of GetResource. Then in code which runs during your app start-up you create a new instance of your custom class and assign it to CustomXamlResourceLoader.Current. Then all requests are passed to your code to be resolved.

One place you may want to use this is where you are getting string resources from a different source than the modern resource system. In a pure UWP approach you can set an x:Uid for a XAML control then add string resources of the form MyId.SomeProperty to set the specified property from the resource. Another place you might have resources defined might be in a Portable Class Library. Because these work across multiple projects you might have string resources specified in a .resx file which you use with a number of projects (think Xamarin etc) and you may wish to also use these from a UWP client. Because of the way these resources are built into the UWP project you can access them via a Windows.ApplicationModel.Resources.ResourceLoader provided you specify the name of the resource set. This is the full namespace and classname of the generated class in the PCL. For example if your PCL has a base namespace of PortableClassLibrary and you have a resx file called StringResources.resx this is “PortableClassLibrary.StringResources”.

For the platforms where it is supported I’ve added a WindowsXamlResourceLoader class to InTheHand.UI. This can be used to refer to either resources defined in the UWP application resw or a named resource set in a referenced library. The source can be found here:-

https://github.com/inthehand/Charming/blob/master/Source/InTheHand/UI/Xaml/Resources/WindowsXamlResourceLoader.cs

An example of setting up the resource loader is called in the App.xaml.cs App() constructor:-

Windows.UI.Xaml.Resources.CustomXamlResourceLoader.Current = new InTheHand.UI.Xaml.Resources.WindowsXamlResourceLoader(typeof(PortableClassLibrary.StringResources).FullName);

The sample project for this blog contains the UwpClientApp and PortableClassLibrary projects to demonstrate the complete solution.

This is just one example of harnessing the CustomResource markup extension for your own use. You could write a resource loader to return values from any other source, you supply the glue to hook it together. The only limitation is you can’t really change the resource loader while dipping in and out of parts of your app so you need just one implementation. You could work around this by prefixing the key with different values linked to different sources…

Categories
Windows Xamarin

Xamarin Forms Windows Colours

When you work with custom renderers on Xamarin Forms (and it’s very difficult not to!) you often have to convert from Xamarin Forms types to their native platform equivalent. In the iOS and Android implementations Xamarin include some extension methods to easily convert Color to the native equivalent. Being the Cinderella of the Xamarin Forms platforms Windows platforms have missed out on this so I’ve filled the gap with this handy extension method:-

https://gist.github.com/peterfoot/be89d5b3c5ac4cc16ae1

This works for Windows Phone 8.1, Windows Store and UWP targets (sorry I haven’t created the Silverlight equivalent)

Categories
Windows

WebAuthenticationBroker Hints

Anyone who has tried to use the WebAuthenticationBroker beyond the simplest of scenarios has probably run into problems and sometimes all you want is a good descriptive error message. Getting things setup just right often takes a certain amount of trial and error so I’m documenting a few things here which are the results of a certain amount of trial and a considerable amount of error. This is as much a reminder for myself the next time I try and do this as it is (hopefully) some useful extra information for you.

Single Sign-in

If you can get the stars to align correctly, your OAuth endpoint can perform single sign-in on a corporate network. If you read the documentation you’ll see you have to specify the flag WebAuthenticationOptions.UseCorporateNetwork when you call AuthenticateAsync. This can be confusing because this flag isn’t needed when debugging when your app is given Intranet access automatically. To set this flag you also need to specify Enterprise Authentication, Private Networks and Shared User Certificates capabilities in your application manifest. Once you’ve added these you can’t submit the app through the public Windows Store.

A caveat to this is that you can only do single sign-in if your “web” application is setup with a redirect Uri which is the app package identity and you use the overload of AuthenticateAsync which doesn’t take a redirect Uri. This is the Uri returned from a call to Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri() at runtime. This identity will change between a side-loaded developer signed package and one which has been distributed through the Windows Store or a private company portal.

Error Codes

A lot of errors within the WebAuthenticationBroker process will result in a return status of WebAuthenticationStatus.UserCancel. However this is not always because the user has explicitly cancelled the process. The ResponseErrorDetail property returns an error code to give the reason and here are some possible values:-

0x800c0019 – An SSL failure. A common cause of this is that the clock is not set correctly on your phone/PC and it can often occur when your device battery went flat and it reset itself to some default date in 2014 and you’ve forgotten to correct it.

0x800c0005 – Network connection error. This is probably because you have no mobile signal and no WiFi.

This isn’t an exhaustive list but knowing the common error codes allows you to write a descriptive message for the user to hopefully resolve the problem themselves.

Categories
Charming Windows Xamarin

InTheHand.UI v9.0

I’ve updated InTheHand on NuGet and added the accompanying library containing UI functionality (InTheHand.UI). The main shared piece of functionality here is the MessageDialog (ala Windows.UI.Popups) and this works across all the Windows platforms (Including Windows Phone Silverlight) and iOS and Android. The appearance of the dialog is as the native experience with one exception…

MessageDialog.UWP.Native

We noticed on Windows 10 that the appearance of MessageDialog changed for our 8.1 app, rather than being a band across the width of the screen it was now a true floating window in its own right but this had one negative aspect – the title text appeared twice on the dialog. Users reported this as confusing and there is currently no workaround directly. In UWP apps there is now a ContentDialog control which is used for popping up content with up to two action buttons (you may recall this from Windows Phone 8.1) and so our implementation wraps this API on Windows 10 Desktop while exposing a single MessageDialog API. To avoid breaking the API we currently fall back to the system MessageDialog if you use three Commands. You can see a taste of the various flavours below:-

MessageDialog.Montage

The other functionality within InTheHand.UI is currently specific to Windows flavours and I’ll be discussing it in a future post.

Categories
Code Windows Xamarin

Build Charming Apps v9.0 Preview

With the impending release of Windows 10 I set about updating the Charming Apps libraries to support UWP targets and it soon became painfully clear that things had got too complicated. There was a separate dll for each small area of functionality and various dependencies and 17 NuGet packages to manage (each with multiple platforms).

Version 9 is a reboot of the project and currently consists of just two packages – InTheHand.dll and InTheHand.UI.dll. The first of these is now live on NuGet in preview form and replaces a number of old libraries and adds new stuff! During the MVP Summit I was able to spend the Hackathon rebuilding my development environment and refactoring the entire solution.

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

The API follows the UWP model where possible, making it familiar to Windows developers while extending both backwards to prior Windows versions and also sideways to Xamarin platforms. Also new in Version 9 is a PCL build which allows you to call the shared functionality from a PCL with the functionality itself provided by the platform specific dll in the consuming application. This is useful in scenarios such as Xamarin Forms projects.

For example InTheHand.ApplicationModel.Package provides a mechanism to query the current application package for name/version etc. This is the sort of information you might need for a custom About page or to pass to analytics etc. The InTheHand.ApplicationModel.DataTransfer namespace contains Clipboard and Sharing functionality which now supports Android and iOS too invoking the native experiences in each. The remainder of the InTheHand.ApplicationModel namespaces allow you to kick off a number of tasks such as SMS, Email etc. Other namespaces exist for querying display properties and battery state.

All the code is on GitHub and a very rudimentary version of documentation is in the project Wiki. Most of the documentation in CodePlex still applies too and will be migrated in due course.

https://github.com/inthehand/Charming

Coming in the InTheHand.UI package are InTheHand.UI.Popups (MessageDialog) and InTheHand.UI.ApplicationSettings (currently Windows platforms only) both of which have some neat Windows 10 specific tweaks.

Categories
Windows Xamarin

Xamarin Forms Password Entry on Windows Runtime

Xamarin Forms doesn’t have a specific PasswordBox control – instead you use the Entry (Think TextBox) and set IsPassword to true. Normally this works as expected and provides a masked entry box. However there is a known issue on Windows Runtime (Phone and Desktop) where AutoSuggest and Auto Capitalisation are not disabled for a Password field. Luckily there is a workaround which is to set the input keyboard to Email. The small side effect is the addition of a “.com” button to the keyboard but it will stop the control capitalising the first letter or showing suggestions based on what you are typing. I added the following code behind:-

if(Device.OS == TargetPlatform.Windows)
{
   txtPassword.Keyboard = Keyboard.Email;
}

This issue doesn’t affect Silverlight apps (TargetPlatform.WinPhone) and I decided not to set the keyboard on other platforms as they work correctly with the default keyboard.

Categories
Windows

ShowEditNewAppointmentAsync Weirdness

The Windows.ApplicationModel.Appointments namespace in Windows 8.1 (and Windows Phone 8.1) provides access to the user’s calendar. Prior to Windows 10 there were big differences in the APIs as Phone had the existing capability to extend the calendar with app-specific calendars. Now the API is unified across Windows devices but there are some changes to be aware of which will affect existing apps as well as new ones built for Windows 10.

On Windows Phone 8.1 there were two APIs for displaying a new appointment – ShowEditNewAppointmentAsync shows the edit view with the fields pre-populated with the Appointment object you supply. The second API is ShowAddAppointmentAsync which is shared with Windows 8.1. On Phone however it would display the same edit view as ShowEditNewAppointmentAsync. The screen co-ordinates you pass are ignored as the dialog is fullscreen.

On Windows 8.1 only ShowAddAppointmentAsync existed and this displayed a read-only popup view of the passed in Appointment. With just the option to save or discard the appointment (and ability to select which calendar to save in if you have multiple accounts).

If you call either of those two APIs for Windows Phone on a Windows 10 Mobile device you’ll get a different experience. Now you see a read-only fullscreen dialog showing the details of the appointment but you can tap an edit button in the appbar to fully edit the item. You’ve not lost any functionality as such but it is an extra step to get to an edit screen which is especially annoying if that is what you specifically requested.

Calendar Display > Calendar Edit

If you call either of those APIs on a Windows 10 PC you’ll get the Calendar app which will show a read-only view of the appointment with the ability to save or discard. There is no edit functionality available at all. If you’re running in Tablet mode Calendar will launch fullscreen, otherwise it just pops up a window over your app. It will be much bigger than the popup used in 8.1.

ShowEditNewAppointmentAsync
What’s wrong with this? Given the Calendar application is shared across both device types I’d expect the full version to support editing like the mobile one does. If you click “New Event” in the Calendar app you get an edit screen – this is what I’d expect from ShowEditNewAppointmentAsync. I’d also expect the same edit button on the read-only view.  I’d expect ShowEditNewAppointment to open the edit view by default – otherwise there isn’t any point in having two different APIs which do the same thing. I’m hoping that with Mobile still not finished there is time to fix that, or maybe it just needs a tweak to the Calendar app.

Categories
Bluetooth Windows

32feet and Windows Apps

Some time ago I created a subset of 32feet.NET to extend the Bluetooth functionality in Windows Phone 8.0. This was for the Silverlight app model and the only API at the time was based around the Proximity APIs. When Windows Phone 8.1 came along it brought a whole new Bluetooth (and Bluetooth LE) API which was, for the most part, consistent with Windows 8.1. I never got around to updating my code for this model.

Looking forwards Windows 10 is just around the corner and the UWP app model includes this same consistent API, with a few additions, across all the flavours of Windows – IoT, Phones and all shapes and sizes of PC. This time I went back to the drawing board and looked at what functionality was missing and could be added in.

One of the new APIs in Windows 10 is the DevicePicker in Windows.Devices.Enumeration. This is not strictly Bluetooth functionality – any class of device which can be enumerated can be used with it. However it serves as a Bluetooth device picker just fine. Since Windows 10 on phones is a little further away than the imminent launch on the desktop I thought there was a good case for providing this UI now to Windows Phone 8.1 apps and showing how to wrap it to pick Bluetooth devices. Thus you can easily reuse the same code in a Windows 10 project further down the track. Thus the InTheHand.Devices.Enumeration.DevicePicker was born. It uses the same API the exception being that screen rectangles passed in are ignored for Windows Phone as it uses a ContentDialog to pop up the selector. You can still customise the foreground/background and accent colors to match your app. For example the sample code displays this:-

32feet DevicePicker

To use the DevicePicker for Bluetooth devices you need to first have the capabilities set correctly in your package manifest (see here for details). Then assuming you have a button or similar to allow the user to start the selection process you can use the following code:-

string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush);

DevicePicker picker = new DevicePicker();
picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33);
picker.Appearance.ForegroundColor = Colors.White;
picker.Appearance.AccentColor = Colors.Goldenrod;

// add our query string
picker.Filter.SupportedDeviceSelectors.Add(aqs);

// prompt user to select a single device
DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect());
if (dev != null)
{
   // if a device is selected create a BluetoothDevice instance to get more information
   BluetoothDevice device = await BluetoothDevice.FromIdAsync(dev.Id);

   // or get the service which you can connect to
   RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(dev.Id);
}

The CodePlex project includes the source code and two samples – one showing the device picker and retrieving device information, the other a Chat application (which is interoperable with the existing 32feet BluetoothChat sample on other platforms. The binaries for the DevicePicker are up on NuGet in this package.

That covers off device selection, the other main area I knew needed some attention is Service Discovery. The Windows API provides the ability to supply custom SDP attributes when creating a service (or as mentioned in a previous blog post an “extension” record containing custom attributes). It also gives the ability to retrieve SDP records. However in both cases it uses IBuffer (the WinRT equivalent of a byte array). Therefore the other part of the new 32feet project is a set of functionality for building (and eventually parsing) SDP attribute values and records. I haven’t published this to NuGet yet as I’m still working on it but the code is there if you fancy a look.

So the next step for 32feet on Windows is a DevicePicker for 8.1 which allows you to painlessly move your code forward to 10, and a portable SDP library which will work with 8.1 and 10 and possibly outside of Windows platforms too in the future…