November 21, 2014 8:58 GMT

Pull/Swipe To Refresh for Xamarin.Forms Android Apps

It is true that I absolutely love cross platform settings for mobile applications built with Xamarin. However, there is something that I love even more… Pull To Refresh!



It all started over year ago when I blogged about how to add a UIRefreshControl to MVVMCross iOS apps. Google then introduced an official SwipeRefreshLayout for Android , so naturally I blogged about adding this new layout to your MVVMCross Android applications. With the release of Xamarin.Forms to build iOS, Android, and Windows Phone apps UIs from one shared C# code base things got a little bit more interesting. Since everything was shared logic even for the UI you had to do a little bit more work to get pull to refresh working on iOS with a custom renderer and view. Yet again I got the source code up and running and blogged about it as well. I am back for a fourth blog after much effort, work, and help from Jason to get a Pull To Refresh for Xamarin.Forms Android apps :)

Getting Started

There are a few things to understand about the SwipeRefreshLayout and also about Xamarin.Forms before we get started. The SwipeRefreshLayout is part of the Support v4 Library, which you can find on NuGet, and at it’s core it is just a ViewGroup and acts as a FrameLayout that you can add Android Views to it. You can read all about it’s properties on Google’s Android documentation website. On the Xamarin.Forms side of things there is a great extensibility model using custom renders to customize controls or add your own controls to Xamarin.Forms. So using this concept I thought it would be a nice idea to use a ContentView as my base control to inherit from and add bindable properties to trigger a refresh and execute a refresh command. This will look very similar to the iOS version except that I had inherited from a ListView for iOS:



Custom Renderer

Normally you would pick from a set of pre-built Renderers that are built into Xamarin.Forms to do your customizations. Or you can inherit from a ViewRenderer for a custom view, which is really nice. The issue here is that we will need access to add and remove Child views from the SwipeRefreshLayout. So, while these base Renderers provide a lot of great things built into the framework such as handling most of the property changes, the issue we will run into is there is no ContentViewRenderer and even using a ViewRenderer we will not be able to accomplish our goal (trust me I have tried). This is when Jason led me onto Xamarin.Forms capability of doing everything yourself by subclassing SwipeRefreshLayout itself and implementing IVisualElementRenderer, which is an interface that enables you to make any control a Xamarin.Forms control.

public class FormsSwipeRefreshLayout : SwipeRefreshLayout, IVisualElementRenderer, SwipeRefreshLayout.IOnRefreshListener

The caveat here is that you have do ALL of the manual work to set it up and get it working. There are a few helpers though to get you going and once you understand how it actually works it is really simple to create them.

IVisualElementRenderer Implementation

Here is our default implementation of IVisualElementRender:


Now this might look a little scary, but let’s break it down one step at a time. SetElement is actually the largest amount of work. This is where we will setup the control and register for property change events. This method will also fire off the ElementChanged event whenever it is called. In this instance we only ever want to initialize once and we will save the “ViewGroup” that is added as the ContentView to our Xamarin.Forms control so we can add it later on.



The rest of the code is actually really simple and is just a bunch of getters and setters since we already set most of this up in the SetElement Method. The only real work we need to implement is measure any children that we have added as sub views:



Almost there!

With this code in place we are basically done, but we will run into a few issues when we run the sample because the SwipeRefreshLayout doesn’t actually know when it is allowed to be pulled or when it should disable itself. The CanChildScrollUp method of the SwipeRefreshLayout is what handles this, and it usually expects a ListView or ScrollView to be the first child, however there seems to be some quirks with how Xamarin.Forms is laying out the controls (or maybe how we are). So, we just need a bit of logic to tell the SwipeRefreshLayout when the ListView is allowed to scroll up.



That’s it! With the refresh control in place we can now add this into our shared code to see it in action!

Limitations

Mostly, this is really proof of concept and I need to do a bit more work to really make it bullet proof. It is extremely functional, but here are the current limitations.
  • Only works with ListView set as Content of ContentView
  • IsRefreshing Binding only goes 1 way from ViewModel down to Control (will be fixed in 1.3.X of Xamarin.Forms)
  • You must manually SetColorSchemeResources in code behind (no bindings here yet, but I accept PRs)
  • No support for other normal bindable properties of a ContentView such as BackgroundColor (again, I support PRs)

Get the Code!

As always ,you can get the code from my GitHub account. I have created a new special repository where this code lives called “Xamarin.Forms Awesome Controls”, that houses a few custom controls I have done and the iOS pull to refresh implementation. This is where I will be putting all of my code in the future to ensure it is easy to find and doesn’t clutter up my GitHub. I hope that you enjoyed this post and find it helpful. It is truly proof of just how extensible Xamarin.forms is.
November 21, 2014 7:06 GMT

Get Started with Xamarin.Forms via the Evolve Mini-Hack

As part of the Evolve Darwin Lounge, we had a bunch of small coding exercises for a variety of topics that attendees could complete to win a prize. One of the mini-hacks from Evolve 2014 involved creating a simple application with Xamarin.Forms. This is a nice example to try out Xamarin.Forms yourself.

Let’s take look at how to do this mini-hack. We’ll be creating the Magic 8 ball application shown below:

app screenshot

1. Create a new Xamarin.Forms solution called MagicBall (I’m using the PCL project here):

new solution

2. Add a ContentPage named BallPage to the shared project:

content page

3. Edit BallPage.xaml to contain a StackLayout with an Image, Label and Button respectively. Also add some padding to the top of the page:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
  xmlns="http://xamarin.com/schemas/2014/forms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  x:Class="MagicBall.BallPage"
  Padding="0, 30, 0, 0">
  <ContentPage.Content>
    <StackLayout>
      <Image Source="ball.png"></Image>
      <Label x:Name="label" Text="Magic 8 Ball" Font="Large"
        HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
      <Button x:Name="button" Text="Tell Me!" HorizontalOptions="Center"
        VerticalOptions="CenterAndExpand" Clicked="ButtonClicked" />
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

4. Add code to BallPage.xaml.cs to update the label randomly from an array of strings when the button is clicked:

public partial class BallPage : ContentPage
{
  string[] options = {" It is certain"
        , " It is decidedly so"
        , " Without a doubt"
        , " Yes definitely"
        , " You may rely on it"
        , " As I see it, yes"
        , " Most likely"
        , " Outlook good"
        , " Yes"
        , " Signs point to yes"
        , " Reply hazy try again"
        , " Ask again later"
        , " Better not tell you now"
        , " Cannot predict now"
        , " Concentrate and ask again"
        , " Don't count on it"
        , " My reply is no"
        , " My sources say no"
        , " Outlook not so good"
        , " Very doubtful "
  };
  public BallPage ()
  {
    InitializeComponent ();
  }
  void ButtonClicked (object sender, EventArgs args)
  {
    label.Text = options [new Random ().Next (options.Length - 1)];
  }
}

5. Update App.cs to return a BallPage:

public class App
{
  public static Page GetMainPage ()
  {
    return new BallPage ();
  }
}

6. Add the ball.png image to the Resources folder on iOS and Resources/drawable on Android.

7. Run the application and ask the 8 ball for advice.

The code for this mini-hack is available here: https://github.com/xamarin/mini-hacks/tree/master/Xamarin.Forms/solution/MagicBall

Update:
Craig Dunn has a solution in his repo that includes a Windows Phone project as well.

November 21, 2014 12:00 GMT

Mobile Essentials: Productivity Tools for Mobile Developers

A bunch of mobile development and tooling enthusiasts here at the office wanted to put out some tools, templates and general productivity enhancements for mobile developers, so we decided to set up a custom Visual Studio gallery that you can set up to get these tools in an integrated fashion in the Extensions and Updates dialog (a.k.a. Extension Manager). These will generally be projects we work on the side, on weekends and nights and hackathons.

The goal of these extensions is to be completely independent of your other tools in VS (like your Xamarin installation) so that you can try them without risking breaking your stable development environment. If something doesn’t quite work, you just remove the extension and you’re done. Pristine environment back!

At Xamarin, we may use this gallery also for early prototypes or spikes we do on top of the Xamarin Platform, so that we can gather early feedback without disrupting your stable installation and without requiring you to switch between official channels. Whatever we put out will be for use “at your own risk” so to speak. As I said, it could become a way for us to also share bits earlier and get timely feedback for things that may make it into the core product. It also would allow us to discard ideas that don’t get traction :).

The source code for the gallery itself as well as installation instructions are available on GitHub. I’m copying the instructions here for convenience:

Mobile Essentials Gallery Beta

The Mobile Essentials Gallery provides a custom Visual Studio Gallery (also called Private Galleries, but ours is pretty public ;)) with experimental and early prototypes and tools for mobile development on the Xamarin platform.

All extensions are provided free to use and experiment. We welcome your feedback on the tools at our UserVoice forum!

Installing

In order to get the new gallery in your Visual Studio 2012 (or later), open Tools | Options and configure the page Environment > Extension Manager as follows:

Gallery Setup

Once the gallery is set up, you can go to Visual Studio’s Tools | Extensions and Updates... menu and a new Mobile Essentials node will appear under the Online category, where you can explore and install the tools:

Using the Gallery

Updates also show in this same window, under the respective category Updates > Mobile Essentials:

Using the Gallery

Remarks

As you can see, one of the first extensions we’ve uploaded is an initial version of Xamarin.Forms intellisense. You probably guessed that that’s one that will definitely make it into the main Xamarin installation in the future ;).

November 20, 2014 4:17 GMT

Real-Time Code Iteration with Sketches

Sketches are a powerful new feature that we announced as a preview release at Xamarin Evolve in October. With Sketches, developers can iterate on code within Xamarin Studio and immediately see the results, without having to go through a full build and deploy cycle.

Sketches

A sketch is a file that stands alone or can be contained in a project, making it easy to move experimental code from a sketch into a code base. In some ways, it’s the immediate window on steroids.

For example, say you want to inspect the result of some code such as :

var x = 1;
var y = 2;
var z = x + y;

Sketches use a REPL (read–eval–print loop) that evaluates the code and displays the results:

sketch results

Viewing Output

