July 27, 2014 2:07 GMT

Using MessagingCenter in Xamarin Forms for ViewModel to ViewModel Navigation

When following the MVVM pattern your viewmodels should not communicate with each other directly, meaning no interdependencies. Navigation on the different platforms is from one view to another but we generally want to take control of the navigation structure at viewmodel level when coding cross platform apps (although admittedly, Xamarin Forms does give us more options here...). At its simplest this means that if you want to trigger navigation from one viewmodel to another you need to raise some sort of navigation event in the source view model and subscribe to this in the corresponding view. This event code would then navigate to the target view, which in turn would instantiate the target viewmodel. Simple. But the code can get messy. Most MVVM frameworks provide a message framework which can be used in this situation, and Xamarin Forms is no exception.

This code uses the MessageCenter provided by Xamarin Forms to perform this function. It's not meant to be a complete and standalone working project, but is rather some code snippets to demonstrate how the MessagingCenter can be used for this purpose.

As per the diagram above, the source viewmodel will send a message requesting a particular navigation:

MessagingCenter.Send<NavigationMessage>(new NavigationMessage() { Parameter = someObject }, eNavigationMessage.ShowTargetView.ToString());

A couple of points here. Firstly, you'll need a NavigationMessage class as follows:

    public class NavigationMessage


        public object Parameter { get; set; }


Secondly, note that second parameter to the Send method - a string. his can be used to differentiate between different messages of the same message type, so for navigation purposes this would contain things like “ShowCustomerView”, “ShowAccountView”, etc. depending on which view you’re requesting navigation to. Because these strings are used more than once (see the destructor notes below) and because it’s general good practice I’ve used an enumeration as follows:

public enum eNavigationMessage




Your source view will subscribe to this message. When the message is received it will navigate to the target view.

public SourceView()



    this.BindingContext = ViewModelLocator.SourceViewModel;



private void SubscribeToMessages()


    MessagingCenter.Subscribe<NavigationMessage>(this, eNavigationMessage.ShowTargetView.ToString(), (navigationMessage) =>




            // Perform the actual navigation here

            if (navigationMessage.Parameter != null)


                Navigation.PushAsync(new TargetView(navigationMessage.Paraneter));




                Navigation.PushAsync(new TargetView());



        catch(Exception ex)


            ServiceLocator.ErrorHandlingService.ReportError(ex, "SourceView.NavMessage", navigationMessage);




All views will instantiate their corresponding viewmodel (simple sample shown in the constructor above).

Lastly you’ll need a destructor to clean up these message subscriptions, like this:





private void UnsubscribeFromMessages()


    MessagingCenter.Unsubscribe<NavigationMessage>(this, eNavigationMessage.ShowTargetView.ToString());


I’ll try and put up some more posts fairly soon (pending deadlines) which will illustrate the use of this method in the context of an app which provides other functionality.

July 25, 2014 9:29 GMT

Contest: Code Monkeys in the Wild

We’ve shipped Xamarin Monkeys to every corner of the world, and it’s time for them to check in.  

For this contest, all you need to do is take a picture of your plush Xamarin monkey doing something awesome! Whether it be your favorite part of your town, on a trip to an exotic paradise, or simply hanging with your dog in your backyard, help show the world how far the Xamarin community reaches.

Looking for some inspiration? Check out our well-traveled friends on @ConceptMonkeys and @MotzMonkeys.

Monkeys in Seattle

How to Enter

  1. Take a picture of your monkey doing something amazing.
  2. Tweet your picture with the hashtag #xamarin #codemonkey

Don’t have a monkey yet? No problem.  Step into our Virtual Monkey Photo Booth by running our excellent “Working with Images” Xamarin.Forms tutorial on your phone for a stand-in monkey.



  • Best Monkey: Exclusive Xamarin Swag Bag
  • Best Virtual Monkey: Exclusive Xamarin Swag Bag + plush Xamarin monkey

All submissions must be made by August 4th at 8am EDT. A valid entry consists of a tweet with monkey(s). We will evaluate each photo and choose a winner based on novelty, photo quality, and reliability. Winners will be announced on Twitter. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up. There is no purchase necessary to enter the Code Monkeys in the Wild contest.

July 25, 2014 7:27 GMT

IoC Containers with Xamarin

When writing cross platform apps with Xamarin, our goal is share as close to 100% of our code across all the platforms. While this is an admirable goal to aim for, it is not realistic. Very often, we find ourselves needing to access a platform specific feature from our shared code. We have multiple options in this case. We could use a Shared Project with compiler directives, class mirroring, or partial classes and access the platform code alongside our shared code. Alternatively we could use an abstraction for the functionality in our shared code, and pass an implementation of the abstraction into our shared code. In this way, our shared code only needs to know about the abstraction, typically an interface. This strategy, known as Inversion of Control or IoC, works especially well when using Portable Class Libraries (PCL) for our shared code.

Even when using IoC, manually managing all of our dependencies, including instantiating the dependency tree for an object, can be tedious at best. This is where we turn to a host of existing IoC containers. The .net ecosystem has long had a wealth of choices in IoC containers. Some of the more popular ones include StructureMap, Castle Windsor, Ninject, Unity, and Autofac. These are by no means the only choices, up to and including rolling our own.

Not all of these containers are able to run in limitations imposed by mobile devices though. Phones and tablets have constrained cpu and memory, and iOS devices forbid JIT compiling and certain uses of reflection. Additionally, the library authors have to specifically compile for Xamarin.iOS and Xamarin.Android, either individually or as part of a PCL.

I decided to put together some sample code showing how the Xamarin-compatible IoC containers work. As of this writing (July, 2014) I have limited the comparison only to IoC containers that 1) I could get to work successfully and 2) had an available Nuget package for easy installation. I did not want to go through the process of pulling individual repositories and building the source from scratch, although that is a valid option. This excluded some options that I do want to mention as alternatives.

  • Xamarin.Forms Dependency Service. This is really more of a Service Locator than it is an IoC container. Also, it is only available as part of Xamarin.Forms.
  • Ninject. Currently, Ninject does not work in the limitations of a physical iOS device, although there is a branch in Github to address this. If this changes, I will update this post and the sample code to include it. Ninject is very popular on desktop and asp.net projects.
  • OpenNetCF. There is no nuget package for this library. Also, it requires custom attributes be added to the shared code, diminishing the usefulness.
  • XPlatUtils. There is no nuget package for this library.

The libraries that I focused on were Autofac, MvvmCross, TinyIoc, and Unity.

All of the code is available from my Github Repo

Sample Project

In the sample project, we have a single IoCDemo.Core project. This project contains the interface abstractions for our platform specific projects (ISettings and IPlatform) and a concrete ViewModel (MainViewModel) which takes the two interfaces as constructor dependencies. For each library, I created an iOS and an Android project to demonstrate wiring up the dependencies to platform specific implementations and creating the view model. Each container will be wired up in an App.cs file in each platform.

Some of the IoC containers have the ability to scan your assemblies and automatically wire up your dependecies. I chose not to use this ability. In a mobile app, every bit of cpu power is precious. I would rather spend the extra few seconds to write the code to wire up the dependency once at development time than have the app scan the assemblies every single time it is started.


Install-Package Autofac

Wiring up the container

using Autofac;  
using IoCDemo.Core;

namespace AutoFacDemo.iOS  
    public class App
        public static IContainer Container { get; set; }

        public static void Initialize()
            var builder = new ContainerBuilder();

            builder.RegisterInstance(new ApplePlatform()).As<IPlatform>();
            builder.RegisterInstance(new AppleSettings()).As<ISettings>();
            builder.RegisterType<MainViewModel> ();

            App.Container = builder.Build ();

Resolving the view model

MainViewModel viewModel = null;