There are visualizers for the output built in, too. For instance, a color is displayed as shown below:

color visualizer

You can even pin the results to the output area:

color output

Additionally, the output can display graphs of data:

output graph

Visualizing Images

The visualizer can display other types of data, too, such as images:

image visualization

Graphics Code

Having image support is nice, because it allows you to write arbitrary graphics code in a sketch and render it to an image. For example, here’s a code snippet from a blog post I wrote a while back, showing the rendering of some Core Graphics drawing code (updated for the unified API) in an iOS sketch:

// Sketch your next great idea!
using UIKit;
using Foundation;
using CoreGraphics;
//
UIGraphics.BeginImageContext (new CGSize (320.0f, 300.0f));
using (var gctx = UIGraphics.GetCurrentContext ()){
  gctx.SetLineWidth(4);
  UIColor.Purple.SetFill ();
  UIColor.Black.SetStroke ();
  var path = new CGPath ();
  path.AddLines(new CGPoint[]{
    new CGPoint(100,200),
    new CGPoint(160,100),
    new CGPoint(220,200)});
  path.CloseSubpath();
  gctx.AddPath(path);
  gctx.DrawPath(CGPathDrawingMode.FillStroke);
}
var image = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();

This renders a triangle in the sketch, as shown below:

Core Graphics sketch

Visualizing Views

Visualizers aren’t limited to just images. You can display views as well, such as a UIView on iOS or an NSView on OS X. For example, here is an NSBox with a border:

view visualization

Where sketches start getting even more compelling is when you start using them to modify code running in the iOS simulator and the Xamarin Android Player. For example, here is some Xamarin.Forms code created on the fly in a sketch, running in the Android Player:

forms sketch

To learn more about Sketches, check out the documentation in our developer center and the Sketches’ samples. Also see Aaron Bockover‘s great talk from Evolve.

November 20, 2014 1:50 GMT

Help Test the Future of Xamarin.Mac

Xamarin.Mac and Xamarin.iOS have always been close sister projects, sharing much of their underlying tooling and infrastructure. One of the features in the upcoming version of Xamarin.Mac that we are very excited about is the runtime unification.

Underlying any application that uses Xamarin.Mac (or Xamarin.iOS) is a runtime that manages interactions with the objective-c runtime. It handles exposing your C# objects to objective-c and your calls into various Apple APIs. Up until now we had two separate runtimes, one for iOS and one for OS X.

The runtime unification effort changes that, we now have the same runtime powering our Mac and iOS products. This will bring bug fixes and performance work done on iOS to OS X and enable many of the features that were pioneered in iOS to come to the Mac platform,  such as the new refcount system.

While we have worked hard to test these runtime changes internally, such a far reaching change has the potential to introduce bugs in many places.

We are releasing a preview version of the upcoming Xamarin.Mac to the alpha channel for an extended period of time for testing.

While the runtime unification work is the major feature of this preview release, this alpha also adds support for these 64-bit frameworks:

  • Accounts
  • GameController
  • EventKit
  • MapKit
  • MediaAccessibility

in addition to the frameworks provided in the previous alphas:

  • CloudKit
  • GLKit
  • JavaScriptCore
  • LocalAuthentication
  • SpriteKit

We are asking you to test your applications with it and report any issues you might find.

November 19, 2014 11:18 GMT

Xamarin.Forms And Resources

ResourcesOften, there will be multiple views in your form that share the same values (e.g., font size, color, etc.).  There are a couple ways you can handle this:

  • Create a resource dictionary and then refer to the resources using the key and the keyword StaticResource
  • Declare constants and then refer to them using x:Static

While the names are very similar, x:Static and Static resources work differently.  The former access a public static constant  (or a public static property defined by a class).  The latter, static resources, is a markup extension supported by xAML that depends on the creation of a resource dictionary.

Let’s look at how you might use both.  More…

November 19, 2014 6:19 GMT

Xamarin Insights and the Azure Outage

On November 18, 2014 at about 5:00PM PST, Xamarin Insights experienced a service disruption due to a worldwide outage of Microsoft Azure. In addition, we had been experiencing partial outages at least 5 hours prior to this.

Even though Azure suffered a catastrophic storage failure, our event collection API – the web service that receives telemetry from every mobile app that has the Insights client library running – was able to receive and store reports during the entire outage. This means that we experienced zero data loss during this down time.

Even if our event collection API had been overwhelmed or inoperative, the Xamarin Insights client library has a smart queueing system which queues reports locally on end-user devices, and sends them once service is restored.

Our services that process the telemetry data have fully caught up on the backlog of data that was collected during the Azure outage. The aggregate statistics displayed in the graphs and various “counts” are lagging about an hour behind, but will continue to catch up throughout the rest of the day.

Insights - Azure

A graph showing the backlog of telemetry data. Notice the 3 minor hiccups before the outage.

Our goal with Xamarin Insights is to provide a real-time, comprehensive app monitoring service that helps you understand exactly how well your app is performing. We are gratified that the architectural decisions we’ve made so far have paid off in challenging circumstances, and we’ve learned a lot from this outage about how we can improve Insights in the future.

To learn more about Xamarin Insights to add real-time monitoring to your mobile applications check out xamarin.com/insights.

November 19, 2014 3:00 GMT

Episode 20: Mobile Web Performance with Tammy Everts

Performance matters, especially when it comes to mobile development. Join us as we talk to Tammy Everts about the ins and outs of mobile web performance!

Hosts: Greg Shackles, Jon Dick

Guests: Tammy Everts

Links:

Thanks to our Sponsors!

Raygun.io

Raygun.io – Exceptional Error Tracking Raygun.io is the fastest and easiest way to track your application’s errors and get the level of detail you need to fix crashes quickly. Notifications are delivered right to your inbox and presented on a beautiful dashboard.

November 19, 2014 12:33 GMT

Live Webinar: Mobile Enterprise Success with Xamarin and IBM

We recently announced our collaboration with IBM, allowing businesses to build fully native iOS, Android and Windows Phone applications with shared code – while also leveraging IBM Mobile First Worklight’s robust integration, security and connectivity. With this partnership, enterprises are able to deliver both the UI quality consumers demand and the enterprise-grade backend and reliability that corporations require.

IBM and Xamarin Logos

Join IBM and Xamarin technical executives on Thursday, December 11 at 8 am PST/ 11 am EST/ 5 pm GMT for a live webinar as they discuss the IBM and Xamarin partnership, demo the IBM MobileFirst SDK for Xamarin, walkthrough the IBM Worklight platform and answer any developer questions.

Ken ParmeleeKen Parmelee
IBM Business Development Executive & Program Director, MobileFirst

Dustin AmrheinDustin Amrhein
IBM Mobile Technical Leader, MobileFirst


Steve HallSteve Hall
Xamarin Director of Enterprise Mobility


We’ll send a recording after the webinar, so we encourage you to register even if you’re unable to attend.

Register Now


November 18, 2014 7:14 GMT

An Improved Cross-Platform Settings Library for iOS, Android, and Windows

If you follow me at all on GitHub or Twitter than you probably know that I love portable class libraries. I know this might sound odd, but I also love settings inside of mobile applications. NSUserDefault, SharedPreferences, IsolatedStorage… yup I love it. A few years back when I was doing a lot of MVVMCross development I created Mvx.Plugins.Settings to enable developers to save settings and preferences extremely easily from 1 common API. Under the hood though I am taking advantage of each platforms native method of saving and retrieving settings. To me this is the best approach especially on Android where you can create an entire settings screen from an XML file!

Settings Everywhere

Back in March, I updated my settings plugin to be completely generic from any framework. This means anyone can use it no matter if you are developing with traditional Xamarin, Xamarin.Forms, or MVVMCross. Today, I am pleased to announce a brand new update, 1.4.0.0, that brings a flurry of enhancements and fixes.

Enhancements

Over the last several months I have added support for Windows 8.1 and Windows Phone 8.1 RT development and in this latest version I bring full support for Xamarin.iOS Unified projects.

Simplified API

I have received a lot of feedback over the year on how the API worked. The biggest issue was that I enforced that you first attempt to “Update” the setting and then call “Save” to actually store the value. This is nice if you wanted to do batch saving of settings, however it was very annoying and created extra code. I have listened and created an even easier API:



There you have it, simply get and set from the settings and the library will handle the rest for you.

Data Types

I have also expanded the datatypes that you can store:
  • Boolean
  • Int32
  • Int64
  • String
  • Single(float)
  • Guid
  • Double
  • Decimal
  • DateTime

Bullet Proof

In addition to all of these enhancements I wanted to make sure that going forward anyone would be able to pull down the library, make changes, and do a full regression test. I have built out a full NUnit test library to ensure the highest quality for the library.

Get it today

As always you can get the entire source code on the GitHub project where you can contribute to the project. Additionally, you can get the NuGet today.
November 18, 2014 1:10 GMT

Getting Started with the Xamarin Android Player

Slow emulators and fragmentation xamarin-android-playerare two of the main frustrations for Android developers. Android emulators are slow to boot and perform poorly, but buying multiple devices to debug an application for multiple API levels isn’t an affordable (or scalable) solution. Neither of these scenarios are ideal for real world mobile development.

At Xamarin, our customers told us they were struggling with slow emulators, so we developed the Xamarin Android Player, introduced at Xamarin Evolve 2014. It can be downloaded from its dedicated page.

Blazing Fast Emulator

Xamarin Android Player Pic 2The Xamarin Android Player runs Android x86 virtual machines using hardware accelerated virtualization technology and is available on both Windows and Mac OS X. It supports OpenGL, delivering smooth, fast graphics. With these features, and a boot time of as little 17 seconds, it’s a blazing fast Android emulator. It also tightly integrates with Visual Studio and Xamarin Studio, so that developers can build, deploy, and debug their apps right from their favorite IDE. Additionally, you can run the Xamarin Android Player side-by-side with the Windows Phone Hyper-V emulator without any conflicts for a great development experience on Windows.

Getting Started

After installing Xamarin Android Player you will be able to browse from a selection of Android images featuring different API levels. Once you have an image installed, you are able to start the player directly from Visual Studio or from Xamarin Studio’s debug on device option.

Xamarin Android Player Images

Even More Features

The Android Player can also emulate different properties of devices, including battery percentage, volume levels, GPS location, and screen orientation. This allows you to try your application in different scenarios. You can even take a screenshot of your running application.
Xamarin Android Player - Pic 3

Download Now

The Xamarin Android player is available to all Xamarin users with an active Xamarin.Android trial or full Xamarin subscription, and the Xamarin Android Player documentation and release notes are great places to help you get started with it today!

November 17, 2014 12:00 GMT

Installing Xamarin for Visual Studio 2015 Preview

By now you probably got the blurb of last week’s Microsoft announcements:

Microsoft Takes .NET Open Source And Cross-Platform

TechCrunch - Frederic Lardinois “Unsurprisingly, the company plans to work with the Xamarin-sponsored Mono community, which already produces a cross-platform open source .NET framework based on C#. “We will announce this and then take the next few months working with the Mono community,” Somasegar told me. “We are working very closely with the Xamarin guys on this.”

With .NET turnaround, Microsoft wants to create ‘one big family’ with open-source community

GeekWire - Todd Bishop “Miguel is still the man!” said an enthusiastic S. “Soma” Somasegar, the corporate vice president in charge of Microsoft’s Developer Division. Somasegar made the comments in an interview discussing the company’s plan to open-source .NET and make it possible to use Microsoft’s developer technologies to make software for — you guessed it — Mac, Linux, Android and iOS. Microsoft is working on the initiative with the Mono community and the startup Xamarin, which de Icaza co-founded.”

Microsoft open-sources server-side .Net, launches Visual Studio 2015 preview

InfoWorld - Simon Bisson “This doesn’t mean the work on cross-platform client-side .Net will stop. “We’re going to continue partnering deeply with Xamarin,” Somasegar says. That’s borne out by the upcoming release of Visual Studio, which will make it easier to add Xamarin tools to support iOS and Android development alongside Windows apps.”

As a testament of our close collaboration with Microsoft, we shipped same-day support for Android Native C++ projects in VS 2015, as well as deep integration with Microsoft’s Hyper-V based Android Emulator.

The experience basically is that now in VS 2015 you have two new templates for Android and iOS:

New Android App

New iOS App

Launching any of those two templates will create a project that is like an introduction to the product and links to download it (similar to what the Azure templates do when you don’t have Azure SDK installed):

Install Xamarin

Now you can just click that download button, and get the new integration for 2015!

If you happened to have a previous version of Xamarin for Visual Studio installed, please keep reading as you may not have gotten the 2015 bits installed by default (it’s something we’re fixing shortly).

Ensuring 2015 support is installed (only for previous Xamarin users)

By default, Windows Installer will just update the components you have previously installed, when applying an update. Since you previously didn’t have 2015 components installed, then by default you won’t be getting them installed right now. (we’re fixing that soon-ish).

Don’t worry, you don’t have to go download anything again, here are the easy steps to ensure you turn the bits on for 2015:

1 - Go to Add/Remove programs and search for Xamarin:

Add/Remove Xamarin

2 - Click Next on the installer window and select Change on the next screen:

Change MSI

3 - Finally, make sure you check and install locally the Visual Studio 2015 feature:

Install 2015 Feature

After the installer is done applying your changes, the old “starter” templates will be gone and you’ll be greeted with a bunch of template that you’re surely familiar with already (since this section applies to existing users only ;)).

In a future post I’ll delve a bit more on how we’re integrating with Microsoft C++ Android Native projects (hint: you can just add a project reference! ;)).

Enjoy!

November 16, 2014 2:47 GMT

Cross-Platform Desktop UIs

In almost every city, I’ve been asked to recommend a Xamarin.Forms style library for developing desktop applications. In this blog post I’m going to give an overview of the different options available to desktop developers who wish to target Windows, Mac and Linux.

TRADITIONAL APPROACH

 

xplatDesktop