using (var scope = App.Container.BeginLifetimeScope ()) {  
    viewModel = App.Container.Resolve<MainViewModel> ();


Install-Package MvvmCross.HotTuna.CrossCore

Wiring up the container

using Cirrious.CrossCore;  
using IoCDemo.Core;  
using Cirrious.CrossCore.IoC;

namespace MvvmCrossDemo.iOS  
    public static class App
        public static void Initialize ()
            MvxSimpleIoCContainer.Initialize ();
            Mvx.RegisterType<IPlatform, ApplePlatform> ();
            Mvx.RegisterType<ISettings, AppleSettings> ();

Resolving the view model

var viewModel = Mvx.IocConstruct<MainViewModel> ();  


Install-Package TinyIoc

Wiring up the container

using TinyIoC;  
using IoCDemo.Core;

namespace TinyIoCDemo.iOS  
    public static class App
        public static void Initialize ()
            var container = TinyIoCContainer.Current;

            container.Register<IPlatform, ApplePlatform> ();
            container.Register<ISettings, AppleSettings> ();

Resolving the view model

var viewModel = TinyIoC.TinyIoCContainer.Current.Resolve<MainViewModel> ();  


Install-Package Unity

Wiring up the container

using Microsoft.Practices.Unity;  
using IoCDemo.Core;

namespace UnityDemo.iOS  
    public class App
        public static UnityContainer Container { get; set; }

        public static void Initialize()
            App.Container = new UnityContainer();
            App.Container.RegisterType<IPlatform, ApplePlatform> ();
            App.Container.RegisterType<ISettings, AppleSettings> ();

Resolving the view model

var viewModel = App.Container.Resolve (typeof(MainViewModel), "mainViewModel") as MainViewModel;  

Again, checkout the sample app on my Github repo to compare our IoC container choices for Xamarin.

July 25, 2014 4:31 GMT

Build Your First F# Mobile App Contest Winners

The launch of Xamarin 3 at the end of May brought Xamarin developers access to first-class support for F#, enabling succinct, expressive and functional mobile apps for iOS and Android. We received many great entries, making it difficult to select just two winners.

First place goes to Bernard Hsu for his app Evolution! Evolution is, “a mobile app (iOS written in Xamarin) that demos Evolutionary situations in-silico.” Bernard ported the C# version of Evolution to utilize all of the functional power of F# and will be rewarded with a new Apple Mac Mini for the valiant effort. Congratulations!

Evolution App by Bernard Shoe

Second place goes to Peter Klima’s TripDiary app. TripDiary allows you to track your, “trips to nature, for culture or wherever you want, to go take pictures and make notes during your journey.” TripDiary shows off how to interact with a SQLite database in F#, as well as how to build up a complete user interface with maps, photos, and more. Congratulations, Peter, you’ll soon be sporting a new Samsung Gear Live Watch!


Thank you to everyone who participated in the F# contest! Once again, we are amazed to have such a strong and inspiring community following Xamarin. To show our thanks, everyone who submitted a valid entry to the contest will be receiving a plush Xamarin monkey. If you didn’t manage to get an entry submitted this time, no worries; keep an eye on the Xamarin Blog for future contest announcements!

July 25, 2014 3:39 GMT

Android's Built-in List Item Layouts

Android's List View allows us to iterate over an enumerable collection and display each piece of data in a list item. The list view works in conjunction with an adapter to loop over the data and display the data in a layout. We could, and often do, create our own layouts for this purpose. Customizing the layout allows us to match the list view's look and feel to the rest of our app, and to tailor the fields and controls that are shown.

For the times where we just want to display some simple data on the screen though, Android does include some built-in list item layouts. I was having a hard time finding any good documentation of these built-in layouts, so I have created a sample app displaying as many of the layouts as I could figure out. The app is written using Xamarin.Android.

All of the code is available from my Github repo

ArrayAdapter with SimpleListItem1

The simplest adapter to use is the built-in ArrayAdapter, using the built-in Android.Resource.Layout.SimpleListItem1 layout. This layout contains a single TextView, allowing display of a single piece of text.

using System;  
using Android.App;  
using Android.OS;  
using Android.Widget;

namespace ListViewDemo  
    [Activity (Label = "ExampleActivity")]
    public class ExampleActivity : ListActivity
        protected override void OnCreate (Bundle savedInstanceState)
            base.OnCreate (savedInstanceState);

            var kittens = new [] { "Fluffy", "Muffy", "Tuffy" };

            var adapter = new ArrayAdapter (
                                this, //Context, typically the Activity
                                Android.Resource.Layout.SimpleListItem1, //The layout. How the data will be presented 
                                kittens //The enumerable data

            this.ListAdapter = adapter;

The other layouts include (with the controls available)


  • 1 ImageView (Android.Resource.Id.Icon)
  • 1 TextView (Android.Resource.Id.Text1)


  • 1 TextView (Android.Resource.Id.Text1)


  • 1 TextView/Title (Android.Resource.Id.Text1)
  • 1 TextView/Subtitle (Android.Resource.Id.Text2)


  • 1 TextView (Android.Resource.Id.Text1)
  • Note : Set choice mode to multiple or single
  this.ListView.ChoiceMode = ChoiceMode.Multiple;


  • 1 TextView (Android.Resource.Id.Text1)
  • 1 TextView/Subtitle (Android.Resource.Id.Text2)
  • Note : Set choice mode to multiple or single
  this.ListView.ChoiceMode = ChoiceMode.Multiple;


  • 1 TextView (Android.Resource.Id.Text1)
  • Note : Set choice mode to multiple or single
  this.ListView.ChoiceMode = ChoiceMode.Multiple;


  • 1 TextView (Android.Resource.Id.Text1)
  • Note : Set choice mode to multiple or single
  this.ListView.ChoiceMode = ChoiceMode.Multiple;


  • 1 TextView (Android.Resource.Id.Text1)
  • Note : Set choice mode to single
  this.ListView.ChoiceMode = ChoiceMode.Single;


  • 1 TextView (Android.Resource.Id.Text1)


  • 1 TextView/Title (Android.Resource.Id.Text1)
  • 1 TextView/Subtitle (Android.Resource.Id.Text2)

Again, checkout the Xamarin.Android sample app on my Github repo to see these list view layouts in action.

July 23, 2014 11:19 GMT

Using Twilio with Xamarin

Twilio recently published a great component to enable iOS and Android apps developed with Xamarin to easily add VoIP capabilities.

twilio component

This post walks through making a simple app to call a phone number.

Setting up the Twilio Server

The first thing you need to do is sign up for a Twilio account. They have a free trail version, which you can sig nup for at https://www.twilio.com/try-twilio, that will work fine for our purposes.

Before getting started there is a bit of setup you’ll need to perform in the Twilio portal.

When you set up a Twilio account, you’ll be given a Twilio phone number. You can view your phone number at any time by selecting the “Numbers” section in the Twilio user account page:


You’ll also need your account SID and auth token, which you can get under the “dashboard” section of the account page.


The last thing you’ll need to create is a TwiML app, which you can do under “Dev Tools” > “TwiML Apps”. Set the app url to http://YourDomain/InitiateCall as shown below:


Note the SID here is the application SID,as opposed to the account SID shown earlier.

We these things in place, you’re ready to get started coding. Twilio requires a server to handle token generation and in this case, the TwiML app to initiate the call.

A free ASP.NET MVC website in Azure works fine. Here’s the full code for the ASP.NET MVC controller for this example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twilio;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

namespace TokenGenerator.Controllers
    public class ClientController : Controller
        public ActionResult Token(string clientName = "default")
            string accountSid = "Your account SID";
            string authToken = "Your auth token";
            string appSid = "Your app SID";
            var capability = new TwilioCapability(accountSid, authToken);

            return Content(capability.GenerateToken());

        public ActionResult InitiateCall(string source, string target)
            var response = new TwilioResponse();
            response.Dial(target, new { callerId = source });

            return new TwiMLResult(response);

For the above code, you’ll also need to add a couple NuGet packages:

  • Twilio.Mvc
  • Twilio.Client

Then, simply replace the accountSid, authToken and appSid with the values obtained above and publish the site to Azure.

Using the Xamarin Twilio Component

For this example I’m just going to create a simple iOS client to make an outgoing call. However, Android is supported as well.

In a new iOS project create 3 buttons named callButton, hangUpButton and sendKeyButton (I used a storyboard to create the UI) and add the following code to the view controller.

using System;
using System.Net.Http;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using TwilioClient.iOS;

namespace HelloTwilio
    public partial class HelloTwilioViewController : UIViewController
        TCDevice device;
        TCConnection connection;

        public HelloTwilioViewController (IntPtr handle) : base (handle)

        public async override void ViewDidLoad ()
            base.ViewDidLoad ();

            var client = new HttpClient ();
            var token = await client.GetStringAsync ("http://YourSite/Client/Token");

            device = new TCDevice (token, null);
            callButton.TouchUpInside += (object sender, EventArgs e) => {

                string twilioNumber = "Your twilio number";
                string numberToCall= "Some number to call";

                var parameters = NSDictionary.FromObjectsAndKeys (
                    new object[] { twilioNumber, numberToCall }, 
                    new object[] { "Source", "Target" }
                connection = device.Connect (parameters, null);

            sendKeyButton.TouchUpInside += (object sender, EventArgs e) => {
                if (connection != null) {
                    connection.SendDigits ("1");

            hangUpButton.TouchUpInside += (object sender, EventArgs e) => {
                if (connection != null) {
                    connection.Disconnect ();

In the code, set the domain name you published to earlier where it says “YourSite” and add your Twilio number and a phone number to call respectively.

Adding the Twilio component is easy. Just right-click on “Components” in the Solution Explorer, select “Get More Components”, and pick the Twilio component.

Once the component is added, run the application and click “Call”. After hearing the trial account message, press the “Send Key 1″ button and the phone call will be initiated.

phone app

There you have it, VoIP added to an iOS app. Pretty cool :)

July 23, 2014 5:09 GMT

New Sprite Kit Physics Features in iOS 8

Sprite Kit, the 2D game framework from Apple, has some interesting new features in iOS 8 and OS X Yosemite. These include integration with Scene Kit, shader support, lighting, shadows, constraints, normal map generation and physics enhancements. Previously, I went through an introduction to Sprite Kit. This post will take a look at some of the new physics features, particularly improvements to physics bodies and physics fields.


Creating a Physics Body from a Texture

Sprite Kit now supports deriving the physics body of a sprite from its texture. This makes it easy to implement collisions that look more natural.

For example, notice in the following collision how the banana and monkey collide nearly at the surface of each image:

physics collision

Sprite Kit makes creating such a physics body possible with a single line of code. Simply call SKPhysicsBody.Create with the texture and size:

sprite.PhysicsBody = SKPhysicsBody.Create (sprite.Texture, sprite.Size);

Additionally, you can tune how the physics body is derived by passing in an alpha threshold, which defines the minimum alpha value a pixel must have to be included in the resulting physics body.

sprite.PhysicsBody = SKPhysicsBody.Create (sprite.Texture, 0.7f, sprite.Size);

Tweaking the alpha threshold like this fine-tunes the previous collision, such that the monkey falls over when colliding with the banana:

physic collision alpha threshold

Physics Fields

Another great addition to Sprite Kit is the new physics field support. These allow you to add things such as vortex fields, radial gravity fields and spring fields to name just a few.

Physics fields are created using the SKFieldNode class, which is added to a scene just like any other SKNode. There are a variety of factory methods on SKFieldNode to create different physics fields. You can create a spring field by calling SKFieldNode.CreateSpringField(), a radial gravity field by calling SKFieldNode.CreateRadialGravityField(), etc.

SKFieldNode also has properties to control field attributes such as the field strength, the field region, the noise used to generate forces, and the amount of attenuation of field forces as you move away from the field.

For example, the following code creates a spring field and adds it to the scene:

SKFieldNode fieldNode = SKFieldNode.CreateSpringField ();
fieldNode.Enabled = true;
fieldNode.Position = new PointF (Size.Width / 2, Size.Height / 2);
fieldNode.Strength = 0.5f;
fieldNode.Region = new SKRegion(Frame.Size);
AddChild (fieldNode);

You can then add sprites and set their PhysicsBody properties so that the sprites will be affected by the physics field, as the following code does when the user touches the screen:

public override void TouchesBegan (NSSet touches, UIEvent evt)
    var touch = touches.AnyObject as UITouch;
    var pt = touch.LocationInNode (this);
    var node = SKSpriteNode.FromImageNamed ("TinyBanana");
    node.PhysicsBody = SKPhysicsBody.Create (node.Texture, node.Size);
    node.PhysicsBody.AffectedByGravity = false;
    node.PhysicsBody.AllowsRotation = true;
    node.PhysicsBody.Mass = 0.03f;
    node.Position = pt;
    AddChild (node);

This causes the bananas to oscillate like a spring around the field node:

spring force field

Adding a different field is similar. For instance, the following code creates a radial gravity field:

SKFieldNode fieldNode = SKFieldNode.CreateRadialGravityField ();
fieldNode.Enabled = true;
fieldNode.Position = new PointF (Size.Width / 2, Size.Height / 2);
fieldNode.Strength = 10.0f;
fieldNode.Falloff = 1.0f;

As you can see, this results in a different force field, where the bananas are pulled radially about the field:

radial gravity field

With the new features added to Sprite Kit in iOS 8, it’s now very easy to create interesting effects in 2D iOS and OS X games. Have fun!

The code from this post is available in my GitHub repo.

Discuss this blog post in the Xamarin Forums

July 22, 2014 4:50 GMT

Announcing the Xammy Awards

Xammy BadgesWe are excited to announce the Xammy Awards, which will be awarded this year at Xamarin Evolve 2014. Xamarin developers represent the world’s top mobile developers and this is your chance to be recognized on our global stage.

Apps can be submitted in the following 4 categories:

  • Consumer: Tell us how your app changes the way we interact with the world and each other.
  • Gaming: Show us how you’ve created a breakthrough new game concept, or otherwise advanced the craft of game development.
  • Enterprise: Highlight how your app is transforming business processes and making BYOD work for employees and businesses.
  • Emerging Devices: Showcase how you’re taking C# to new form factors, and pioneering the next generation of mobile experiences.

There will be winners in each category, a Grand Prize winner, and a Developers’ Choice winner. Submissions are open from now until August 11th, and winners in the 4 categories will be announced at Xamarin Evolve 2014.

There is only one chance to claim a category for this inaugural year of the Xammy Awards — submit your app today!

July 22, 2014 3:38 GMT

Heading Home to Phoenix for 2 Xamarin Talks and Workshop

After several trips around the US in the last few weeks, I am finally heading back to my second home, Phoenix AZ. I will be driving all around the valley visiting and presenting at several local user groups this week. This weekend I will be presenting and helping at a Xamarin workshop to help build a brand new Code Camp mobile app! If you are in the Phoenix area and want to chat Xamarin and other mobile development goodness please swing by an event!

Wednesday July 23rd 6:00PM: North West Valley .NET (Glendale, AZ)
Topic: Building iOS, Android, and Windows Apps in C# with Xamarin
More info & Register Here

Thursday July 24th 6:00PM: Arizona - Xamarin Mobile Developers (Scottsdale, AZ)
Topic: Xamarin 3! iOS and Android Development in C# with Xamarin
More info & Register Here

Saturday July 26th 8:00AM: Xamarin Workshop (Chandler, AZ)
Topic: Full day Xamarin workshop. Lunch included!
More info & Register Here

I hope to see you there!

Photo from filckr user cobolt123

July 22, 2014 11:35 GMT

Xamarin Evolve 2014: Announcing Training Classes & 39 Conference Sessions

Xamarin Evolve 2014 in Atlanta, GA, October 6-10We are very excited to announce the first major wave of amazing, expert-led sessions for Xamarin Evolve 2014, our annual developer conference, happening from October 6-10 in Atlanta, Georgia.

In-Depth Training Sessions Announced

Attend two days of training from Xamarin University spanning all topics from mobile development fundamentals to advanced areas such as enterprise security and data integration, getting the most from Xamarin.Forms, advanced iOS and Android topics such as graphics and animation, and tackling mobile quality with Xamarin Test Cloud.

Ten Tracks to Meet All of Your Mobile Development Needs

During three conference days, you will have the chance to attend over 50 live sessions, in 10 tracks, led by industry leaders and experts from Microsoft, GitHub, Facebook and more, covering all areas of mobile development:

  • Xamarin Platform: deep dive into C#, F#, Async, and getting the most from Xamarin Studio and Visual Studio.
  • iOS: learn about what’s new in Xamarin.iOS and iOS 8, binding Objective-C libraries, and memory management tips and tricks.
  • Android: get the scoop on Material design in Android L, the latest in Xamarin.Android, and effective navigation.
  • Cross-Platform: gain new skills in hybrid app development, Xamarin.Forms, iBeacons, augmented reality, and code-sharing architectures.
  • Mobile Best Practices: see how experts are achieving great mobile UI and UX, using functional reactive programming, and navigating the tricky world of app stores.
  • Enterprise Mobility: hear from a panel of experts on mobile security, building a modern DevOps solution, and learn from real world case studies from top companies.
  • Emerging Devices: mobile is rapidly moving beyond phones and tablets, so this is your chance to learn how Xamarin helps you get C# to all of these new form factors.
  • Gaming: From building games in iOS 8 to some secret announcements, you’ll be well equipped to build the next with Xamarin.
  • Testing: crashes and regressions are the top reasons for poor app adoption. Learn how to incorporate automated UI testing into your development workflow. Your users with thank you.
  • Mobile Ecosystem: add more awesome to your apps by leveraging the rich ecosystem of cloud services, libraries and controls that integrate with the Xamarin platform.

Register now to get your ticket to mobile expertise!

Register Now

Team Xamarin

July 22, 2014 4:38 GMT

Having Fun With UIVisualEffectViews in iOS 8 & Xamarin

As you have probable seen by now, UIVisualEffectView in iOS 8 gives us an easy way to apply a blur or vibrancy effect to UI elements. While alone this effect is pretty cool, I wanted to see what we could do if we had a bit of fun with it.

Blurred MapView

The concept here is to force the focus on the location you wish the user to be looking. To do this we blur out the entire map but leave a circular transparent section in the centre. To do this we set up our view like this:

private UIVisualEffectView blurView;
private const int CIRCLE_RECT_SIZE = 250;

public override void ViewDidLoad ()
   base.ViewDidLoad ();
   this.blurView = new UIVisualEffectView (UIBlurEffect.FromStyle (UIBlurEffectStyle.Light));
   this.blurView.Frame = this.View.Frame;
   //Allows the map underneath to be interacted with
   this.blurView.UserInteractionEnabled = false;
   this.View.Add (this.blurView);

   //Create a masking layer to cut out a section of the blur
   var maskLayer = new CAShapeLayer ();
   var maskPath = new CGPath ();
   maskPath.AddRect (this.blurView.Bounds);
   maskPath.AddEllipseInRect (new RectangleF (((this.blurView.Bounds.Width - CIRCLE_RECT_SIZE) / 2),   ((this.blurView.Bounds.Height - CIRCLE_RECT_SIZE) / 2), CIRCLE_RECT_SIZE, CIRCLE_RECT_SIZE));
   maskLayer.Path = maskPath;
   maskLayer.FillRule = CAShapeLayer.FillRuleEvenOdd;
   this.blurView.Layer.Mask = maskLayer;

Effect Button

Following on with the circle theme, here is a button which contains a UIEffectView clipped to a circle. This gives it an interesting look different from a usual UIButton.

public CircularEffectButton (PointF location, float size, UIVisualEffect effect, UIColor backgroundColor, string title, UIColor titleColor)
: base(UIButtonType.Custom)
   this.Frame = new RectangleF(location, new SizeF(size, size));
   this.effectView = new UIVisualEffectView (effect);
   this.effectView.Frame = new RectangleF(new PointF(0,0), this.Frame.Size);
   //Allows for the button to be tappable
   this.effectView.UserInteractionEnabled = false;
   this.Add (this.effectView);
   //Set a background color with a small Alpha (gives a hint of color)
   this.BackgroundColor = backgroundColor.ColorWithAlpha(0.2f);
   this.SetTitle (title, UIControlState.Normal);
   //Get a color which contrast the background for the title text
   var contrastingColor = this.ContrasingColor (backgroundColor);
   this.SetTitleColor (contrastingColor, UIControlState.Normal);
   this.TitleLabel.AdjustsFontSizeToFitWidth = true;
   this.TitleLabel.TextAlignment = UITextAlignment.Center;
   this.Layer.CornerRadius = size / 2;
   this.Layer.BorderWidth = 1;
   this.Layer.BorderColor = contrastingColor.CGColor;
   this.ClipsToBounds = true;

Bringing this all together gives us something like this!

Obviously this amount of dynamic effects takes a significant amount of processing power. Always remember “WITH GREAT POWER THERE MUST ALSO COME–GREAT RESPONSIBILITY!”

Get the sample on GitHub here.

July 21, 2014 6:00 GMT

Live Webinar: Test Apps on Hundreds of Devices with Xamarin Test Cloud

Xamarin Test Cloud

There are hundreds of mobile devices, OS versions, form factors and screen resolutions in use today, and your app needs to run on all of them. Xamarin Test Cloud makes it fast and easy to test your mobile apps on hundreds of real iOS and Android devices in the cloud, automatically.

Join Chris King, Xamarin’s Sr. Customer Success Engineer, for a live webinar this Thursday, July 24th at 8am PDT/ 11am EDT to find out why Xamarin Test Cloud is the easiest and fastest way to automate UI testing to ensure that you find bugs before your users do.

All registrants will receive a copy of the webinar, so please feel free to register even if you can’t attend.

Register Here

Want to get a head-start for the webinar? Take a few minutes to learn more about Xamarin Test Cloud.

July 17, 2014 5:52 GMT

Using Custom Controls in Xamarin.Forms on Windows Phone

Xamarin.Forms lets developers create native user interfaces on iOS, Android and Windows Phone from a single, shared C# codebase. Since the UI is rendered using the native controls of the target platform, it gives you great flexibility in customizing the controls separately on each platform. Each control is rendered differently on each platform using a Renderer class, which in turn creates a native control, arranges it on the screen and adds the behavior specified in the shared code.

Previously, we showed you how to build custom renderers in Xamarin.Forms on iOS and Android platforms to extend custom built controls. In case you missed it, its all here:

In practice,  you will use the same techniques to create custom renderers on Windows Phone as well.


Windows Phone Custom Controls

.NET third party vendors provide you with wide range of top quality reusable UI controls on the Windows Phone platform. Sometimes it is easier to buy and use them than to build something on your own. Especially, the data visualization controls such as charts that transform your tabular data into something beautiful on the Windows Phone screen.

In this blog post, I will take you through steps involved in integrating a Infragistics XamDataChart control for Windows Phone in Xamarin.Forms. Xamarin.Forms-CustomControl-Charts

There are two main parts to implementing a custom control with a renderer -

  1. Create your own custom Xamarin.Forms control with bindable properties in Shared Project so that Xamarin.Forms API can refer them.
  2. Create a renderer in Windows Phone platform that will be used to display the Infragistics XamDataChart control and subscribe to property changed notifications

CustomChartView Control

In my shared project, I’m going to create a new control called CustomChartView that will be used in my Xamarin.Forms page. CustomChartView must inherit from Xamarin.Forms.View.

public class CustomChartView : View
  public static readonly BindableProperty ItemSourceProperty =
    BindableProperty.Create<CustomChartView, StockMarketDataSample>(p =>
    p.ItemSource, new StockMarketDataSample());
  public StockMarketDataSample ItemSource
    get { return (StockMarketDataSample)GetValue(ItemSourceProperty); }
    set { SetValue(ItemSourceProperty, value); }
  // Additional bindable properties

Notice the BindableProperty called ItemSourceProperty - this property is my DataModel which is of type StockMarketDataSample that has some necessary logic to simulate live data. In a real scenario, this will be replaced with the data that comes from a web service or something similar. In the code, you will see two more properties PriceDisplayType and ShowSpline. These are the properties that will help us interact with the chart for e.g. for changing the Price Type (CandleStick or OHLC) or Show/Hide a SplineAreaSeries from Xamarin.Forms controls.

CustomChartView Renderer

Now, with my Xamarin.Forms control in place I can write some Windows Phone platform specific code. I will implement a CustomChartViewRenderer class that inherits from a ViewRenderer and layout the XamDataChart on it.

public class CustomChartViewRenderer : ViewRenderer<CustomChartView, XamDataChart>
  XamDataChart DataChart;
  public CustomChartViewRenderer()
    DataChart = new XamDataChart();
  //.. code

Since this renderer on Windows Phone inherits from View, which means Xamarin.Forms will handle all of the size calculations and will have the normal properties of a standard Windows Phone View. Add the XamDataChart to the project and update the references accordingly. Additionally, you will need to add more code to set your XAxis, YAxis and the FinancialPriceSeries to the XamDataChart. That code has been omitted from this post for brevity.

Now, I will set my renderer to display the XamDataChart control when the CustomChartView is added to the page layout. This is done by overriding the OnElmentChanged method and calling the SetNativeControl method in it.

protected override void OnElementChanged(ElementChangedEventArgs<CustomChartView> e)
  if (e.OldElement != null || this.Element == null)

UpdateChart() method is a private method that sets the DataContext of the XamDataChart control to the Xamarin.Forms CustomChart control’s ItemSource property.

private void UpdateChart()
  DataChart.DataContext = this.Element.ItemSource;
  DateXAxis.ItemsSource = this.Element.ItemSource;
  series.ItemsSource = this.Element.ItemSource;
  //.. code

Export Renderer Attribute

[assembly: ExportRenderer((typeof(CustomChartView)), typeof(CustomChart.WinPhone.ViewRenderers.CustomChartViewRenderer))]
namespace CustomChart.WinPhone.ViewRenderers
  public class CustomChartViewRenderer : ViewRenderer<CustomChartView, XamDataChart>

To get the control to show up in the actual view, I need to set an attribute ExportRenderer to the CustomChartViewRenderer class.

Wiring up the UI in XAML

Finally, I will add our custom control to the Page.  There are two approaches to create user interfaces in Xamarin.Forms. The first one is to create UI views entirely with source code using the Xamarin.Forms API. The other option available is to use Extensible Application Markup Language (XAML) which is the approach I’ve taken to build this demo.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >
            <RowDefinition Height="80"/>
            <RowDefinition Height="80"/>
            <RowDefinition Height="*" />
            <RowDefinition Height="1" />
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="1"/>
        <StackLayout Orientation="Horizontal" Grid.Row="0" Grid.Column="0" HorizontalOptions="Center">
            <Button Text="Start" x:Name="StartButton" />
            <Button Text="Stop"  x:Name="StopButton"  />
            <Label Text="Spline:" VerticalOptions="Center"/>
            <Switch x:Name="ShowSplineSwitch"/>
        <Picker x:Name="chartPicker" Title="Chart Type" HorizontalOptions="FillAndExpand" VerticalOptions="Center" Grid.Row="1"/>
        <custom:CustomChartView x:Name="chart" Grid.Row="2" />

This page contains a Start Button – that starts a live feed, a Stop Button – thats stops the live feed, a Switch – that lets you show/hide a SplineAreaSeries in the Chart, and a Picker – that let’s you choose the Price Display Type (CandleStick or OHLC).


Handling Property Changes 

In the CustomChartControl of the shared project, along with the ItemSourceProperty, I have exposed the PriceDisplayTypeProperty and ShowSplineProperty as well. We can now easily set these property to interact with the XamDataChart. To make this work, we need to listen to the property changed event and set appropriate property of the XamDataChart. We will override the OnElementPropertyChanged method in the CustomChartViewRenderer class to do so.

protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  base.OnElementPropertyChanged(sender, e);
  if (Control == null || Element == null)
  if (e.PropertyName == CustomChart.CustomControls.CustomChartView.PriceDisplayTypeProperty.PropertyName)
    series.DisplayType = Element.PriceDisplayType.ToIGPriceType();
  if (e.PropertyName == CustomChart.CustomControls.CustomChartView.ShowSplineProperty.PropertyName)
private void ShowHideSpline()
  if (this.Element.ShowSpline)
  else if (DataChart.Series.Contains(splineSeries))

Bringing it all together

That’s it! Now we can set these properties in the appropriate event handlers of the controls. Also, setting the ItemSource property to a StockMarketDataSample will populate the chart with the values.

public HomePage ()
  InitializeComponent ();
  chart.ItemSource = _data = new StockMarketDataSample();
void ShowSplineSwitch_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
  chart.ShowSpline = e.Value;
void chartPicker_SelectedIndexChanged(object sender, EventArgs e)
  PriceDisplayType priceDisplayType;
  if (Enum.TryParse<PriceDisplayType>(chartPicker.Items[chartPicker.SelectedIndex], out priceDisplayType))
    chart.PriceDisplayType = priceDisplayType;

To simulate a Live Data, StockMarketServiceClient is used which has a timer that ticks every few milliseconds and raises an event with new value. Subscribing to that event and updating the ItemSource will change the visualization in the chart.

Xamarin.Forms-CustomControl-WPTo learn more about customizing your Xamarin.Forms controls and applications be sure to read our documentation.

Infragistics controls were used as an example in this post to show you how well Xamarin.Forms can integrate with third party controls. You can use any third party controls or custom controls that you have built with Xamarin.Forms and the procedure to get that working remains the same. 

Source Code

You can download the full source code for this project from my GitHub. Make sure you download and install Infragistics libraries before compiling.

Discuss this blog post in the Xamarin Forums

July 17, 2014 5:47 GMT



For the past couple months, I have been working on a top secret project that aims to redefine the way work will get done, address key industry mobility challenges and spark true mobile-led business change. I’m just kidding, it’s a podcast player!


Mocast is not going to redefine how work gets done, but I am hoping it redefines how you listen to podcasts.

I wrote Mocast because I was unhappy with the iOS podcast app selection. While there are almost as many iPhone podcast players as there are weather apps, I find that they all have two fatal flaws.

First, they take downloads way too seriously. Most UIs differentiate downloaded vs. not downloaded episodes and bifurcate their interface along those lines. This is silly to us podcastistas who aren’t the greatest at planning ahead.

Second, they take new episodes too seriously. Whole apps seem built with only new episodes in mind as they hide away the back catalog. I don’t know why this is. My favorite podcast, The Incomparable has an amazingly rich back catalog of episodes that I love to listen to. It’s nice when a new episode arrives but there’s no need over-emphasize them at the cost of the full catalog.


First, and most importantly, downloads are completely optional when using Mocast. You can always play an episode immediately, whether you have downloaded it or not thanks to streaming.

Next, it’s a single-screen thumb-based UI. You see, I walk a lot in parks and can’t stand apps that have a complex navigation history with back buttons with crazy nesting - I need to be able to do everything with my thumb and I need the screen to be predictable. Mocast makes that possible. You will only ever see a list of episodes, a search box, and play controls. There is no Now Playing screen, no episode screens, just episodes and a big play button. I even tried to limit the number of buttons all together. This is a slide-happy, thumb loving app.

Mocast puts you in control with queues. Mocast presents four different lists of episodes: Per-podcast, New, Queued, and History. While Mocast manages most of those lists, The Queue is fully under your control. You can add episodes to listen to later or setup a nice set of old favorites to listen to when nothing new is coming in.

Mocast acknowledges and embraces our busy lives that prevent us from completing episodes. It keeps a running History of past played episodes (and of course where you left off) so that you can jump around between episodes without ever worrying about forgetting to finish one.

Lastly, and this is one of my favorite features, Mocast lets you perform offline full-text searches of all episodes’ show notes. Do you want to see all podcasts that mentioned WWDC 2014? Easy. How about all Star Wars episodes? Done. Every list Mocast shows is searchable and the search box is always ready for you at the top of the app.

A bit of fun

While I truly believe Mocast has a lot to offer in terms of usability, I think it’s a fun app too. Here are a few of my favorite features.

Siri is used to announce episodes. Yes, that Siri. It took some string pulling and I have to deal with a 150 page rider, but she’s there to let you know what you’re listening to.

The time scrubber is thumb friendly, velocity controlled, big and bold. I can’t stand apps with tiny scrubbers so I hope you will enjoy this one.

Dark disco theme that adapts to your episodes. Mocast is just a sad dark gray app until you start adding podcasts. But once they’re in, it lights up with their colors and keeps those colors moving around. It’s hard to describe in words, so I hope you’ll risk the $3 to see for yourself.

There are more features than this tucked away! I hope you’ll check them out!


As with all my apps, I wrote Mocast in C# using Xamarin.iOS. She came out to be about 8,000 loc with about 60% of that code lying in the UI layer.

July 17, 2014 2:31 GMT

Custom Modal Transitions in iOS 8 & Xamarin

With the advent of iOS 8 and the inclusion of the UIPresentationController we now have a free reign in terms of presenting and transitioning to modal views in iOS.

To create a custom modal transition we are required to use 3 classes:

  • UIPresentationController
  • UIViewControllerAnimatedTransitioning
  • UIViewControllerAnimatedTransitioningDelegate

Apart from the excessively long names, these classes are really easy to use and setting up your awesome modal presentation transition will be a doddle.


This class is responsible for being the container of the view being presented, in my example we create a dimmed view to overlay the view being transitioned from. The required overriden methods / properties are:

  • FrameOfPresentedViewInContainerView: returns a frame which the presented view will be displayed in.
  • PresentationTransitionWillBegin: apply any visual configuration / animations to the container view before the presenting transition.
  • DissmissalTransitionWillBegin: apply any visual configuration / animations to the container view before the dismissing transition.
public override RectangleF FrameOfPresentedViewInContainerView {
   get {
           var containerBounds = this.ContainerView.Bounds;

           var presentedViewFrame = RectangleF.Empty;
           presentedViewFrame.Size = new SizeF (300, 300);
           presentedViewFrame.X = (containerBounds.Width / 2) - (presentedViewFrame.Width / 2);
           presentedViewFrame.Y = (containerBounds.Height / 2) - (presentedViewFrame.Height / 2);

           this.PresentedView.Layer.CornerRadius = presentedViewFrame.Size.Width / 2;
           this.PresentedView.ClipsToBounds = true;

           return presentedViewFrame;

public override void PresentationTransitionWillBegin ()
   this.dimmingView.Frame = this.ContainerView.Bounds;
   this.dimmingView.Alpha = 0;

   this.ContainerView.InsertSubview (this.dimmingView, 0);
   var coordinator = this.PresentedViewController.GetTransitionCoordinator ();
   if (coordinator != null) {
      coordinator.AnimateAlongsideTransition((context) => 
         this.dimmingView.Alpha = 1;
      (context) => 
   } else {
      this.dimmingView.Alpha = 1;

public override void DismissalTransitionWillBegin ()
   var coordinator = this.PresentedViewController.GetTransitionCoordinator ();
   if (coordinator != null) {
      coordinator.AnimateAlongsideTransition((context) => 
         this.dimmingView.Alpha = 0;
      (context) => {});
   } else {
      this.dimmingView.Alpha = 0;


The main animation to display the presented view is handled here, there are only two required methods to override:

  • TransitionDuration: returns (as per the name) the duration of the transition based on the transitioning context.
  • AnimateTransition: create you animation transition between your two view controllers here.
public override double TransitionDuration (IUIViewControllerContextTransitioning transitionContext)
   return 0.5;

public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext)
   var fromVC = transitionContext.GetViewControllerForKey (UITransitionContext.FromViewControllerKey);
   var fromView = fromVC.View;
   var toVC = transitionContext.GetViewControllerForKey (UITransitionContext.ToViewControllerKey);
   var toView = toVC.View;
   var containerView = transitionContext.ContainerView;

   var isPresentation = this.IsPresentation;

   if (isPresentation) {
      containerView.AddSubview (toView);

   var animatingVC = isPresentation ? toVC : fromVC;
   var animatingView = animatingVC.View;

   var appearedFrame = transitionContext.GetFinalFrameForViewController (animatingVC);
   var dismissedFrame = this.startFrame;

   var initialFrame = isPresentation ? dismissedFrame : appearedFrame;
   var finalFrame = isPresentation ? appearedFrame : dismissedFrame;
   animatingView.Frame = initialFrame;

   UIView.AnimateNotify (0.5f, 
      UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.BeginFromCurrentState,
      () => { animatingView.Frame = finalFrame;	},  
      new UICompletionHandler((bool finished) => 


The glue that holds all of this awesomeness together, responsible for creating the UIPresentationController and marshalling the UIViewControllerAnimatedTransitioning instances for dismissal and presentation.

public override UIPresentationController GetPresentationControllerForPresentedViewController (UIViewController presentedViewController, UIViewController presentingViewController, UIViewController sourceViewController)
   if (this.awesomePresentationController == null) {
      this.awesomePresentationController = new AwesomePresentationController (presentedViewController, presentedViewController);
   return this.awesomePresentationController;
public override IUIViewControllerAnimatedTransitioning GetAnimationControllerForDismissedController (MonoTouch.UIKit.UIViewController dismissed)
   var transitioning = this.AnimationTransitioning;
   transitioning.IsPresentation = false;
   return transitioning;

public override IUIViewControllerAnimatedTransitioning PresentingController (UIViewController presented, UIViewController presenting, UIViewController source)
   var transitioning = this.AnimationTransitioning;
   transitioning.IsPresentation = true;
   return transitioning;

Implementing The Presentation

this is done in a few lines of code as follows:

partial void TransitionPressed (MonoTouch.Foundation.NSObject sender)
   var overlayVC = (OverlayViewController)this.Storyboard.InstantiateViewController("OverlayVC");

   this.transitioningDelegate = new AwesomeTransitioningDelegate (((UIButton)sender).Frame);

   overlayVC.ModalPresentationStyle = UIModalPresentationStyle.Custom;
   overlayVC.TransitioningDelegate = this.transitioningDelegate;

   this.PresentViewControllerAsync(overlayVC, true);

Get the sample on GitHub here.

July 16, 2014 5:33 GMT

New Collection View Features in iOS 8

Collection Views are a powerful user interface technology for laying out collections of data. With fantastic support for high performance grid layouts, flexible line based layouts, and fully custom layouts, along with integrated animation capabilities, they make creating beautiful data-driven UIs a wonderful experience both for the developer and the end user.

collection views

iOS 8 adds some nice enhancements to Collection Views, including the ability to self-size cells without the need for using a delegate. Likewise, the layout attributes of individual cells can now be adjusted directly from within the cell class without having to use a delegate. This makes it easier to make small layout changes that are related to a particular cell.

Self-sizing Cells

First, let’s look at how to self-size cells. Before iOS 8, creating cells that sized to their content required working within a layout class directly or via a layout’s delegate, such as the UICollectionViewDelegateFlowLayout.

For example, the following code adjusts the cell size to fit cells comprised of simple UILabels, presented using a UICollectionViewFlowLayout:

class FlowLayoutDelegate : UICollectionViewDelegateFlowLayout
  string[] items;
  UIStringAttributes attr;
  public FlowLayoutDelegate (string[] items)
    this.items = items;
    attr = new UIStringAttributes {
      Font = new UILabel ().Font
  public override SizeF GetSizeForItem (UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath)
    string text = items [indexPath.Row];
    return new NSString (text).GetSizeUsingAttributes (attr);

This code results in a Collection View where each cell fits the text it contains:

self sizing cells

Creating cells that are self-sized is much easier in iOS 8. Simply set the EstimatedItemSize on the UICollectionViewFlowLayout and implement SizeThatFits or use AutoLayout in the cell class.

For example, to self-size the cells in the example above, set EstimatedItemSize as shown below:

flowLayout = new UICollectionViewFlowLayout (){
  EstimatedItemSize = new SizeF (44, 144)

Then, simply adding the following implementation of SizeThatFits in the cell class produces the same result, without the need for the UICollectionViewDelegateFlowLayout implementation:

public override SizeF SizeThatFits (SizeF size)
  label.Frame = new RectangleF (new PointF (0, 0), label.AttributedText.Size);
  return label.AttributedText.Size;

Adjusting Layout Attributes in Cells

iOS 8 also makes it easier to manipulate the layout attributes returned from within the cell class without resorting to a UICollectionViewDelegateFlowLayout. Just override PreferredLayoutAttributesFittingAttributes in the cell class.

The following code changes the font of every other label and adjusts the layout for each cell appropriately:

public override UICollectionViewLayoutAttributes PreferredLayoutAttributesFittingAttributes (UICollectionViewLayoutAttributes layoutAttributes)
  var newLayoutAttributes = (UICollectionViewLayoutAttributes)layoutAttributes.Copy ();
  if (layoutAttributes.IndexPath.Row % 2 == 0) {
    label.TextColor = UIColor.Red;
    ContentView.BackgroundColor = UIColor.LightGray;
    var attr = new NSAttributedString (Text, UIFont.SystemFontOfSize (28.0f));
    label.Font = UIFont.SystemFontOfSize (28.0f);
    newLayoutAttributes.Frame = new RectangleF (new PointF (0, 0), attr.Size);
    label.Frame = new RectangleF (new PointF (0, 0), attr.Size);
  } else {
    newLayoutAttributes.Frame = new RectangleF (new PointF (0, 0), label.AttributedText.Size);
    label.Frame = new RectangleF (new PointF (0, 0), label.AttributedText.Size);
  return newLayoutAttributes;

This allows fine-grained control at the cell level, as shown below:

layout attributes

As you can see, iOS 8 adds flexibility to Collection Views, allowing granular control of cells directly from the cell class and making it easier to control cell layout and sizing when needed.

The code from this post is available here.

Discuss this blog post in the Xamarin Forums

July 15, 2014 4:21 GMT

Mobile .NET Meetups and Xamarin 3 Celebrations in July

We’ve had some amazing Xamarin 3 celebrations over the last few months, but we aren’t done just yet. This month, Mobile .NET developer groups around the world are joining in to celebrate the latest Xamarin release with pizza, cake, and in-depth sessions on all of the new features in Xamarin 3. We have also launched a brand new Twitter account, @XamarinEvents, which will regularly tweet about upcoming Xamarin and community events.

Xamarin Cake

Here are some upcoming Xamarin developer group meetups:

Nashville Xamarin User Group us

  • Nashville, TN: Tuesday, July 15th 6:30PM

  • Xamarin.Forms Demo & Lab

Austin Mobile .NET Developers Group us

  • Austin, TX: Wednesday, July 16th 6:30PM
  • Cross Platform Development with Portable Class Libraries

Portland Area .NET Users Group in

  • Portland, OR: Thursday, July 17th 6:00PM
  • Creating UIs for Cross-Platform Apps with Xamarin, with Xamarin’s James Montemagno

Los Angeles Mobile .NET Developers Group in

  • Los Angeles, CA: Monday, July 21st 7:00PM
  • Xamarin Basics

Israel .NET Developer Group il

  • Tel Aviv, Israel: Tuesday, July 22nd 5:30PM
  • Building Cross Platform Apps with Xamarin

Minnesota Enterprise Mobile in

  • Wayzata, MN: Tuesday, July 22nd 5:30PM
  • Building iOS User Interfaces with Xamarin

Northwest Valley .NET User Group in

  • Glendale, AZ: Wednesday, July 23rd 6:00PM
  • Building iOS, Android, and Windows Apps in C# with Xamarin, with Xamarin’s James Montemagno

Boston Mobile C# Developers Group us

  • Cambridge, MA: Thursday, July 24th 6:00PM
  • Introduction to Xamarin.Forms, with Xamarin’s Pierce Boggan

Arizona – Xamarin us

  • Scottsdale, AZ: Thursday, July 24th 6:00PM
  • Xamarin 3! iOS and Android Development in C# with Xamarin

Chicago .NET Mobile Developers us

  • Chicago, IL: Thursday, July 31st 5:45PM

  • Introduction to the MVVMCross Cross Platform Framework

Xamarin events are always happening around the world, so if you don’t see your city listed above, be sure to also check out the Xamarin Events forum where new meetups are being added all the time. Additionally, don’t forget to follow our brand new @XamarinEvents Twitter account to make sure you never miss an upcoming Xamarin event.

Don’t see a developer group in your area and want to get one started? We’re here to help! We have a tips and tricks guide on starting a developer group, our introduction to Xamarin slide deck, and of course our community sponsorship program to get you on your way. We also want to hear from you, so please feel free to send us an email or tweet @XamarinHQ so we can help spread the word and continue to grow the Xamarin community.

July 14, 2014 4:10 GMT

Core Motion in iOS 8 and Xamarin

Core Motion is having an update with the introduction of iOS 8 and we get several new classes to play with.


The first of these being CMPedometer, this looks to take the place of CMStepCounter which came about with iOS 7. What do we get over and above the old step counter? Here is the new data broken down:

  • Number of steps
  • Distance travelled
  • Speed (Based on calculating from distance over time)
  • Floors ascended (Requires information about the building to be available)
  • Floors descended (Requires information about the building to be available)

The implementation of this is really simple and looks a little like this:

public override async void ViewDidLoad ()
   base.ViewDidLoad ();

   this.pedometer = new CMPedometer ();
   this.pedometer.StartPedometerUpdates (new NSDate (), this.UpdatePedometerData);

   var data  = await this.pedometer.QueryPedometerDataAsync (DateTime.SpecifyKind (DateTime.Now.AddHours(-24), DateTimeKind.Utc), DateTime.Now);
   this.UpdatePedometerData(data, null);

private void UpdatePedometerData(CMPedometerData data, NSError error)
   if (error == null) {
      this.InvokeOnMainThread (() => {
         this.StepsLabel.Text = string.Format ("You have taken {0:0.00} steps", data.NumberOfSteps);
         this.DistanceLabel.Text = string.Format ("You have travelled {0:0.00} meters", data.Distance.DoubleValue);
         var endTime = DateTime.SpecifyKind(data.EndDate, DateTimeKind.Utc);
         var startTime = DateTime.SpecifyKind(data.StartDate , DateTimeKind.Utc);
         var time = endTime.Subtract(startTime);
         var speed = data.Distance.DoubleValue / time.TotalSeconds;
         this.SpeedLabel.Text = string.Format ("Your speed was {0:0.00} meters a second", speed);
         this.FloorsAscendedLabel.Text = string.Format("You have ascended {0} floors", data.FloorsAscended);
         this.FloorsDescendedLabel.Text = string.Format("You have descended {0} floors", data.FloorsDescended);


The second class brand new to iOS 8 is CMAltimeter which seems to point to the new hardware to be made available with the next iteration of the iPhone / iPad. The main function here is to get the relative altitude of the device but this is currently not supported on any available hardware.

Here is a look at the implementation though as it stands:

public override void ViewDidLoad ()
   base.ViewDidLoad ();
   if (CMAltimeter.IsRelativeAltitudeAvailable) {
      this.altimeter = new CMAltimeter ();
      this.altimeter.StartRelativeAltitudeUpdates (NSOperationQueue.MainQueue, this.UpdateAltitudeData);
   } else {
      this.AltitudeLabel.Text = "Your device does not have required hardware for altitude..";

private void UpdateAltitudeData(CMAltitudeData data, NSError error)
   this.InvokeOnMainThread (() => {
      this.AltitudeLabel.Text = string.Format ("Your relative altitude is {0}", data.RelativeAltitude);

I think just based on these 2 new classes we can tell the context is going to be huge moving forward, whether you think it is an invasion of privacy or an innovation that your mobile device knows how many flights of stair you have claimed that day is a question that only you can answer. All i can say is that as app developers we have lots of options moving forward.

Get the source over at GitHub.

July 11, 2014 7:45 GMT

Exploring HealthKit With Xamarin: Provisioning and Permissions Illustrated Walkthrough

One of the more interesting frameworks in iOS 8 is Health Kit, system-wide persistent storage for health-related information. I’m just beginning to explore the namespace myself, but thought I’d walk through the steps you need to manipulate Health Kit with Xamarin.

Because health-related information is so sensitive, developing for Health Kit requires:

  1. The app be developed using an “Explicit App ID” with Health Kit Services explicitly enabled (see below);
  2. The Entitlements.plist must have a com.apple.developer.healthkit key set to true; and
  3. At initial runtime, the user must grant access via a detailed permissions dialog

Additionally, it’s worth emphasizing the importance of checking error codes in Health Kit API function calls. If a user does not grant permission or if for any other reason the app makes a call to a non-permitted API, this does not raise an exception. Rather, a null or otherwise empty result will be returned and typically an out NSError or closure-parameter will be set.

Provisioning and Permissions

Xamarin has a great article on device provisioning, but just to hit the highlights for Health Kit:

You need to set an “Explicit App ID” and explicitly enable “Health Kit” as an app service. Here, I’m created an ID for an app whose ID is “{PREFIX}.com.xamarin.HKWork”:


Screen Shot 2014-07-11 at 7.51.14 AM

After you do that, you’ll have to create a new provisioning profile for this App ID:

Screen Shot 2014-07-11 at 7.59.17 AM

Once you’ve awaited the generation of the profile, download it and double-click to install it on your development system:

Screen Shot 2014-07-11 at 8.05.17 AM

Now, in your Xamarin Studio project, open your Info.plist and set the Bundle Identifier to your explicit App ID (without the team prefix):

Screen Shot 2014-07-11 at 8.56.35 AM

And set your project’s Bundle Signing options so that you are using your new provisioning profile:

Screen Shot 2014-07-11 at 8.14.07 AM

(Now that I’ve written that, I suspect that you can probably leave it as “Automatic”, since the App ID is explicitly the same as that in the custom provisioning profile: that’s how the two are matched by the system. But still, I’m going to leave the step just to be clear what’s happening. And I don’t think there’s any harm in setting the provisioning profile explicitly.)

You’ve taken care of Info.plist, so now open Entitlements.plist. (Some project templates don’t automatically generate an Entitlements.plist file. If your project doesn’t have one, use File/New File…/iOS and choose Entitlements.plist.) Click on “Source” and add a new key com.apple.developer.HealthKit of type Boolean with a value of Yes (== true):

Screen Shot 2014-07-11 at 9.14.53 AM

Write code to request permission from the app user

To use Health Kit, the user must grant your app access. This involves these API calls:

var temperatureKey = HKQuantityTypeIdentifierKey.BodyTemperature;
var tempQuantityType = HKObjectType.GetQuantityType (temperatureKey);

var hks = new HKHealthStore ();
hks.RequestAuthorizationToShare (new NSSet (new [] { tempQuantityType }), new NSSet (), (success, error) => {
	Console.WriteLine ("Authorized:" + success);
	if (error != null) {
		Console.WriteLine ("Authorization error: " + error);

Here, we are requesting authorization to share body temperature data (i.e., “share data generated by my app with the HealthStore database”). When this app is run, the user will be presented with the Health Kit permissions dialog, which will give the user fine-grained control over the requested types of data you’ll share. In this case, for instance, the dialog inside the Health app looks like this:


Write a brilliant app

I have no insight into how to do that.

… that has some health-related information

Oh good, I can help with that.

Creating and storing data in the shared HealthKit store involves these API calls:

var temperatureKey = HKQuantityTypeIdentifierKey.BodyTemperature;
var tempQuantityType = HKObjectType.GetQuantityType (temperatureKey);
var myCurrentTemp = HKQuantity.FromQuantity (HKUnit.DegreeFahrenheit, 98.6);
var meta = NSDictionary.FromObjectAndKey (new NSNumber (4), HKMetadataKey.BodyTemperatureSensorLocation);
var tempSample = HKQuantitySample.FromType (tempQuantityType, myCurrentTemp, new NSDate (), new NSDate (), meta);

hks.SaveObject(tempSample, (success, error) => {
	Console.WriteLine("Write succeeded: " + success);
	if(error != null)

I trust it’s obvious that the types of data you attempt to store must match those you’ve requested permission from the end-user and that your error-handling should be considerably more sophisticated (since it’s incredibly possible that app users are going to be very cautious about allowing access to their medical data, even if it’s clearly central to the app’s value).

The resulting shared data (assuming that permissions are granted) looks like this in the Health app:


Notice that although I created the data using Fahrenheit, in this case it’s being displayed as Celsius (which I imagine is the opposite of the likely use-case!). Units of measure and conversions are built in to Health Kit, which I’ll cover in a later post. For now, though: Happy Healthing!

July 11, 2014 6:04 GMT

My Xamarin Studio F# Wishlist

I am writing a large iOS and OS X app in F# and am totally digging the honeymoon phase. Not only is F# a crazy powerful language, but it has a great interactive code executer built right into the IDE. In all, it’s a wonderful development experience.

(If you haven’t seen it, check out my hastily recorded Interactive F# Development in Xamarin Studio video.)

While F# in Xamarin Studio is great, it does lack a few features I miss from the C# experience. These include:

Sorted Intellisense. If you didn’t know, you can hold the Shift key while upping and downing through the Intellisense to switch to an inheritance sorted list of members. This is not only useful, but critical to exploring new objects and APIs. It also lets you filter out all the junk that comes with base classes (I’m looking at you NSObject). I miss this feature so, so much (imagine creepy Anakin Skywalker saying that).

Expand Selection using the AST. Another important but often missed feature of Xamarin Studio’s editor is the ability to expand your selection based on the language’s syntax tree. If you have the text “fo|o + bar”, then expand the selection, you get “[foo] + bar”. Expand again, and you get “[foo + bar]”. This is an amazing keyboard shortcut that services quick identifier selection, expression selection, method selection, and more.

Rename Refactoring. You know, you don’t think of it much, but when someone takes away your rename refactoring, you all of a sudden are back in the 1990’s coding in Turbo Pascal with your crappy IBM PS/2 debating whether code clarity is worth the trouble…

Thanks to Don Syme for setting me straight: Xamarin Studio supports Rename and it works great (even across projects). I’m going to meditate a bit on how it’s possible to be completely blind to a feature.

Search for Definition. MonoDevelop used to have a great tool for jumping to any definition in your code. Just hit Cmd + . and you get a great search window. Xamarin Studio screwed this up a bit by putting the window in your peripheral vision and limiting the results to just a few items with not enough info to distinguish them. But I digress. Even in its not-very-useful state, I still wish I could search for and jump to definitions in F# code more easily.

NUnit IDE Integration. Xamarin Studio has shortcut “test bubbles” in C# code when using NUnit. These bubbles are right in the editor with the code so it makes running and debugging tests a two click task. While F# of course supports NUnit testing, the editor doesn’t care. Too bad.

And then the crashing. Hey, it sucks to be on the frontier, software sometimes breaks and needs time to be refined. I just wish I could go more than 5 minutes without Intellisense crashing or more than 15 minutes without Xamarin Studio crashing. Coding F# with functioning Intellisense would be so groovy…

What’s the good news? The Xamarin Studio F# integration is open source! That means I should “put up or shut up”. I have a small amount of experience writing XS addins and a small amount of experience coding F# - I figure this qualifies me to at least send a pull request. Wish me luck!

July 11, 2014 3:00 GMT

Xamarin on Film: @dotnetConf & FlashCast

Earlier this year, Xamarin invaded Channel 9′s Visual Studio Toolbox and Dev Radio shows. Response to all 6 shows has been amazing, with over 325,000 views so far! Now, we’re back again with even more great videos for your weekend enjoyment.


Microsoft hosted their second dotnetConf, a free online conference, in June, and Xamarin was there in full force. I’ve included my talk Developing Native iOS, Android, and Windows Apps with Xamarin below, which you can find, with all of the great .NET related videos from this year’s conference, on Channel 9.

FlashCast is a brand new web series offering unique, 15-minute webinars on awesome topics. Evangelist Mike Bluestein kicked off the very first FlashCast with Build your first iOS App with Visual Studio and Xamarin, included below:

Our next entry in the FlashCast series was on how to Build your first Android app with Visual Studio and Xamarin:

Stay tuned over the next few weeks for even more new FlashCast episodes featuring Xamarin!

July 11, 2014 4:25 GMT

Adding Touch ID Authentication in iOS 8

It has now become very easy to ensure the person using your app is the owner of the iOS device it is running on. To add this takes only a few lines of code.


partial void LoginPressed (UIButton sender)
   var context = new LAContext ();

   var error = new NSError ();
   if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error)) {
      var replyHandler = new LAContextReplyHandler((success, err) => {
         this.InvokeOnMainThread(() => {
               Console.WriteLine("You Logged in");
            } else {
               var errorAlertView = new UIAlertView("Login Error", err.LocalizedDescription, null, "Close");
      context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "You need to login", replyHandler);

That’s all there is to it! The power and security of fingerprint authentication all wrapped up in a simple API.

you can grab the same project here

July 11, 2014 3:11 GMT

What's new in ReactiveUI 6: ReactiveCommand<T>

One of the largest breaking changes in ReactiveUI 6.0 is the new ReactiveCommand. Since this change is the most likely one to mess with your existing code, I wanted to make sure to get the blog post about it as soon as possible.

What was wrong with the old ReactiveCommand?

There are a few parts of the existing ReactiveCommand design that made certain scenarios particularly difficult to deal with. The original scenario that motivated this rewrite was the following (simplified for effect):

"In GitHub for Windows, the Sync Command is an invocation of the Pull Command followed by the Push Command - how can I create a Command whose CanExecute turns off until the Pull then the Push completes?"

The only one who received the completion that the background method for Pull and Push completed was the person who set it up (i.e. the one who called RegisterAsyncXYZ). Other callers had to do something really hacky:

someCommand.IsExecuting.Where(x => x == false).Skip(1).Take(1);  

The even more common scenario was, "Write a test that invokes a Command with a background method, then wait for the result".

With the new ReactiveCommand and the ExecuteAsync method, the GitHub for Windows scenario becomes very easy:

var canSync = Observable.CombineLatest(  
    Push.CanExecuteObservable, Pull.CanExecuteObservable,
    (pl,pu) => pl && pu);

Sync = ReactiveCommand.CreateAsyncTask(canSync, async _ => {  
    await Pull.ExecuteAsync();
    await Push.ExecuteAsync();

The test scenario similarly becomes much more straightforward:

var fixture = new CoolViewModel();  
var result = await fixture.ExecuteAsync();  

Creating ReactiveCommands

ReactiveCommand is now a Generic class - before, Subscribing to ReactiveCommand would give you the (relatively useless, Worst Practice) CommandParameter. Now, Subscribing to ReactiveCommand gives you the result of your background method after it finishes.

To facilitate this, the correct way to create ReactiveCommands is now via a static ReactiveCommand.CreateXYZ family of methods. Create lets you provide both the canExecute as well as providing the method you used to provide to RegisterAsync.

Dual-Mode Zen Nature: ExecuteAsync vs. Subscribe

ReactiveCommand now has two complimentary ways to get the result of your background method:

  • Subscribing to the Command itself gives you a stream of all results - this is very convenient to connect to a property on the ViewModel via ToProperty

  • ExecuteAsync returns a single invocation of the background method. This is useful for invoking a Command as part of a larger workflow, or for testing the background method of a Command. Both the awaiter and any Subscribers to the Command will receive the results.

Some Before => Afters


// Create a simple command
var someCmd = new ReactiveCommand();  
someCmd.Subscribe(_ => Console.WriteLine("Cool it was invoked!"));

// Create an async command
var asyncCmd = new ReactiveCommand(myCanExecute);

asyncCmd.RegisterAsyncTask(x => doAThingAsync())  
    .ToProperty(this, x => x.OutputText, out outputText);


// Create a simple command
var someCmd = ReactiveCommand.Create();  
someCmd.Subscribe(_ => Console.WriteLine("Cool it was invoked!"));

// Create an async command
var asyncCmd = ReactiveCommand.CreateAsyncTask(myCanExecute, x => doAThingAsync());

asyncCmd.ToProperty(this, x => x.OutputText, out outputText);  
July 10, 2014 10:59 GMT

Welcome to ReactiveUI 6.0

After 8 months of work, 878 commits, and 1032 files changed, ReactiveUI 6.0 is finally released, the biggest RxUI release ever! A huge thanks to our contributers for this release:

  • Johan Laanstra
  • Oren Novotny
  • Todd Berman
  • Michael Teper
  • Felipe Lessa
  • Amy Palamountain
  • Dennis Daume
  • Rik Bosch
  • James Nugent
  • Phil Haack
  • Maratoss
  • David Lechner
  • Justin Manus
  • Keith Dahlby
  • Markus Olsson

In particular, a huge thanks goes to Johan, who has done an enormous amount of great work on this release. Thank you so much!

Migrating from existing code

We've written a migration guide to help existing application authors migrate their 5.x applications to ReactiveUI 6.0. Check out this document before updating your dependencies to get a heads-up as to what you're in for.

What's New in ReactiveUI 6.0

Over 120 new features were merged into ReactiveUI 6.0, trying to sum them all up is a huge undertaking! Here are some of the highlights:

Universal Windows Phone app and Xamarin Forms Support

ReactiveUI 6.0 has great support for all of the latest developer platforms, including WinRT Universal Apps as well as support for the new Xamarin Forms UI toolkit via the new ReactiveUI-XamForms NuGet package. Use either the updated Portable Library support, or use the new Shared Projects tooling in Visual Studio.

Existing support for Android and iOS has also been greatly improved, including support for unit test runners on those platforms, as well as creating Observable abstractions for all events via the ReactiveUI-Events package. Helpers for the Android Support Library are now also provided, via the ReactiveUI-AndroidSupport package.

ReactiveUI 6.0 supports the following platforms (In order of personal developer joy):

  • Xamarin.Android
  • Xamarin.iOS
  • Xamarin.Mac
  • Xamarin Forms (iOS + Android + WP8)
  • .NET 4.5 (WPF and Windows Forms, via ReactiveUI-WinForms)
  • Universal Windows Apps (WPA81)
  • Windows Phone 8.0 Apps (Silverlight-based)
  • Windows Store Apps (WinRT)

ReactiveUI makes creating list-based views a snap

We've added great support for recycling list-based views on iOS and Android (UICollectionView and UITableView on iOS, ListAdapter on Android). These new adapter classes allow you to map a ReactiveList of ViewModel objects and automatically create and recycle the associated views, for high-performance lists without writing a ton of boilerplate code.

On iOS, added and removed items will even be automatically animated in and out. On Android, we help you easily implement the ViewHolder pattern to limit the amount of work done while scrolling.

Large Application Performance

One of the focuses of this release has been performance and memory usage in large applications. ReactiveUI 6.0 is much less prone to creating memory leaks in application code via WeakEventManager, as well as more performant by eliminating scheduling latency as much as possible. Other features, such as View and ViewModel Activation, allow you to create and clean-up objects only when the View is actually visible on-screen, saving a lot of unnecessary work.

While some of these changes will require you to update your application and unit tests, the end result is an application that uses less memory and feels more responsive.

The same Rx, Everywhere

ReactiveUI 5.x used a separate installation of the Reactive Extensions for .NET for Xamarin projects, which made creating proper Portable Libraries more difficult. RxUI 6.0 now resolves this completely, and you can now build ViewModels that work on every supported platform.

Questions, Comments, Concerns?

There are three great venues for problems / questions related to this release:

July 10, 2014 4:32 GMT

The Protocol Pattern

In C# (and F#), one can define extension methods on interfaces. These extension methods can have implementations, which can be used as default implementations for implementors of the extension. I haven’t heard a name for this technique.


interface IFoo


static class IFoo_Extensions 
	public static void Foo(this IFoo self) { Console.WriteLine("Foo"); }

class ImplementingClass : IFoo


class MainClass
	public static void Main (string[] args)
		var aFoo = new ImplementingClass ();
		aFoo.Foo (); //Prints "Foo" from extension default implementation


Xamarin uses this pattern extensively when binding Objective-C Protocols, which are essentially interfaces with optional methods. For instance, if you have an interface where some methods must be implemented by the library user but some aren’t, you can do this:

interface IFoo
	//Methods defined here, as always, must be implemented
	void Necessary ();

static class IFoo_Extensions
	//"Optional" methods defined here with default implementations
	public static void Optional (this IFoo self)

class ImplementingClass : IFoo
	public void Necessary ()
		Console.WriteLine ("Necessary");

//    public void Optional()
//    {
//        Console.WriteLine("Overridden");
//    }


Obviously, it’s not exactly the same to have a default implementation defined in an extension method as it is to have an optional method that simply does not exist. But conceptually it’s close enough that I’ve started referring to this technique as the “Protocol Pattern.”


July 05, 2014 11:13 GMT

Port of Floating Action Button

Android L has introduced something called a Floating Action Button (FAB), which is basically a circle overlayed on top your application. This FAB can be clicked to do an action. In the Google+ application this is used to persistently allow the user to create a new post.

It basically looks like in the screenshot above, where you can see a circle with a play icon at the bottom of the screen. Faiz Malkani backported this from Android L to work on JellyBean and KitKat, and I took the liberty to port it to Xamarin.Android.

You can find the repository on GitHub along with a sample application, which the screenshot above is from.
July 03, 2014 6:19 GMT

Local Notifications in iOS 8 With Xamarin

As of iOS 8, the user has to provide explicit permission for apps to respond to local notifications. This means that now, the first time the program is run, you need to run code such as:

    ||| UIUserNotificationType.Badge 
    ||| UIUserNotificationType.Sound, 
    new NSSet())
|> UIApplication.SharedApplication.RegisterUserNotificationSettings


var settings = UIUserNotificationSettings.GetSettingsForTypes(
    || UIUserNotificationType.Badge 
    || UIUserNotificationType.Sound, 
    new NSSet());

Which will present a user dialog. When they complete that dialog, the system will call the UIAppDelegate.DidRegisterUserNotificationSettings method. You can check the status using UIApplication.CurrentUserNotificationSettings.

If you try to send a notification without these settings being allowed, you will get a runtime error of the form:

Attempting to schedule a local notification {...} with an alert but haven't received permission from the user to display alerts
Attempting to schedule a local notification {...} with a sound but haven't received permission from the user to play sounds
Attempting to schedule a local notification {...} with a badge number but haven't received permission from the user to badge the application
July 03, 2014 1:21 GMT

Screen Mirroring for iOS, Android, and Windows Phone

It is unfortunate that we don’t live in a world where we can use an iOS, Android, and Windows Phone emulators/simulators at the same time. Nested virtualization really messes things up and even if that worked the arm emulators for Android are a nightmare. Even on the PC side where I can use the wonderful x86 emulator (read my blog post on setup) for Android, you have to turn off hyper-v to get things to work, and of course there is no iOS simulator over there. So what is one to do? I have to use real devices and rely on screen mirroring to pull them simultaneous views of all of our devices for that WOW effect. Here are my recommended tools to get you going:

iOS Screen Mirroring

On the iOS side of things it is really simple as my hat goes off to AirSquirrels for their amazing app called Reflector. Using the power of AirPlay built into every iOS device you are easily able to stream your screen over WiFi to your PC or Mac. They didn’t stop there though as you can also do full screen recordings of your device and pick what device frame you want to use as well. The only downside is that you will need to fork over $13 for their software… twice if you want it on PC and Mac, but it is well worth it. The best part is nothing needs to be installed on your phone at all.

iOS Mirroring Alternatives
Reflector isn’t the only one out there as other have tapped into the AirPlay screen mirroring including AirServer and X-Mirage.

Since all of these apps are based on AirPlay you will need to ensure the WiFi network allows AirPlay. This sometimes is an issue on public WiFi networks so I often have my own hotspot for this. Additionally, I have not gotten it to work inside of a PC VM on the mac, so I mirror directly to the Mac and that works great.

Android Screen Mirroring

I wrote about Android screen mirroring in the past and my opinion still hasn’t changed, as Mobizen is by far the best screen mirroring application out there. You install their app from Google Play and then install an app on your PC and you are good to go with screen mirroring over USB, which is great. They recently went through a big transition of introducing a horrible web version of the app, but have now merged them together.

Android Mirroring Alternatives
Mobizen offers a nice 1 to 1 mirroring, which is why I love it. However, it is only available on PC currently. So if you need to mirror on your Mac you will need a different option. Droid@Screen actually works pretty good. It is based on screen shots and usually runs at a low frame rate, but it gets the job done. In addition to that Google announced that you will be able to mirror your Android device to your Chromecast, but that does us little good if we want it on our Mac/PC.

Mobizen requires about every permission under the sun so be aware of that. I haven’t had any real issues with that though as I run it on my developer devices. All apps are running things via ADB from my best knowledge so that might be a bit tricky and sometimes I reboot VS to get things going, but that isn’t too bad.

Windows Phone

With Windows Phone 8.1 it couldn’t be easier to screen mirror to your Windows PC as it is built right into the phone! All you need to do is install the “Project My Screen" app on your PC and you are good to go. As soon as you launch the app your Phone which is plugged in via USB will prompt you to mirror the screen.

There you have it screen mirroring for iOS, Android, and Windows Phone. Here is a demo:

July 02, 2014 10:59 GMT

F# For Scripting

It’s F# Week at Xamarin. Also, in the US, it’s only a 4-day work-week. F# saves 20% of your time. QED.

Anyway, I don’t have any actually interesting F# to share, but I recommend:

But what I thought I could quickly contribute is that:

  • F# is an awesome scripting language; and
  • Scripting may be the best way to learn F#

Scripting tasks often involve transforming a stream of text by repeatedly Filtering, Assigning, Reducing, Transforming, and Slicing it (“a sequence of FARTS“) and this is an area where the functional approach is pretty clearly easier to work with than the OOP approach of a network of cooperating objects.

And since scripting tasks are often private or semi-private low-complexity chores, they’re an excellent domain for regularly exercising your knowledge of a new language. It’s all well and good to carve out a couple weekends and work through a book but nothing beats regular exposure.

(While I’m on the subject, these are currently my favorite F# books. Initial exploration:

Deeper dives:


F# scripts are F# files with the .fsx extension. On OS X with mono, they can be run with fsharpi script.fsx or:

#if run_with_bin_sh
  exec fsharpi --exec $0 $*
printfn "%A" fsi.CommandLineArgs

To add references, use #r:

#if run_with_bin_sh
  exec fsharpi --exec $0 $*

#r "System.Core.dll"
#r "System.Xml"

open System
open System.Xml.Linq
open System.IO


I’ve been using F# for scripting for more than a year now and I can honestly say that it’s displaced Ruby as my scripting language of choice.

Give it a shot!

July 01, 2014 4:56 GMT

Xamarin Getting Started Sampler

There are many great resources for learning Xamarin, ranging from docs, samples and videos, to full-blown training via Xamarin University. If you’re just getting started, here are a list of resources to get you off to a good start. There are many other articles and samples as well in the Xamarin Developer Center, so it really depends upon your interests, but these are good fundamental topics in any case:




Also see:

And check out the recipes, samples and videos sections as well:

July 01, 2014 3:00 GMT

End to End Mvvm with Xamarin

As a Xamarin University instructor, I am occassionally asked how I would put together a typical MVVM based app while connecting to a remote service. This is not the only way to architect our apps, and may not be the best for your app. Your mileage may vary.

Our goal is to connect to a remote service api, download the data, convert into a model that we control, and bind it to our ui. We'll connect to a remote service to download technical conference information, and we'll utilize a handful of useful open source .net libraries to speed things along and make our code cleaner.

We'll be using Xamarin Studio 5 (although Visual Studio will work just fine), and we'll use Xamarin.Forms for our user interface. All of the code is available from my Github Repo

Create Solution

Start by creating a new solution. We'll be using the "Blank App (Xamarin.Forms Portable)" template under the "Mobile Apps" node. I prefer PCLs over Shared Projects, but that's just me. Shared Projects will work also. I'll name the solution "DtoToVm" This template will create a core Portable Class Library as well as an Android and an iOS project (and a Windows Phone app if you're using Visual Studio on Windows). We'll be putting almost all of our code in the shared PCL.

File -> New Solution -> Blank App (Xamarin.Forms Portable)

Remote Third Party API (JSON)

Let's take a look at the api that we'll be working with. For this example, I'll be using api.tekconf.com/v1/conferences an open source conference management system (written by me). When performing a GET request on the conferences uri, we're given a list of all of the active conferences in the system.

    slug: "codestock-2014",
    name: "CodeStock 2014",
    start: "/Date(1405036800000)/",
    end: "/Date(1405123200000)/",
    callForSpeakersOpens: "/Date(1391619909000)/",
    callForSpeakersCloses: "/Date(1391619909000)/",
    registrationOpens: "/Date(1391619909000)/",
    registrationCloses: "/Date(1405036800000)/",
    description: "CodeStock is a two day event (July 11th & July 12th of 2014) for technology and information exchange. Created by the community, for the community – this is not an industry trade show pushing the latest in marketing as technology, but a gathering of working professionals sharing knowledge and experience. Join us at CodeStock 2014 and move into the future.",
    lastUpdated: "/Date(1392149694455)/",
    address: {
      streetNumber: 0,
      city: "Knoxville",
      state: "TN",
      postalArea: "US"
    imageUrl: "http://tekconf.blob.core.windows.net/images/conferences/codestock-2014.png",
    imageUrlSquare: "http://tekconf.blob.core.windows.net/images/conferences/codestock-2014-square.jpg",
    isLive: true,
    homepageUrl: "http://www.codestock.org/",
    position: [
    defaultTalkLength: 60,
    rooms: [ ],
    sessionTypes: [ ],
    subjects: [ ],
    tags: [ ],
    sessions: [ ],
    numberOfSessions: 0,
    isAddedToSchedule: false,
    isOnline: false,
    dateRange: "July 11 - 12, 2014",
    formattedAddress: "Knoxville, TN"

Service Client

In order to connect to this service, we'll use Microsoft's HttpClient library. This is a cross platform nuget package that works well with PCLs and provides a nice async interface for accessing remote web endpoints. TekConf may not be the only service that we connect to though, so we'll wrap the access to the site in a client. This segregates the TekConf service to a small corner of our apps and allows the app code to focus on the app.

Add Class to PCL -> Services/TekConfClient.cs

namespace DtoToVM.Services  
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using AutoMapper;
    using Newtonsoft.Json;
    using DtoToVM.Dtos;
    using DtoToVM.Models;

    public class TekConfClient
        public async Task<List<Conference>> GetConferences ()
            IEnumerable<ConferenceDto> conferenceDtos = Enumerable.Empty<ConferenceDto>();
            IEnumerable<Conference> conferences = Enumerable.Empty<Conference> ();

            using (var httpClient = CreateClient ()) {
                var response = await httpClient.GetAsync ("conferences").ConfigureAwait(false);
                if (response.IsSuccessStatusCode) {
                    var json = await response.Content.ReadAsStringAsync ().ConfigureAwait(false);
                    if (!string.IsNullOrWhiteSpace (json)) {
                        conferenceDtos = await Task.Run (() => 

                        conferences = await Task.Run(() => 
                            Mapper.Map<IEnumerable<Conference>> (conferenceDtos)

            return conferences.ToList();

        private const string ApiBaseAddress = "http://api.tekconf.com/v1/";
        private HttpClient CreateClient ()
            var httpClient = new HttpClient 
                BaseAddress = new Uri(ApiBaseAddress)

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return httpClient;

Data Transfer Object (DTO)

Notice that we're introducing two new classes here, the DTO and the Model. We're creating a DTO so that we can deserialize the JSON string from the api into strongly typed C# objects. We'll use the Newtonsoft JSON.net nuget package for the deserialization. This DTO will match the remote json, and therefore be in the format and naming dictated by the remote, possibly third party service.

Add Class to PCL -> Dtos/ConferenceDto.cs

namespace DtoToVM.Dtos  
    using System;
    public class ConferenceDto
        public string Slug { get; set; }
        public string Name { get; set; }
        public DateTime Start { get; set; }
        public double[] Position { get; set; }


The model class will be in the shape and structure that we want to deal with in our app. The DTO and the model very likely will be different. In our case, the DTO has an array of doubles named position to hold the geographic location of the conference, while our Conference model has two individual properties named Latitude and Longitude, which will be easier to store in our local SQLite database.

Add Class to PCL -> Models/Conference.cs

namespace DtoToVM.Models  
    using System;
    using SQLite.Net.Attributes;
    public class Conference
        [PrimaryKey, AutoIncrement, Column ("_id")]
        public int Id { get; set; }
        public string Slug { get; set; }
        public string Name { get; set; }
        public DateTime Start { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }

Map DTO to Model

To convert from the externally defined DTO to our model, we'll use AutoMapper, which provides us an easy way to map two different objects and copy the data from one to another.

Add Class to PCL -> Bootstrapper.cs

namespace DtoToVM  
    using AutoMapper;
    using DtoToVM.Dtos;
    using DtoToVM.Models;

    public class Bootstrapper
        public void Automapper()
            Mapper.CreateMap<ConferenceDto, Conference> ()
                .ForMember(dest => dest.Latitude, opt => opt.ResolveUsing<LatitudeResolver>())
                .ForMember(dest => dest.Longitude, opt => opt.ResolveUsing<LongitudeResolver>());

    public class LatitudeResolver : ValueResolver<ConferenceDto, double>
        protected override double ResolveCore(ConferenceDto source)
            return source.Position[0];

    public class LongitudeResolver : ValueResolver<ConferenceDto, double>
        protected override double ResolveCore(ConferenceDto source)
            return source.Position[1];

View Model

At this point, we're downloading the conference data from the remote site, and transforming it into our C# model. Next, we want to create some user interface to display that data. Xamarin.Forms shines for an app like this, where we want the same UI across three platforms, and we're not going to be customizing the UI very much. In order to simplify databinding, we'll create a View Model class for the list of conferences. The View Model will implement the INotifyPropertyChanged interface to relay change events to our UI. We'll using Fody.PropertyChanged to implement the interface for us, removing the boilerplate code. See my previous post Fody.PropertyChanged + Xamarin Studio = Easy Mvvm for more information about this library.

The View Model will use the TekConfClient class to download the Conference information. It will then save the list of Conference models to a local SQLite database. Lastly, it will set the Conferences property, which our UI will bind to.

Add Class to PCL -> ViewModels/ConferencesViewModel.cs

namespace DtoToVM.ViewModels  
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using PropertyChanged;
    using DtoToVM.Data;
    using DtoToVM.Models;
    using DtoToVM.Services;

    public class ConferencesViewModel
        readonly SQLiteClient _db;

        public ConferencesViewModel ()
            _db = new SQLiteClient ();

        public List<Conference> Conferences { get; set; }

        public async Task GetConferences ()
            await GetLocalConferences ();
            await GetRemoteConferences ();
            await GetLocalConferences ();

        private async Task GetLocalConferences()
            var conferences = await _db.GetConferencesAsync ();
            this.Conferences = conferences.OrderBy(x => x.Name).ToList();

        private async Task GetRemoteConferences()
            var remoteClient = new TekConfClient ();
            var conferences = await remoteClient.GetConferences ().ConfigureAwait(false);
            await _db.SaveAll (conferences).ConfigureAwait(false);

Save to Database

Once we download the remote conference information, we'll cache it in a local SQLite database. By using the SQLite.Net PCL, the SQLite.Net Async PCL, and the SQLite Android and SQLite iOS libraries, we are able to easily save our Conference model to a local database. The SQLite PCL enables us to write almost all of our database code in our PCL and share it across all the different platforms that we're supporting. The one piece that is not shared though is the database connection. For that, we'll create an ISQLite interface, and we'll use Xamarin.Forms DependencyService to resolve the platform specific implementation of the SQLite connection.

Add Class to PCL -> Data/SQLiteClient.cs

namespace DtoToVM.Data  
    using SQLite.Net.Async;

    public interface ISQLite {
        SQLiteAsyncConnection GetConnection();

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using SQLite.Net.Async;
    using Xamarin.Forms;
    using DtoToVM.Data;
    using DtoToVM.Models;

    public class SQLiteClient
        private static readonly AsyncLock Mutex = new AsyncLock ();
        private readonly SQLiteAsyncConnection _connection;

        public SQLiteClient ()
            _connection = DependencyService.Get<ISQLite> ().GetConnection ();
            CreateDatabaseAsync ();

        public async Task CreateDatabaseAsync ()
            using (await Mutex.LockAsync ().ConfigureAwait (false)) {
                await _connection.CreateTableAsync<Conference> ().ConfigureAwait (false);

        public async Task<List<Conference>> GetConferencesAsync ()
            List<Conference> conferences = new List<Conference> ();
            using (await Mutex.LockAsync ().ConfigureAwait (false)) {
                conferences = await _connection.Table<Conference> ().ToListAsync ().ConfigureAwait (false);

            return conferences;

        public async Task Save (Conference conference)
            using (await Mutex.LockAsync ().ConfigureAwait (false)) {
                // Because our conference model is being mapped from the dto,
                // we need to check the database by name, not id
                var existingConference = await _connection.Table<Conference> ()
                        .Where (x => x.Slug == conference.Slug)
                        .FirstOrDefaultAsync ();

                if (existingConference == null) {
                    await _connection.InsertAsync (conference).ConfigureAwait (false);
                } else {
                    conference.Id = existingConference.Id;
                    await _connection.UpdateAsync (conference).ConfigureAwait (false);

        public async Task SaveAll (IEnumerable<Conference> conferences)
            foreach (var conference in conferences) {
                await Save (conference);

Note : Find the AsyncLock class on Scott Hanselman's Blog

SQLite Implementations

Add Class to iOS Project -> Data/SQLiteClient.cs

using Xamarin.Forms;  
using DtoToVM.iOS.Data;

[assembly: Dependency (typeof(SQLiteClient))]
namespace DtoToVM.iOS.Data  
    using System;
    using DtoToVM.Data;
    using SQLite.Net.Async;
    using System.IO;
    using SQLite.Net.Platform.XamarinIOS;
    using SQLite.Net;

    public class SQLiteClient : ISQLite
        public SQLiteAsyncConnection GetConnection ()
            var sqliteFilename = "Conferences.db3";
            var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
            var libraryPath = Path.Combine (documentsPath, "..", "Library");
            var path = Path.Combine (libraryPath, sqliteFilename);

            var platform = new SQLitePlatformIOS ();

            var connectionWithLock = new SQLiteConnectionWithLock (
                                          new SQLiteConnectionString (path, true));

            var connection = new SQLiteAsyncConnection (() => connectionWithLock);

            return connection;

Add Class to Android Project -> Data/SQLiteClient.cs

using Xamarin.Forms;  
using DtoToVM.Android.Data;

[assembly: Dependency (typeof(SQLiteClient))]
namespace DtoToVM.Android.Data  
    using System;
    using DtoToVM.Data;
    using SQLite.Net.Async;
    using System.IO;
    using SQLite.Net.Platform.XamarinAndroid;
    using SQLite.Net;

    public class SQLiteClient : ISQLite
        public SQLiteAsyncConnection GetConnection ()
            var sqliteFilename = "Conferences.db3";
            var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);

            var path = Path.Combine (documentsPath, sqliteFilename);

            var platform = new SQLitePlatformAndroid ();

            var connectionWithLock = new SQLiteConnectionWithLock (
                                         new SQLiteConnectionString (path, true));

            var connection = new SQLiteAsyncConnection (() => connectionWithLock);

            return connection;

Notice the use of

[assembly: Dependency (typeof(SQLiteClient))]

on each class. This will register the class in the DependencyService, and allow our PCL to resolve the dependency. Also note that on iOS, we are specifying the database path differently, so that the db3 database file is not backed up into iCloud.

Xamarin.Forms UI

The last part of the project is to create the user interface and wire everything up. We can use Xamarin.Forms to quickly create a cross platform UI and bind our list of conferences to a ListView control. Here, we'll create an instance of our ConferencesViewModel class, set the databinding to the ListView's cell template, and load the data. The key is setting the ListView's ItemsSource property to our ViewModel's Conferences property, which is implmenting the INotifyPropertyChanged events.

_conferencesListView.ItemsSource = viewModel.Conferences;  

Add Class to PCL -> Pages/ConferencesPage.cs

namespace DtoToVM.Pages  
    using System.Threading.Tasks;
    using Xamarin.Forms;
    using DtoToVM.ViewModels;

    public class ConferencesPage : ContentPage
        ListView _conferencesListView;

        public ConferencesPage ()
            this.Content = new Label { 
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                VerticalOptions = LayoutOptions.CenterAndExpand

            Init ();

        private async Task Init ()
            _conferencesListView = new ListView { 
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand,

            var cell = new DataTemplate (typeof(TextCell));
            cell.SetBinding (TextCell.TextProperty, "Name");
            cell.SetBinding (TextCell.DetailProperty, new Binding (path: "Start", stringFormat: "{0:MM/dd/yyyy}"));

            _conferencesListView.ItemTemplate = cell;

            var viewModel = new ConferencesViewModel ();
            await viewModel.GetConferences ();
            _conferencesListView.ItemsSource = viewModel.Conferences;

            this.Content = new StackLayout {
                VerticalOptions = LayoutOptions.FillAndExpand,
                Padding = new Thickness (
                    left: 0, 
                    right: 0, 
                    bottom: 0, 
                    top: Device.OnPlatform (iOS: 20, Android: 0, WinPhone: 0)),
                Children = { 

In just a few lines of code we were able to create a fully native app for three different platforms. We leveraged the wealth of fantastic open source PCL libraries available on Nuget to quickly connect to a remote service, download json data, convert it to a model for our app, and save it to a local database. We then wired everything up and bound the data to our UI.

This is not the only solution available to you, but it's my preferred approach and is just one of the reasons I find working with C# and Xamarin such a joy.

View the code on Github

July 01, 2014 1:57 GMT

iOS 8 Scene Kit sample in F#

Here’s an F# iOS 8 Scene Kit port of the C# code from the Xamarin blog, ported with some help from Larry O’Brien.

namespace FSHelloSceneKit
open System
open MonoTouch.UIKit
open MonoTouch.Foundation
open MonoTouch.SceneKit
type FSHelloSceneKitViewController () =
    inherit UIViewController()
    let CreateDiffuseLightNode (color: UIColor, position: SCNVector3, lightType: NSString): SCNNode = 
        new SCNLight ( Color = color, LightType = lightType )
        |> fun lightNode -> new SCNNode ( Light = lightNode, Position = position )
    override this.ViewDidLoad () =
        let scene = new SCNScene ()
        let view = new SCNView (this.View.Frame, Scene = scene, AutoresizingMask = UIViewAutoresizing.All, AllowsCameraControl = true)
        new SCNCamera (XFov = 40.0, YFov = 40.0)
        |> fun c -> new SCNNode (Camera = c, Position = new SCNVector3(0.0F, 0.0F, 40.0F))
        |> scene.RootNode.AddChildNode
        let material = new SCNMaterial ()
        material.Diffuse.Contents <- UIImage.FromFile ("monkey.png")
        material.Specular.Contents <- UIColor.White
        new SCNNode( Geometry = SCNSphere.Create(10.0F), Position = new SCNVector3(0.0F, 0.0F, 0.0F) )
        |> fun node -> node.Geometry.FirstMaterial <- material; node
        |> scene.RootNode.AddChildNode
        new SCNLight ( LightType = SCNLightType.Ambient, Color = UIColor.Purple)
        |> fun lightNode -> new SCNNode ( Light = lightNode )
        |> scene.RootNode.AddChildNode
            ( UIColor.Blue, new SCNVector3 (-40.0F, 40.0F, 60.0F) );
            ( UIColor.Yellow, new SCNVector3 (20.0F, 20.0F, -70.0F) );
            ( UIColor.Red, new SCNVector3 (20.0F, -20.0F, 40.0F) );
            ( UIColor.Green, new SCNVector3 (20.0F, -40.0F, 70.0F) )
        |> Seq.map (fun (color, pos) -> CreateDiffuseLightNode(color, pos, SCNLightType.Omni))
        |> Seq.iter scene.RootNode.AddChildNode

You can read more about Scene Kit on the Xamarin blog.

July 01, 2014 11:23 GMT

Xamarin.Forms and MvvmCross

As promised during the Xamarin 3 webinar, I have made a small sample showing how to use Xamarin.Forms along with MvvmCross.

What I did was look at the code Stuart Lodge already had made in another private repository, and adapted this to use it with Xamarin.Forms. What it basically does is implement custom Presenter implementations, which work with the way Xamarin.Forms navigates its Pages, which is through a NavigationPage and simple Push and Pop methods. This is wrapped in a PageNavigationProvider in MvvmCross which is in turn leveraged by the custom presenter.

Right now the sample has these presenters and MvvmCross specific classes built in, but will most likely in the future be pulled out and made into a plugin, which you can use in your own applications.

So the sample itself is a very simple application, which allows you to search TMDB for movies, it then fetches similar movies based on your search query and displays them. In turn you can then press an item in the list presenting the search results and get detailed information about the movie.

The sample actually covers a lot of MvvmCross by using:

  • ViewModels
  • Services
  • Custom Presenters
  • Bindings
  • Commands
  • Converters
  • Nuget
You can get the sample on Github
July 01, 2014 9:09 GMT

Shallow: Cloning a Hook-up App in F#

If you're looking to pass superficial judgement on hot nerds in F# t-shirts, you've come to the right place.

F# is a functional programming language designed with an emphasis on data science, that can also be used to build native iOS and Android apps with Xamarin. In my experience, when people discuss F#, someone inevitably asks “F# is great for analysis, but is it good for creating user interfaces?” I created a simple Tinder clone for iOS to show that F# is actually awesome for creating UIs, and for building apps in general.

Another ‘sharp’ language?

F# is heavily inspired by OCaml, a functional language known for its pragmatic blend of functional features with a familiar object model. This inherited design decision is still bearing fruit, as F# makes it possible to build iOS and Android apps using object-oriented APIs like UIKit, while incorporating incredibly useful functional features like algebraic datatypes, pattern matching, immutability, and more. I’ll show you how I used a mix of functional and OO features to build a slick, interactive UI.

The gateway drug of functional languages

For the uninitiated, functional programmers can seem like demented wizards–they utter arcane-sounding words like functor, and get inordinately excited over tiny functions that appear to do basically nothing. Thankfully, F# can resemble a leaner version of C# when you want it to, so it’s easy to start using it. For example, here I’ve defined a type encapsulating an animation that shoots a view outside of another view:

type ShootOutAnimator(referenceView: UIView) =
    let speed = 1300.0f
    let animator = UIDynamicAnimator(referenceView)
    member this.ShootOut(view: UIView, direction: Direction) =
        let x, y = direction.UnitVector
        let shoot = UIDynamicItemBehavior(view, AngularResistance=2.0f)
        shoot.AddLinearVelocityForItem(PointF(x * speed, y * speed), view)
        shoot.AddAngularVelocityForItem(x * 3.0f, view)
        shoot.Action <- fun () ->
            if not (referenceView.Bounds.IntersectsWith(view.Frame)) then

Pretty vanilla, right? Any Python, Java, or C# developer would understand at least 90% of what’s happening here.

As you become more comfortable with F#, you’ll start using functional features in your more traditionally OO code. For example, here I make an algebraic datatype for specifying directions to the ShootOutAnimator, and I define a read-only UnitVector property using type inference, pattern matching and tuples:

type Direction =
    Up | Down | Left | Right

    member this.UnitVector =
        match this with
        | Up -> (0.0f, 1.0f)
        | Down -> (0.0f, -1.0f)
        | Left -> (-1.0f, 0.0f)
        | Right -> (1.0f, 0.0f)

This lets me get the x and y components for a given screen direction like:

let (x, y) = Left.UnitVector

Finally, you can write code in a predominantly functional style. Here I create an asynchronous computation that downloads photos from an infinite stream of photo URLs, uses a higher-order memoize function to cache the results, and hides state within a closure (technically a deferred computation built with an async workflow, which is F#’s euphemism for “monad”):

let nextPhoto =
    let urls = (Seq.cycle photos).GetEnumerator()
    let getImage = memoize UIImage.FromUrl
    async {
        return getImage urls.Current

If you’re new to FP, you’re probably feeling a bit queasy after that last code snippet. That’s okay–the nextPhoto computation could have been implemented as a 25-line C#-style method, but I love that F# gives me such a range of expression.

These snippets come together to make this delightful interaction (full source):

I hope I’ve convinced you that compelling UIs in F# are at least possible, and that it’s a great language for gradually learning the functional concepts that are having an increasing impact on mainstream programming. If you’re still skeptical, download Xamarin, clone this app, and see for yourself! Send me an interesting pull request and I’ll mail you an F# t-shirt :smile:


June 30, 2014 6:40 GMT

Standardized Navigation Principles for Android App Development - Visual Studio Magazine Article

Navigation in mobile devices is an important consideration. If a user isn't able to navigate an app, he might quickly abandon it. Learn the navigation principles of Android to keep this from happening to you.

Mobile applications have a number of screens (Activities and Fragments) associated with them. Navigating through these is an important mechanism. There are a number of ways to provide standardized navigation in Android. This article will look at three mechanisms to provide navigation:

  1. Menus: Menus provide a common UI component for an application. The Menu APIs are used to present actions, as well as other options within an application.
  2. Navigation Drawer: The navigation drawer is a panel shown from the side of the display; it provides the user with the application's main navigation.
  3. Action Bar: The action bar provides a familiar navigation mechanism to the user across the top of the screen via an app icon, action items and action overflow.

URL: http://visualstudiomagazine.com/articles/2014/06/01/standardized-navigation-principles.aspx

Many thanks to Tomasz Cielecki

June 28, 2014 11:27 GMT

Zuckerberg and Gates

Two articles, next to each other, in my rss reader this morning. The first is about Facebook, via Marco Arment.

Scientists at Facebook have published a paper showing that they manipulated the content seen by more than 600,000 users in an attempt to determine whether this would affect their emotional state.

... And there was no need to ask study “participants” for consent, as they’d already given it by agreeing to Facebook’s terms of service in the first place.

Facebook used to be somewhat useful and interesting, to the point where the privacy stuff was bearable. Now it's filled with junk and just flat out creepy, even out-creeping Google.

The other one is from the former "Grandmaster of evil"*, Bill Gates and his wife Melinda, via The Loop:

So here is our appeal to you: As you leave Stanford, take your genius and your optimism and your empathy and go change the world in ways that will make millions of others optimistic as well.

You don’t have to rush. You have careers to launch, debts to pay, spouses to meet and marry. That’s enough for now.

But in the course of your lives, without any plan on your part, you’ll come to see suffering that will break your heart.

When it happens, and it will, don’t turn away from it; turn toward it.

That is the moment when change is born.

Gates has gone from Mr Corporate Evil to possibly one of the most prolific philanthropists in the world. The commencement speech is well worth reading.

* or so the tinfoil hat brigade in the 90's would have you believe.