The first approach is what we’ve named at Xamarin the ‘traditional’ approach. You’ve probably seen this approach, but for mobile. The general idea is that you should implement your user interface uniquely for each platform you wish to target. This means on Mac, you would use Cocoa (Xamarin.Mac), Windows would use WPF and Linux would use Gtk (Gtk#). This approach will guarantee that your desktop application looks and behaves as the platform users expect. It also means that your application looks great if Apple, Microsoft or the OpenSource community decide to update the look and feel of the underlying OS. It’s also worth noting that with this approach you gain 100% access to every UI control and API available in the UI libraries, and won’t be limited in your ability to create beautiful experiences for your users.

In case you’re in any doubt, this is the approach I recommend you take when developing your apps. This is actually the approach Xamarin has started to use for our new products. You can see this in action with our Profiler and Android Simulator; both of these use WPF on Windows, and Xamarin.Mac (Cocoa) on OS X.

XWT

xwt

Much like Xamarin.Forms, Xwt allows you to use one API that maps to the native widgets of the platform. This means your application when running on Windows will be using WPF widgets, on Mac its Cocoa, and Linux is Gtk. This results in a 100% native user interface on three platforms from one codebase. Much like Xamarin.Forms, because its aim is to create a unified API for all desktop platforms, it only maps to a subset of widgets and properties. It’s worth noting that with Xwt you still have the ability to implement a native widget which isn’t mapped as part of the API.

For all platforms you can use the native engine, or the Gtk engine. If you’re wondering what a Gtk app looks like on Windows and Mac, then I recommend downloading Xamarin Studio. This is primarily built using Gtk, and in areas actually uses Xwt. On Windows the native engine is WPF, on OS X its Cocoa, and on Linux it remains Gtk (using Gtk#).

Learn more here: https://github.com/mono/xwt

WEBVIEW

One other option you might want to consider, is using a WebView for your user interface whilst maintaining a C# backend. This is the approach that Rdio has taken for their OS X client, and to a novice it’s difficult to spot that it’s not a native app. This approach can produce some great looking applications which can even run in the Cloud, but it would be difficult to claim you’ve created an application when the reality is you’ve packaged up a website.

QTSHARP

Although this approach is not yet ready for consumption, I thought I would mention it as it’s a project on GitHub that excites me. Much like Xamarin.Mac is a binding to the Cocoa framework, a group of enterprising .Net developers are aiming to create a .Net binding to the Qt library. Having used Qt in a previous life, I can confirm that the UIs can often be a little hit or miss (because it’s a lowest common denominator approach). That said, if you’re developing an internal application, or willing to take the time to craft the UI for each platform (different layouts for each platform) then it can work really well.

The project is still in its infancy, and many developers have tried and failed at this approach. Its not ready for production as yet (it doesn’t appear to even be close) but its a great start. My fingers are crossed that the developers continue to invest their time in the project, and the .Net community gains access to one of the most widely used cross-platform user interfaces frameworks in existence.

The post Cross-Platform Desktop UIs appeared first on Mike James.

November 16, 2014 10:00 GMT

Installing Portable Class Libraries for Xamarin Studio

In order to use Portable Class Libraries (PCLs) with Xamarin Studio you need to have the following installed:

  • Portable Class Library Reference Assemblies.
  • Portable Class Library MSBuild targets.
  • Xamarin’s Portable Class Library Profiles.

If you do not all of the above installed then you may run into the following problems when using Xamarin Studio.

  1. Unable to create a Portable Library project since the project template is not available.
  2. Unable to install a NuGet package, such as Json.NET, that contains PCL assemblies into an Android or iOS project. Example error message below:

    Could not install package ‘Newtonsoft.Json 6.0.6’. You are trying to install this package into a project that targets ‘MonoAndroid,Version=v4.4’, but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

On the Mac the Portable Class Libraries for Mono 3.10.0 are installed into the directory:

/Library/Frameworks/Mono.framework/Versions/3.10.0/lib/mono/xbuild-frameworks/.NETPortable

On Windows the Portable Class Libraries are installed into the directory:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable

So let us take a look at how to install everything required to get PCLs fully supported within Xamarin Studio.

Mac – Installing Portable Class Libraries

The Portable Class Libraries are included with the Mono Development Kit (MDK) but not with the Mono Runtime Environment (MRE). If you are installing Mono yourself instead of using Xamarin’s Universal Installer then you will want to install the MDK instead of the MRE. The MDK includes the MRE as well as extra tools, libraries and the .NET Portable Class Library profiles.

If Mono is updated from within Xamarin Studio using Check for updates then the MDK should be installed.

Windows – Installing Portable Class Libraries

Xamarin Studio on Windows uses Microsoft’s .NET Framework instead of Mono so the Portable Class Libraries need to be installed separately. To install the Portable Class Libraries on Windows you have three options:

  1. Install Visual Studio 2013 (full or Express version). Update 2 or above is required.
  2. Install the Portable Library Tools and the Portable Library Reference Assemblies 4.6.
  3. Install the Portable Library Tools and copy the .NETPortable directory from Mono over to Windows.

If you do not want to install Visual Studio 2013 then you should look at options 2 or 3.

One problem with option 2 is that not all the .NET Portable profiles, such as Profile 259, will be installed. The full list of what .NET Portable profiles are installed by each of the installers listed above is available from the .NET Portable Profiles page

Let us take a look in more detail at the option 2 since this has a few manual steps.

Windows – Installing the Portable Library Tools and the Portable Library Reference Assemblies 4.6

Before you start make sure Xamarin Studio is not running.

Download the Portable Library Tools.

To install the Portable Library Tools open a command prompt where PortableLibraryTools.exe was downloaded and run:

PortableLibraryTools /buildmachine

Download the Portable Library Reference Assemblies 4.6 and run the NetFx_PortableLibraryReferenceAssemblies46.msi installer. This will install a PortableReferenceAssemblies.zip file into the directory:

C:\Program Files (x86)\Microsoft .NET Portable Library Reference Assemblies 4.6

This PortableReferenceAssemblies.zip file contains three directories (4.0, 4.5 and 4.6) which need to be extracted and copied into the PCLs directory:

 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable

The PortableReferenceAssemblies.zip file contains files which already exist in the above folder and you should replace the existing files with the new versions from the .zip file.

If you installed Xamarin Studio before you installed the Portable Class Libraries you will now need to reinstall the Xamarin PCL profiles. The Xamarin PCL profiles will only be installed if the Portable Class Libraries were already installed. The simplest way to do this is to find Xamarin in the Control Panel’s Programs and Features, right click it and select Repair.

Repairing Xamarin in Programs and Features

This will add a set of Xamarin .xml files into the profiles that are compatible with the Xamarin frameworks. For example looking at the Profile78 directory we see:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile78\SupportedFrameworks
  • .NET Framework 4.5.xml
  • Windows 8.xml
  • Windows Phone Silverlight 8.xml
  • Xamarin.Android.xml
  • Xamarin.iOS.xml

Now you should have full support for Portable Class Libraries in Xamarin Studio.

November 13, 2014 3:00 GMT

Transitioning to Infinity

I remember clearly when I sat down at I/O this year, watching the introduction of Material design in the keynote unfold and how, at the time, I told myself there was no way we could implement all of this in Android.

One such aspect that I was highly skeptical of until very recently was the concept of animated transition.

We actually talked about this during our Material Design Evolve session with James and at the time of that talk, the only facility we had been given to do it was by keyframe animations which is incredibly clunky to maintain.

Meet our new private implementation friend, PathDataEvaluator.

This evaluator is able to understand the path definition used by vector drawable and create intermediary versions of it.

This means that given two specific path of a vector drawable, we can use an object animator to, not only animate transformation or style like we have seen before, but also the actual pathData of the vector itself.

Now before you get too excited, it’s not a miracle evaluator. There are two very strong requirements for it to work properly:

  • The path command list needs to be of the same size
  • Each command in that list needs to be of the same type

Basically, the evaluator treats the path data as an array of float extracted from each command parameters and use that to interpolate inbetweeners.

This essentially mean that when crafting your paths, you may need to get a bit creative in the amount of nodes you use in order to make those requirements fit.

As an example, this is what we are going to make:

Intuitively, based on our previously mentioned requirements, we can see there is already fundamental problem when we think of alternating between a standard play icon and a standard pause icon: they don’t have the same amounts of subparts (2 rectangles for pause, 1 triangle for play).

In addition, the pause icon rectangles necessitate 4 control points for each subpart whereas the triangle of the play icon only requires 3.

That’s where the tweaking part comes in, following are how I created those shapes in my editor to solve both issues (nodes handles are highlighted):

The work was actually focused on the play icon by first separating the triangle shape in two right sub-triangles and then adding a (normally unnecessary) extra node onto its hypotenuse.

Each node is also numbered as the order in which the path is drawn has an impact on the look and feel of the animation. With those numbers, you can visualize in your head how the nodes are going to move across the canvas to alternate between the two shapes.

Without further ado, here are the vector drawables we are using:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- In your strings.xml file -->
<resources>
	<string name="pause_vector_path">M12,10L20,10L20,38L12,38ZM28,10L36,10L36,38L28,38Z</string>
	<string name="play_vector_path">M16,24L38,24L27.3,30.8L16,38ZM16,10L27.3,17.2L38,24L16,24Z</string>
</resources>

<!-- Resources\drawable\ic_play.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
	android:height="48dp"
	android:width="48dp"
	android:viewportHeight="48"
	android:viewportWidth="48">
	<group>
		<path android:name="d"
			android:fillColor="@color/white_primary"
			android:pathData="@string/play_vector_path" />
	</group>
</vector>

<!-- Resources\drawable\ic_play.xml is identical except
     replace pathData with the second string resource -->

The path data themselves are stored as a string resources. This makes it easier to use them in different places without having to copy and paste the entire thing.

Notice also how my commands are ordered (M stands for moveto and L for lineto) to reflect what the editor diagram showed and also how each command type maps to the same command type between the two definitions.

Since we want to create a transition we need a container for this that handle state using the Android standard state tracking mechanism. This type of container is called a state-list and, as we already covered in the Evolve video above, we now also have an equivalent version that supports animated transition between state: AnimatedStateListDrawable.

Here is my definition for the play/pause button state (based on the state_checked presence):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<animated-selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize="true">
    <item
        android:drawable="@drawable/ic_pause"
        android:state_checked="true"
        android:id="@+id/pause_state" />
    <item
        android:drawable="@drawable/ic_play"
        android:id="@+id/play_state" />
	<transition android:fromId="@id/play_state" android:toId="@id/pause_state" android:reversible="true">
		<animated-vector android:drawable="@drawable/ic_play">
			<target android:name="d" android:animation="@anim/play_pause" />
		</animated-vector>
	</transition>
</animated-selector>

You can watch the Evolve video again for a longer explaination of how this works but essentially we are now naming our various <item /> elements with an id so that we can reference them for animation in <transition /> blocks.

Inside the transition, you’ll find our known companion AnimatedVectorDrawable referencing this object animator definition:

1
2
3
4
5
6
7
<!-- Resource\anim\play_pause.xml -->
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
	android:duration="250"
	android:propertyName="pathData"
	android:valueFrom="@string/play_vector_path"
	android:valueTo="@string/pause_vector_path"
	android:valueType="pathType" />

Key aspect is the valueType attribute that is set to pathType (the only actual way to can reference the non-public PathDataEvaluator class) and the property name set to pathData to change the corresponding member in the vector drawable. For the rest, you can tweak this like any other animator.

Last piece is to show this transition in something. The default Android framework offers a CheckedTextView for those cases but no CheckedImageButton (because using Checkbox can in some occasions result int a bit of pain with positioning). It’s easy to implement though:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class CheckedImageButton : ImageButton, ICheckable
{
	static readonly int[] CheckedStateSet = {
		Android.Resource.Attribute.StateChecked
	};
	bool chked;

	// Add standard constructors

	public override bool PerformClick ()
	{
		Toggle ();
		return base.PerformClick ();
	}

	public void Toggle ()
	{
		Checked = !Checked;
	}

	public bool Checked {
		get {
			return chked;
		}
		set {
			chked = value;
			RefreshDrawableState ();
			Invalidate ();
		}
	}

	public override int[] OnCreateDrawableState (int extraSpace)
	{
		var drawableState = base.OnCreateDrawableState (extraSpace + 1);
		if (Checked)
			MergeDrawableStates (drawableState, CheckedStateSet);
		return drawableState;
	}
}

You can use this class and simply set the android:src attribute to the animated state-list drawable.

Also don’t forget to set the android:background of the button to use the theme value ?android:selectableItemBackgroundBorderless to get the nice ripple effect on touch.

To conclude, you can still use the keyframe approach when doing animated state-list transition if you actually want to invest the time crafting each intermediary state maybe because it does a complex movement that can’t be naively interpolated.

But if you don’t need to, we now have an easy, fast and cumberless way to create beautiful state transitions using vector drawables.

November 12, 2014 2:45 GMT

Microsoft and Xamarin Expand Global Partnership

Xamarin CEO Nat Friedman on stage at Microsoft's Visual Studio Connect();

This morning in New York City, Miguel and I joined Microsoft executives on stage at the Connect(); developer event, which outlined what Microsoft has planned for their developer tools and application platforms.

We launched our partnership with Microsoft one year ago, and in that year a lot has happened. We have reached over 20,000 companies and more than 100 members of the Fortune 500 with Xamarin’s platform, rolled out support for Portable Class Libraries and Shared Projects to make it easier to share code, delivered the Xamarin Designer for iOS making it possible to design iOS UIs from within Visual Studio, and shipped Xamarin.UITest, which makes it easy automate mobile app testing in C# and Visual Studio.

Today we’re excited to take the partnership to the next level, by announcing:

  1. Xamarin Templates in Visual Studio 2015 – Today, we released support for the Visual Studio 2015 Preview release, which includes Xamarin templates that make it easier to discover and download Xamarin from within the IDE. And Microsoft is now including templates for building iOS and Android apps with Xamarin directly in Visual Studio 2015.
  2. Free Xamarin Starter Edition for Visual Studio Users – Today, Microsoft announced a new, free edition to Visual Studio—Visual Studio Community. Visual Studio Community contains support for extensions, which means it will be Xamarin compatible with from day one. We want to help make Visual Studio Community a tool for anyone to create native apps for iOS and Android, so we are announcing our plans to enable our freely available Xamarin Starter Edition to work with Visual Studio Community. We are also doubling the size limit on apps that can be created with Xamarin Starter Edition, so that you can build even more capable apps for free. This will be available in the coming weeks.
  3. Special offers for MSDN Subscribers – We’ve worked with Microsoft to create a  20% discount for Visual Studio Premium and Ultimate MSDN subscribers to purchase Xamarin Business or Enterprise Editions, or world-class mobile development training with Xamarin University, available up to 60 days after the Visual Studio Purchase. Claim your MSDN benefits today.

Xamarin CTO Miguel de Icaza on stage at Microsoft's Visual Studio Connect();

We are happy to work closely with Microsoft to make sure that .NET developers can build native apps for every device on the planet.

If you’d like to check out all of the new things we’ve added to our Visual Studio support, but your Xamarin trial has expired, let us know and we’ll give you another 30 days!

November 12, 2014 12:19 GMT

Adding Shared Projects Support For Xamarin In Visual Studio 2013

While I love portable class libraries for sharing code across multiple projects, and I absolutely love Shared Projects for sharing code within a single library or project. Shared Projects were introduced with Visual Studio 2013 Update 2 and quickly added to Xamarin Studio enabling you share code easier than ever. The two ways of sharing code are vastly different and you can read about them on the amazing Xamarin documentation, but what you really need to know is that a PCL is an assembly with references and a Shared Project is glorified file linking but contains everything under a project node making it easy to navigate and never having to link a file again. This means that these files are just that….files of code that enable you to do conditional compilation and all that jazz :)

The Problem


The real issue is that when VS 2013 Update 2 shipped it only added Shared Projects if you were creating a Universal App and there was no way to create a separate Shared Project or even easily add one to a non-Universal App. There is no reason for this though as you can “easily” modify the .csproj files to get it working.

The Solution


Since manually editing a .csproj is no fun the good people at Microsoft created a Visual Studio extension called the “Shared Project Reference Manager Extension”, which you can find on the Visual Studio Gallery. You can get to this from “Tools -> Extensions & Updates -> Online” and search for Shared Projects:



Once you have this installed you can simply do a File->New Project and under C# you will see a shared project!



With your shared project in place simply right click on your “References” of your Xamarin iOS or Android app and you will see a new “Add Shared Reference…” entry in the context menu. After that you are all set and ready to share code. Of course there is nothing special you need to do in Xamarin Studio as it just works out of the box :)



I even have a full video breakdown that you can watch as well:
November 12, 2014 12:07 GMT

Animating to Infinity

In my previous post, I covered the basics of a new type of Android drawable introduced in Lollipop for scalable graphics.

In and by itself this is already a very powerful new addition. But to see what else we can do with this, let’s reuse the vector drawable example from the previous post:

1
2
3
4
5
6
7
8
9
10
11
<vector xmlns:android="http://schemas.android.com/apk/res/android"
	android:height="96dp"
	android:width="96dp"
	android:viewportHeight="48"
	android:viewportWidth="48" >
	<group>
		<path
			android:fillColor="@color/black_primary"
			android:pathData="M12 36l17-12-17-12v24zm20-24v24h4V12h-4z" />
	</group>
</vector>

I didn’t touch on it at the time but you may have noticed that our path element is actually contained inside another element called a group.

For the sake of displaying vector drawable, this is not a very interesting element. Now if I paste below the list of other attributes you can set on <group/>, you should see something emerging:

Extra group attributes
rotation, scaleX, scaleY, translateX, translateY.

You will have surely recognized those are the same attributes we use to manipulate our View instances when animating them.

Enter, Animated Vector Drawable.

Animated Vector Drawables are actually more of a meta-type bridging several other pieces together much like a State List Drawable (and like the later, they also are drawables themselves).

Here is an example of an animated vector drawable that we will use later on (also stored in your drawable resource folder):

1
2
3
4
5
6
7
8
9
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
	android:drawable="@drawable/bluetooth_loading_vector" >
	<target
		android:name="circleGroup"
		android:animation="@anim/circle_expand" />
	<target
		android:name="circlePath"
		android:animation="@anim/circle_path" />
</animated-vector>

Animated Vector Drawables are declared using the <animated-vector/> element. The first thing you need to tie in is which vector drawable the animated version is going to use as a base, this is set in the android:drawable attribute at the top level.

The rest of the file contains a bunch of different <target/> elements, those are where we are going to set up which animations are ran and on what part of the vector drawable they will be ran.

But first, here is the definition of the bluetooth_loading_vector referenced in the animated vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="utf-8" ?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
	android:height="64dp"
	android:width="64dp"
	android:viewportHeight="192"
	android:viewportWidth="192" >
	<group>
		<path
			android:fillColor="@color/vector_foreground_color"
			android:pathData="M87.3996,113.161L85.3665,112.191L85.3665,23.517L87.3996,22.5479L143.293,67.8542L87.3996,113.161ZM99.9498,84.2151L120.134,67.8542L99.9498,51.4934L99.9498,84.2151Z" />
		<path
			android:fillColor="@color/vector_foreground_color"
			android:pathData="M87.4147,169.459L85.3665,168.484L85.3665,79.6589L87.4147,78.684L143.277,124.071L87.4147,169.459ZM99.9498,140.484L120.15,124.071L99.9498,107.659L99.9498,140.484Z" />
		<path
			android:fillColor="@color/vector_foreground_color"
			android:pathData="M43.8495,129.345L103.262,81.2217L112.186,92.2392L52.7734,140.362L43.8495,129.345Z" />
		<path
			android:fillColor="@color/vector_foreground_color"
			android:pathData="M43.8495,62.2562L103.262,110.379L112.186,99.3616L52.7734,51.2387L43.8495,62.2562Z" />
	</group>
	<group
		android:name="circleGroup"
		android:pivotX="96.0"
		android:pivotY="96.0"
		android:rotation="0">
		<path
			android:name="circlePath"
			android:strokeColor="@color/vector_foreground_color"
			android:strokeWidth="16"
			android:strokeAlpha="1"
			android:trimPathEnd="0.7"
			android:pathData="M96,5.56405C145.946,5.56405 186.436,46.0536 186.436,96C186.436,145.946 145.946,186.436 96,186.436C46.0536,186.436 5.56405,145.946 5.56405,96C5.56405,46.0536 46.0536,5.56405 96,5.56405Z" />
	</group>
</vector>

And what it looks like when rasterized:

This vector drawble is a bit longer than the previous one, but there are two main things to notice:

  • The drawable is arranged in two distinct groups
  • One group and one path have a name attached, mapping back to the animated vector’s target elements

The way we have layed-out and named our vector drawable means we can now directly reference the relevant parts we want to manipulate.

For instance in our case, we are only interested in the ring around the Bluetooth logo which is why only this piece is actually named in our vector drawable.

To close the loop (so to speak), here are the two animation definition files referenced by the animated vector drawable (placed each in your anim resource folder):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!-- Resources\anim\circle_expand.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
	<objectAnimator
		android:duration="@integer/loading_anim_time"
		android:propertyName="scaleX"
		android:valueFrom="1.0"
		android:valueTo="2.5"
		android:valueType="floatType"
		android:repeatCount="-1" />
	<objectAnimator
		android:duration="@integer/loading_anim_time"
		android:propertyName="scaleY"
		android:valueFrom="1.0"
		android:valueTo="2.5"
		android:valueType="floatType"
		android:repeatCount="-1" />
	<objectAnimator
		android:duration="@integer/loading_anim_time"
		android:propertyName="rotation"
		android:valueFrom="0"
		android:valueTo="360"
		android:valueType="floatType"
		android:repeatCount="-1" />
</set>

<!-- Resources\anim\circle_path.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
	<objectAnimator
		android:duration="@integer/loading_anim_time"
		android:propertyName="trimPathEnd"
		android:valueFrom="0"
		android:valueTo="1"
		android:valueType="floatType"
		android:repeatCount="-1" />
	<objectAnimator
		android:duration="@integer/loading_anim_time"
		android:propertyName="strokeAlpha"
		android:valueFrom="1"
		android:valueTo="0"
		android:valueType="floatType"
		android:repeatCount="-1" />
</set>

Since this is meant as a continous animation, we must ensure that the repeat count of each animator is -1 (a synonym for ‘infinite’) so that the process runs forever.

In the remaning bits, we are simply animating a bunch of property on both the group (for transformations) and on the path (for the stroke style) like we would on a normal view.

The last thing to do is load the animated vector drawable into a continuously animating View, typically a ProgressBar:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/colorPrimary"
    android:padding="48dp"
    android:clipChildren="false"
    android:clipToPadding="false">
    <ProgressBar
        android:indeterminate="true"
        android:indeterminateDrawable="@drawable/animated_bluetooth_loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
</FrameLayout>

And we arrive at this result:

Next up, we will see how we can apply some of this to make terrific transitions.

November 11, 2014 12:03 GMT

A week in AZ: Speaking, Career Fairing, Workshopping, and Game Jamming!

What an exciting and outstanding week in Arizona. Last week I was invited back to my alma mater, the University of Advancing Technology, to participate in several events including their Tech Forum where I gave a talk, an Alumni Panel, a CocosSharp workshop, and I got to help with a 48 hour Game Jam!



I was part of the 2008 graduating class at UAT and boy has our industry changed since then. I never would have imagined my journey from making console games, then printer software, then mobile apps, and now working as a developer evangelist as Xamarin. I don’t even think that smart phones even existed when I started college in 2005 and now they are the pinnacle of the software industry and transforming our society. This was my main topic that I got to deliver to students at the Tech Forum, which was live streamed to the world. Mobile devices and apps have changed our lives and have had the huge impact to software development as we know it. You no longer need hundreds of developers and multiple years to publish a 50 Million selling piece of software. Just look at Angry Birds that was built by a team of less than 10 people in 8 months and only took 35 days to reach 50 million users. It is crazy how fast our industry is moving.



Later in the week I was joined by my good friend and co-worker Mike Bluestein where we got to greet current students at UAT at the Career Fair. It was great to see the professionalism from so many students ready to dive into development and graphic design. Later that night Mike and I gave a full workshop on Xamarin and our brand new 2D gaming engine CocosSharp to several students and instructors. I was excited for the potential of getting back into game development with CocosSharp as it has a beautiful API that anyone can tackle.



Everything came together for the grand finale of the week of a Xamarin and UAT sponsored 48 Hour Game Jam! 30+ developers, artists, and game designers came together for the weekend to jam on games with the chance to win over $500 in prizes. It was an amazing weekend and there were games built with all different programs, languages, and genres. I took to mobile creating my first game in CocosSharp called Nibbles (now open sourced), a puzzle game to connect ever growing bubbles before they burst. It played nice with the Game Jam’s theme of “Connections”.



After 48 Hours the games were judged and everyone got to present their games. Here are some of the highlights in photos from the Jam.



I can’t wait to participate in more events such as this all and I must thank everyone that helped pull together such an amazing week. We recently announced that Xamarin is completely free for Students to build iOS and Android apps in C# and we even have a brand new student ambassador program as well. I am excited to hear from students all over the worlds as they start to build and ship their apps built with Xamarin.

November 10, 2014 4:10 GMT

App Spotlight: VentusAR’s Augmented Reality Wind Turbines with MonoGame Video

George Banfill from Linknode gave us an overview of VentusAR.  Utilizing the Xamarin platform and MonoGame, they have created a unique augmented reality (AR) experience to visualize what wind farms would look from a location.  VentusAR heavily utilizes native features in iPads and Android tablets to access the GPS, accelerometer, compass, and live camera feed to superimpose virtual turbines on the landscape in real-time.

The app provides immediate visualizations of wind-farms to businesses and the public before they’re built, something that would normally take weeks or months.  VentusAR radically reduces that time by loading geographic data models and GPS coordinates of the proposed locations, then going out in the field with the tablet to render 3D turbines aligned on top of a live camera feed.

To really appreciate how innovative this experience is we took this video where George takes us through the problems VentusAR solves and shows us how it works.  Watch it in full-screen to see it in action.

VentusAR opened my eyes about the possibility of using game technology to solve real-world business problems, creating one of the most unique app experiences I’ve ever seen.

Thank you to Linknode for sharing your app with us!

Learn More

Visit VentusAR’s website to learn more.

To get started developing with the Xamarin platform, check out our developer documentation, learn more about MonoGame, and get live online training with Xamarin University.

November 09, 2014 10:54 GMT

Scaling to Infinity

When I make an app, I spend my time between two worlds.

In the first, I produce sequences of meaningul characters for a virtual machine in your favorite IDE, Xamarin Studio. In the second, I use my best friend Inkscape (and lately also Affinity) to help me think, iterate and produce the front face of my app.

The main challenge of this form of development is to find the best way to ease the content transition between both worlds.

In Android, what’s essentially the apocalypse of screen form-factor makes it particularily painful to work with that visual assets part of your app.

Where the world was happily spread between ldpi, mdpi and hdpi a few years back, today we just don’t know how many ‘x’ we are going to be able to fit in front of ‘hdpi’ (at the time of this writing we reached xxxhdpi).

I have actually already talked about this subject and, at the time, released my own library to try to tackle this issue.

But today we can finally rejoice as Google gave developers a blessed way to create unlimited scalable graphics with the recent release of Lollipop (or Android 5.0).

This new types of drawable is unoriginaly called Vector Drawables and, as with any other drawable, they are natively understood by the Android toolchain which make their use as seamless as feasible (i.e. you can reference them in layouts, styles, acquire them through Resources.GetDrawable, …).

This is an example of a vector drawable (store them in your Resources/drawable folder):

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8" ?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
	android:height="96dp"
	android:width="96dp"
	android:viewportHeight="48"
	android:viewportWidth="48" >
	<group>
		<path
			android:fillColor="@color/black_primary"
			android:pathData="M12 36l17-12-17-12v24zm20-24v24h4V12h-4z" />
	</group>
</vector>

Which draws this well known media player action icon:

The beef of a vector drawable is in its various <path/> elements and more precisely its pathData attribute. As arcane as it may look, it actually defines the full blown shape of the icon in the very concise SVG Path data format.

Don’t worry too much though, you won’t have to write that down by yourself (you may need to tweak it though for more funky things but more on that in a later post).

Since it’s based on the same specification than used in SVG itself, as long as you can grab a SVG version of your graphic you will directly be able to copy and paste it into a vector drawable XML.

As a matter of fact, the icon example that I pasted above came from Google’s official material design icon pack which also contains SVG for every icon:

1
2
3
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48">
    <path d="M12 36l17-12-17-12v24zm20-24v24h4V12h-4z"/>
</svg>

Notice also how the viewportHeight and viewportWidth values in the vector drawable reflect what’s in the width/height/viewBox parameter of the SVG. As long as those values are correctly defined, you can play with the android:width and android:height part of your drawable the way you want.

Together with the new general tinting facility in Lollipop, you can now iterate over your assets even faster without leaving your IDE and without having to re-generate 6 variants of your graphics.

November 07, 2014 5:27 GMT

Programming for Google Cardboard on iOS using F#

One of the highlights of Xamarin Evolve is the Darwin Lounge, a hall filled with programmable devices ranging from robots to iBeacons and quadcopters to wearables. One thing that was particularly intriguing this year was a stack of kits from DodoCase, “inspired by Google Cardboard.” Google Cardboard is an inexpensive stereoscope that exploits the ridiculously small pixels of modern phones. Instead of synchronizing two displays, it directs your eyes separately to the two halves of a phone screen in portrait mode.

cardboard

Unfortunately, all of the resources for programming Google Cardboard have been Android only. This is not the Xamarin way and could not stand! Luckily, Joel Martinez had written a 3D demo for our talk, Make Your Apps Awesome With F#, and it was just a matter of a quick hacking session to see our Xamarin.iOS code in glorious stereoscopic 3D.

before_and_after

Functional Refactoring

As Mike Bluestein has written previously, the easiest way to program 3D on iOS is to use Scene Kit, which is what Joel and I had done for our demo. Stereoscopic programming in Scene Kit, as it turns out, is easy!

One great aspect of F# and the functional programming style is that refactoring is often easier than object-oriented refactoring. Instead of creating new objects and data structures, you’re generally focusing on “minimizing the moving parts” and extracting common functionality into reliable functions.

For instance, the first thing we needed to do was switch from a single UIView to two side-by-side views. We refactored this code:

//Configure view
let r = new RectangleF(new PointF(0.0f, 0.0f), new SizeF(UIScreen.MainScreen.Bounds.Size))
let s = new SCNView(r)
configView s scene |> ignore
this.View <- s

into this code:

//Configure views
let outer = new UIView(UIScreen.MainScreen.Bounds)
let ss =
    [
        new RectangleF(new PointF(0.0f, 0.0f), new SizeF(float32 UIScreen.MainScreen.Bounds.Width / 2.0f - 1.0f, UIScreen.MainScreen.Bounds.Height));
        new RectangleF(new PointF(float32 UIScreen.MainScreen.Bounds.Width / 2.0f + 1.0f, 0.0f), new SizeF(UIScreen.MainScreen.Bounds.Width / 2.0f -1.0f, UIScreen.MainScreen.Bounds.Height));
    ]
    |> List.map (fun r -> new SCNView(r))
    |> List.map (fun s -> outer.AddSubview(configView s scene); s)
this.View <- outer

Although you may be more familiar with C# than F#, you should be able to follow what’s going on in the original snippet. We had a RectangleF as big as the entire screen’s Bounds. We created a single SCNView called s. We configured s to show our scene and then, because we don’t need to do any more manipulation on the result of that calculation, we called the ignore function with the result (the |> is F#’s pipe operator, which works just like the familiar pipe operator on the UNIX command-line or PowerShell). Finally, we assigned this single SCNView to be the main View of our controller object.

To refactor, we introduce an outer view that will contain our two eye-specific views. We then use the |> operator again to:

  • Create a 2-element list of RectangleFs, each a half-screen wide
  • Create an SCNView for each one of those
  • Configure each SCNView with the scene
  • Add them to the outer container UIView

Now we have two side-by-side SCNViews, but each is rendering the exact same scene, so there is no 3D effect. Scene Kit is a scene-graph toolkit, and to get a stereoscopic 3D effect, we’re going to need two camera nodes slightly separated in space. That’s easy. We replace:

//Camera!
let camNode = new SCNNode()
camNode.Position <- new SCNVector3(0.0F, 0.0F, 9.0F)
scene.RootNode.AddChildNode camNode

With:

//Cameras!
let camNode = new SCNNode()
let leftCamera = buildCamera camNode (new SCNVector3 (0.0F, 0.0F, 9.0F))
let rightCamera = buildCamera camNode (new SCNVector3 (0.2F, 0.0F, 9.0F))

Note the slight difference in the first argument to the SCNVector3 constructor – this eye-position vector is the “moving part” that we want to isolate. So now our camNode has two subnodes, each containing a node that defines one of our eye positions.

The buildCamera function is:

let buildCamera (parent : SCNNode) loc =
    let c = new SCNNode()
    c.Camera <- new SCNCamera()
    parent.AddChildNode (c)
    c.Position <- loc
    c

It’s worth emphasizing that this function is strongly-typed. Even though it doesn’t explicitly state that loc is an SCNVector or that it returns an SCNNode, F#’s type inference is powerful enough to figure that out and enforce the types at compile-time. (As for programming style: “Is it better to explicitly declare types in the function signature or let them be implicit?” is the type of discussion that happens both in the Darwin Lounge and at Xamarin Evolve parties…)

Now we have two scenes and two camera nodes. To join them together, we use:

//Set PoVs to shifted cameras
ss.Head.PointOfView <- leftCameraNode
ss.Tail.Head.PointOfView <- rightCameraNode

And there you have it! In the following image, you can see the converging perspective of the building climbing into the sky.

living_in_stereo

This might not be ready for the Avatar sequel, but it’s really cool when viewed through Cardboard!

Here’s something James Cameron can’t do, though: exploit the gyroscope and accelerometer on iOS devices. This block of code shifts the orientation of the camNode camera node so that it tracks the direction in which the user is looking:

    let rr = CMAttitudeReferenceFrame.XArbitraryCorrectedZVertical
    this.motion.DeviceMotionUpdateInterval <- float (1.0f / 30.0f)
    this.motion.StartDeviceMotionUpdates (rr,NSOperationQueue.CurrentQueue, (fun d e ->
        let a = this.motion.DeviceMotion.Attitude
        let q = a.Quaternion
        let dq = new SCNQuaternion(float32 q.x, float32 q.y, float32 q.z, float32 q.w)
        let dqm = SCNQuaternion.Multiply (dq, SCNQuaternion.FromAxisAngle(SCNVector3.UnitZ, piover2))
        camNode.Orientation <- dqm
       ()
    ))

Which looks like this in action:

To experiment with stereoscopic 3D in Xamarin and F#, download this Starter-compatible project in Xamarin Studio on Mac or Windows.

November 07, 2014 4:28 GMT

Stop Crashing!

TL;DR I wrote a script that lists functions in your Xamarin app that could cause it to crash. StopCrashing.fsx on github.

We’ve all had apps crash. It’s annoying, it’s stressful, and you feel cheated. Most people give up on apps that crash more than a couple times, or they leave 1 star reviews. Crashing is bad.

One of the benefits of using a managed runtime like .NET and Xamarin is that one of the most common causes of a crash - pointer corruption - is just not possible. Great! My apps should crash a lot less you think.

This is indeed true, but there is a catch: .NET uses exceptions as its error communication mechanism - just like every other modern runtime. That is fine, we all love exceptions.

Well, everyone loves them except old fuddy duddy operating systems from 1970 (i.e. every OS). They only know how to deal with unhandled exceptions by crashing. (Queue Hitchcock’s theme.)

What a world we live in! Our error communication mechanism actually causes our apps to shut down? Madness!

But that is indeed the world we live in. Hi, my name is Frank, and my apps crash. I hate it, I test and test but still manage to miss some exception handling in my code.

I’m tired of it. While crash reporting solutions exist, I would prefer to just not crash at all.

So I wrote a script.

StopCrashing.fsx

I wrote a script that looks for possible ways the OS can call into my code. These entrypoints are the potential origins for crashes because there is no useful exception handler on the stack at that time.

What are these calls? Well, there are a lot of them:

  1. Any time you override members of UI objects
  2. Any time you export functions to the OS (as in, the responder chain)
  3. Any callbacks you register with the OS
  4. I’m sure there are more…

My script uses Mono.Cecil to scan all the byte code of your application to find these entrypoints. (Well, I’ve only implemented #1 and #2. #3 is a harder problem to detect.)

It then detects whether you have any exception handling in that code. If you do not, it yells at you.

The idea is that we don’t want to bloat our software with exception handlers everywhere. This certainly makes coding more tedious but also introduces a lot of ambiguity. Instead, we still want to fail fast by leaving the majority of our code free of handlers. We will only catch exceptions where we must do so to prevent crashes.

The script is available on github. I put a little effort into making it easy to run: just pass it the path of your solution and it will go find the latest binaries automatically. It also returns an exit code so that it can be easily integrated into your CI server. (It is currently configured only to detect iOS and OS X calls. Android and Win RT support can be added if anyone is interested.)

Let’s run it on Calca and see what it has to say:

fsharpi --exec StopCrashing.fsx Calca.Mac.sln

30 UI METHODS IN Calca.Mac.sln NEED EXCEPTION HANDLERS
    Calca.Mac.Editor.InsertText
    Calca.Mac.Preferences.MakeKeyAndOrderFront
    Calca.Mac.TextEditorDelegate.DidChangeSelection
    Calca.Mac.TextEditorDelegate.GetCompletions
    Calca.Mac.TextEditorDelegate.LinkClicked
    Calca.Mac.TextEditorDelegate.ShouldSetSpellingState
    Calca.Mac.TextEditorDelegate.WillChangeSelection
    ...

Wow, it looks like there are 30 methods where an errant exception could crash my app! While I’ve done my best to make sure Calca doesn’t error, it’s just impossible to cover every possible situation. These 30 methods need to handle exceptions.

I have always tried to put good error handling in my code, but did a hap-hazard job of it. If the app doesn’t crash for my beta testers then it probably won’t crash for everyone else. Right? Well, no. I have come to the conclusion that you have to be more proactive. You have to defend against the unknown and this script ups my defenses significantly.

Handling Exceptions

Well, if you’re going to handle errors, then you better do it responsibly. I find that a few types of functions repeatedly show up.

  1. Simple UI actions like clicking a button or entering text These can be handled simply by catching all exceptions and popping up an alert to the user.

  2. System events Since these can occur at random times, you may not want to alert the user (or at least not interrupt them with an alert). Random alerts popping up out of the blue will only confuse your users.

  3. Methods that return values These are often feeding data into other APIs and need to be treated delicately. I try to allocate some safe defaults when the object is first constructed and then return those in error conditions.

Test your error handling! When I’m bored (that is, when I’m procrastinating over a difficult feature or bug) I often put random exceptions into my code just to test the error handling. What if this critical function fails, what will my app do? What if this seemingly innocent function fails, what will my app do? These little experiments can convince you that those 1 star reviews will at least be earned.

Of course, you can still benefit from crash loggers if your users don’t mind submitting error reports. The nice thing is, instead of crash reports, you’ll be delivering error reports.

As a last tip, may I remind you to be careful of loops. Displaying an error is bad and can annoy the user. Displaying the same error 100 times while your loop continually executes is catastrophically bad and you’ll be lucky if that user ever uses your app again.

November 07, 2014 4:55 GMT

Microsoft Band (day 7: heart rate)

So far I've had the Band a week, and it's been on my wrist almost every second of that time (except charging). I'm surprised by how easily I got used to wearing it - it is still chunky, but light enough that I can cope :-)

The one remaining question people have asked is how good the heart-rate sensor is, so I did a couple of tests today both running and walking/sitting. I used the Band in conjunction with a Polar H7 chest-band paired with both the Polar and Strava apps. 


I expected the results to be pretty close (given how good the GPS performance is on the Band)... but turns out, not so much. Here's the heart-rate data from the Band - seems consistent with an average of 165 bpm (high of 177).


The Polar H7 chest strap data was slightly different though. Here is the graph from the Strava app; it recorded an average of 149 bpm (high 159).


And of course you can view the data from the Polar chest-strap in more detail on the Strava website:


So there's a bit of variation between what the Band reports and what was recorded on the chest-strap. I did another test just walking for 20 minutes; with the following result:

  • Microsoft Band reported average 107 bpm (high 147)
  • Polar H7 chest-strap reported average 81 bpm (high 93)

Only on the internet could two tests be considered a statistically valid sample, but there you go - looks like the Band's heart-rate sensor is not as accurate as a chest-strap ;-) In reality, any number of factors could contribute to the difference: maybe I didn't have the Band on tight enough, maybe face-up versus face-down on my wrist makes a difference, maybe the strap is the bad data, who knows?!


The Bottom Line

That's all the blog posts for now - my first week with the Microsoft Band is done.

Overall I still like it - I've gotten used to having it on, the sleep data is new and interesting, and it's a good run tracker (the GPS is as good if not better than my Garmin - and it definitely finds the satellites quicker). I love the notifications on the Band: text messages, email, Facebook, etc... these could be the things that keep me using it after I get bored of the other stuff :)

The negatives are minor, but important for some. The battery realistically only lasts a full day - the minute you use the GPS functionality you're going to have to charge again within 24 hours. People report longer times but I doubt you are really getting the full use of the watch if you're stretching the battery so long. The other hardware issue is the question-mark over the heart-rate sensor ~ I'll leave it for people with more patience than me to do an exhaustive test, but as the disclaimer says "this is not a medical device" and it's probably as good as you can expect for a device of this size.

Finally, though, even assuming the battery lasted a week and the HR was spot-on, I would still not be able to use the Band as my only fitness-tracking device, purely because the data is locked into the Microsoft Health ecosystem. While there is no way to export ALL the data (into Strava or similar systems) I'm just not willing to give up my current devices.
November 06, 2014 5:44 GMT

Xamarin Test Cloud Video Series: Using C# and UITest to Create Your First Mobile Test

Xamarin.UITest is a C#-based testing framework enabling automated UI acceptance tests for iOS and Android applications that can be uploaded to Xamarin Test Cloud to test on over 1,000 real devices. Xamarin.UITest is available as a NuGet package and relies on the popular NUnit testing framework that most C# developers are familiar with.

In this video, Dan Waters shows us the steps to utilize UITest, and also how to use the interactive shell (REPL) included with Xamarin.UITest to explore the views on a screen and to automate interactions with the application. The best thing about Xamarin.UITest is that it tests any mobile app regardless of the platform it’s written in – Objective-C, Java, Xamarin, or 3rd party frameworks.

Each test is a method inside an NUnit Test Fixture class and follows the Arrange-Act-Assert pattern:

  1. Arrange – The test sets up conditions and initializes so that the test can be actioned.
  2. Act – The test interacts with the application, entering text, pushing buttons, tapping, etc.
  3. Assert – The test examines the results of the actions performed in the Act step to determine correctness. For example, the application may verify that a particular error message is displayed.

Watch it in full-screen to see the code and Xamarin.UITest in action.

Learn More & Get Started

To learn more about Xamarin Test Cloud, visit the product page, or check out our developer documentation.

November 06, 2014 1:00 GMT

Xamarin Forms MasterDetail Page Navigation Recipe

MasterDetailPage

In this recipe I will show you how to add a hamburger menu to your Xamarin Forms application using the MasterDetailPage class. MasterDetailPage consists of one page for the master and one or more pages for the detail.

When used for the main navigation, as in this recipe, we will have a single master page and 4 detail pages. The code for this recipe comes from the Xamarin Forms CRM sample. I have simplified and streamlined the code, and a full Xamarin Studio solution is included at the bottom of this post.

Master Detail Page

Think of the MasterDetailPage as the traffic cop of your application navigation. When a user clicks on the hamburger menu, MasterDetail pushes the menu onto the screen. Then when the user taps on a menu item, MasterDetail creates the target page and pushes it onto the stack. Besides those two things, and some styling, MasterDetail doesn’t do much. Have a look at the code.

public class RootPage : MasterDetailPage
{
	public RootPage ()
	{
		var menuPage = new MenuPage ();

		menuPage.Menu.ItemSelected += (sender, e) => NavigateTo (e.SelectedItem as MenuItem);

		Master = menuPage;
		Detail = new NavigationPage (new ContractsPage ());
	}

	void NavigateTo (MenuItem menu)
	{
		Page displayPage = (Page)Activator.CreateInstance (menu.TargetType);

		Detail = new NavigationPage (displayPage);

		IsPresented = false;
	}
}

Pretty simple right? The only complicated bit is with the (Page)Activator.CreateInstance (menu.TargetType) part, but if you have been doing C# on .Net for a while, you probably have seen it before. All it is, is another way of creating objects.

The Menu Page

The menu page is just what the name implies, it’s the Xamarin Forms page that will be shown when the user clicks the menu button. This is our master. Our MenuPage is a simple content page with a StackLayout containing a label and a ListView of our menu items.

Please note the public property Menu. This property allows our MasterDetail page access to the ItemSelected event. When the event is fired, the item selected will be sent to the NavigateTo method on the master detail object.

public class MenuPage : ContentPage
{
	public ListView Menu { get; set; }

	public MenuPage ()
	{
		Icon = "settings.png";
		Title = "menu"; // The Title property must be set.
		BackgroundColor = Color.FromHex ("333333");

		Menu = new MenuListView ();

		var menuLabel = new ContentView {
			Padding = new Thickness (10, 36, 0, 5),
			Content = new Label {
				TextColor = Color.FromHex ("AAAAAA"),
				Text = "MENU", 
			}
		};

		var layout = new StackLayout { 
			Spacing = 0, 
			VerticalOptions = LayoutOptions.FillAndExpand
		};
		layout.Children.Add (menuLabel);
		layout.Children.Add (Menu);

		Content = layout;
	}
}

Please note: you must set the title property of the ContentPage used for the Master part of our MasterDetail. If you don’t, the application will throw an error.

 Menu Item

Menu Item is a simple type that holds our menu data and the most important data is the Target type. When a user clicks on a menu item, the NavigateTo method will create a new page from the TargetType, and push that page onto the stack.

public class MenuItem
{
	public string Title { get; set; }

	public string IconSource { get; set; }

	public Type TargetType { get; set; }
}

 Menu List View

The menu list view couldn’t be simpler; we use the built in ImageCell for the rows and set the bindings to the properties on the MenuItem type. We set the first item as the selected item and also used it when constructing the MasterDetail Page initial detail class.

public class MenuListView : ListView
{
	public MenuListView ()
	{
		List<MenuItem> data = new MenuListData ();

		ItemsSource = data;
		VerticalOptions = LayoutOptions.FillAndExpand;
		BackgroundColor = Color.Transparent;

		var cell = new DataTemplate (typeof(ImageCell));
		cell.SetBinding (TextCell.TextProperty, "Title");
		cell.SetBinding (ImageCell.ImageSourceProperty, "IconSource");

		ItemTemplate = cell;
		SelectedItem = data [0];
	}
}

 Menu List Data

The MenuListData class is a data structure holding our applications navigation. In your app you could get this data from the database or configuration file. The menu structure of my application doesn’t change much, so I just use code.

public class MenuListData : List<MenuItem>
{
	public MenuListData ()
	{
		this.Add (new MenuItem () { 
			Title = "Contracts", 
			IconSource = "contracts.png", 
			TargetType = typeof(ContractsPage)
		});

		this.Add (new MenuItem () { 
			Title = "Leads", 
			IconSource = "Lead.png", 
			TargetType = typeof(LeadsPage)
		});

		this.Add (new MenuItem () { 
			Title = "Accounts", 
			IconSource = "Accounts.png", 
			TargetType = typeof(AccountsPage)
		});

		this.Add (new MenuItem () {
			Title = "Opportunities",
			IconSource = "Opportunity.png",
			TargetType = typeof(OpportunitiesPage)
		});
	}
}

The Content Pages

These pages are what is created when a user clicks on our menu items.

public class ContractsPage : ContentPage
{
	public ContractsPage (){}
}

public class LeadsPage : ContentPage
{
	public LeadsPage (){}
}

public class AccountsPage : ContentPage
{
	public AccountsPage (){}
}

public class OpportunitiesPage : ContentPage
{
	public OpportunitiesPage (){}
}

Junk Burgers

Hamburger menus have been getting a lot of bad press these days and rightly so. During the Apple WWDC event some Apple engineers expressed opinions that hamburger menus are breeding ground for junk. My advise to you is use them sparingly and don’t make them a catchall for your app navigation. They should be used like tabs, where more than 5 things start to get a little crowded.

I hope you learned something from this post. If you have any questions, please leave them in the comments. Thanks, Adam.

Download Xamarin Forms MasterDetail Recipe Code

The post Xamarin Forms MasterDetail Page Navigation Recipe appeared first on Syntax is my UI.

November 06, 2014 11:10 GMT

Using MapFragment inside ScrollView

I have an app where I need to put a Map inside a ScrollView, doing so will make the ScrollView intercept all the touch events. So the solution is to call RequestDisallowInterceptTouchEvent(true) whenever you need the Map to scroll around, pinching it etc. The problem is that MapFragment or its properties do not expose any touch events, so it makes it a bit harder to find out when it is touched.

I found a nice little code snippet, Lorensius Londa posted on his blog, for Java Android, which overlays the MapFragment with a FrameLayout and using the FrameLayout touch event. Using this exact technique help me achieve my goal as well. Here is the code I used.

So as you see in the code there is a TouchableWrapper which simply fires some Actions whenever it was touched or the touch was released. This is grabbed by the TouchableMapFragment which subsequently fires the equivalent events.
The Fragment is used as follows in a AXML layout.
Then you can use the events in your Activity like so.
Now you should be able to navigate your Map when it is nested in a ScrollView.
November 06, 2014 4:20 GMT

Microsoft Band (day 6: data)

Short update today, answering two questions I've heard a lot about the Band:

  • Can the data be exported?
  • Does it work for cycling?

Can data be exported?

The short answer here is "no"; at least I have not found a way to get any of the raw data out of the Band or the Microsoft Health app. There are Connected Apps partners with Microsoft, including RunKeeper, so I signed up for their service to see how much data is shared.

The first problem with Connected Apps is that (apparently) your past data is not shared. This meant that after I joined there was no way for me to upload the half-marathon data from last weekend. New activities, however, seem to appear on RunKeeper as soon as they're sync'd to Health.

The second 'problem' is that only a summary of each activity is available... here is the information available on RunKeeper after a 5 km run this evening:


No details are available in the Connected App - no kilometer splits, elevation chart, map track or heart rate data :-( I would really like to get the running data (heart rate, GPS track as GPX) from my Band activites, and/or sync them automatically with Strava... however if the only integration possible with Strava is a 'summary' such as that shown above - I wouldn't bother!

Interesting statistic shown on the RunKeeper website...
1139 RunKeeper users also use this app
I wonder just how many Bands have been sold so far...


Does it work for cycling?

There's no particular reason why the Band won't collect data (GPS track, heart rate, etc) from a cycling effort as well as a run... I tried it out and it works fine. The problem with this is categorizing that workout in your training records. The speed/average pace recorded for a bike ride will far exceed your running capacity ;) and the heart-rate will be a lot less; making the calorie calculations also useless. 

If metrics are important to you (and they probably are, if you're reading this), then "no" the Band isn't much use for cyclists compared to the myriad of other options available.
November 05, 2014 1:33 GMT

Using Apples new TestFlight Beta Testing

... which is not to be confused with the old TestFlight (which Apple bought and called TestFlight).

At work, we do a pilot release of our app before we go live. This is usually part way thru regression testing, and obviously before we release to the general public. Up to now, we have used TestFlight (the old one) to manage the iOS side of this.

It's worked fine - well, it's worked fairly well, it's never been an overly reliable service - but we are constantly running into the 100 device limit, after we load up all of our test devices, a few developer devices, the business users devices for the pilot, and of course, a lot of people have got new devices since the last roll over....

Enter stage right the new, improved TestFlight Beta Testing.

So whats different?

  • It's integrated into iTunes Connect now.
  • It's supported by Apple, for better or worse.
  • It has a proper client, and proper integration into iOS8 (only).
  • In some cases, it requires approval / review before release. (not as bad as it sounds)

The steps to use it are pretty simple, and some of them can be automated, at least for internal testing.

They do introduce some new terms tho.

  • Internal testers are people who are on your Developer Account who need to test the app. Think people on your direct team, your developers, testers, and maybe product managers. You have have 25 of these and each person can have 10 devices.
  • External testers are normal people who have an Apple ID (the one they use for the AppStore, not iCloud, tho they are often the same). Up to 1000 of these, and no limit on devices, but a single person can't beta more than 10 apps at a time. They do not have to be part of your organisation.

So, how do you do it? Fairly easily.

First, make an AppStore build and upload it as normal. I suggest you set the Build Number to something which you can change each time (I used 3.4 for the version number, and 3.4.1, 3.4.2 etc for the build numbers). It will appear in iTunes Connect in the Prerelease > Builds section. You can then turn on TestFlight Beta Testing and submit it for review.

For me, review took about 12 hours. If you are just releasing it to Internal Testers, you do not require review, and there is a command line tool to update (and I'd assume, release) it for internal use. I suspect we'll be using this as soon as we move to Xcode 6.

Once it's approved, you can then go into external testers (or internal) and add some people1. You need their name and email address for this. Once you have them in there, they get an email which tells them to go get the TestFlight app from the appstore, and after they install it, the same link will take them to the app in TestFlight and let them install or update it. It mostly works like the Appstore from there.

NOTE: If they use the Gmail app and have Google Chrome installed, it will take them to the AppStore every time. Solution is to take the URL it has in Chrome, and paste it into Safari - then it works right.

After they have downloaded your app and installed it, you can see who's installed what in the External Testers list. I've found this to be somewhat inaccurate (eg, in this case, AJ had also installed it), but a good indication.

The user, however, can stop being part of the beta from within the TestFlight app, and get to a few bits of your website (urls provided), but it would be nice if there was away to jump directly to an email to the developer. Tap, get a new message with a predefined subject and some beta metadata in the body. Maybe in version 2.

If you have a new build to push up after that, you can just upload it as normal (with a new build number!), look for it in Builds, and submit it for review again. It asks you if you have made major changes, and if you say no, then it's ready to go and be tested.

It's absolutely an improvement over the old system, but it's still got some kinks to work out - mostly timing issues, and things not updating. Still better than the old system, except for one thing: It's iOS8 only for the testers. I think they could have made the effort to have it on iOS7, which would cover 99% of devices out there, and made the break for broken UDID-based testing once and for all.

So far, we've run into a few problems notifying people - eg, I have 5 testers, I add a new build, tell it to give it to everyone - and only 3 of the 5 get it. No way to "reenable" the other ones, I have to remove and re-add them (which spits out 2 emails). They can't even go into the app and manually refresh - it just shows the old version. Frustrating at best. Consider it a nice Alpha.

1: Chances are you can do this BEFORE your app is approved, but we had one user who got about 20 invites, so maybe wait (you can upload a CSV anyway).

November 04, 2014 7:11 GMT

TechEd Australia 2014: Sydney

It was great fun speaking on Xamarin at TechEd last week. Thanks to all who were able to attend, and extra thanks to those who completed the evaluation and left some feedback. Special thanks also to the staff at White Clarke and the regulars at #SydMobNet who sat through my practice runs and gave some valuable input and pointers.