February 27, 2015 6:17 GMT

Give Us the Gist of It Contest Winners!

Two weeks ago, we asked the community to share the code snippets that help them write amazing apps even faster. Five winners were chosen at random, and here is the gist of it:

Jason Fox:
Snippet Name: Xamarin.iOS Image Blur
Platform: Xamarin.iOS
Function: Image blur extension method for Xamarin.iOS

public static UIImage Blur(this UIImage image, float blurRadius = 25f)
  if (image != null)
    // Create a new blurred image.
    var imageToBlur = new CIImage (image);
    var blur = new CIGaussianBlur ();
    blur.Image = imageToBlur;
    blur.Radius = blurRadius;
    var blurImage = blur.OutputImage;
    var context = CIContext.FromOptions (new CIContextOptions { UseSoftwareRenderer = false });
    var cgImage = context.CreateCGImage (blurImage, new RectangleF (new PointF (0, 0), image.Size));
    var newImage = UIImage.FromImage (cgImage);
    // Clean up
    imageToBlur.Dispose ();
    context.Dispose ();
    blur.Dispose ();
    blurImage.Dispose ();
    cgImage.Dispose ();
    return newImage;
  return null;

Runar Ovesen Hjerpbakk:
Snippet Name: Async and await together with UIAlertController
Platform: Xamarin.iOS
Function: This snippet shows how to use a TaskCompletionSource to enable async and await together with UIAlertController.

public static class CustomerFeelingSheet {
 public static Task<CustomerFeeling> ShowRatingDialogAsync(UIViewController parent) {
   var taskCompletionSource = new TaskCompletionSource<CustomerFeeling>();
   var alert = UIAlertController.Create("howDoYouFeel".T(), null, UIAlertControllerStyle.ActionSheet);
   alert.AddAction(UIAlertAction.Create("likeIt".T(), UIAlertActionStyle.Default,
       a => taskCompletionSource.SetResult(CustomerFeeling.LikeIt)));
   alert.AddAction(UIAlertAction.Create("couldBeBetter".T(), UIAlertActionStyle.Default,
       a => taskCompletionSource.SetResult(CustomerFeeling.CouldBeBetter)));
   alert.AddAction(UIAlertAction.Create("cancel".T(), UIAlertActionStyle.Cancel,
       a => taskCompletionSource.SetResult(CustomerFeeling.DontCare)));
   parent.PresentViewController(alert, true, null);
   return taskCompletionSource.Task;

Matthieu Guyonnet-Duluc:
Snippet Name: Android Behavior – WPF Style
Platform: Xamarin.Android
Function: Reproduce the beloved WPF behaviors in Android

        local:View="@+id/resultsList" />
    public class ListViewHideKeyboardOnScroll : Behavior<AbsListView>
        public ListViewHideKeyboardOnScroll(Context context, IAttributeSet attrs)
            : base(context, attrs)
        #region implemented abstract members of Behavior
        public override void OnAttached()
            View.ScrollStateChanged += HideKeyboard;
        public override void OnDetached()
            View.ScrollStateChanged -= HideKeyboard;
        void HideKeyboard(object sender, AbsListView.ScrollStateChangedEventArgs e)
            if (e.ScrollState == ScrollState.TouchScroll)
                var inputManager = (InputMethodManager)this.Context.GetSystemService(Context.InputMethodService);
                inputManager.HideSoftInputFromWindow(View.WindowToken, HideSoftInputFlags.None);

Ken Pespisa:
Snippet Name: SQLite Extension methods for Save & Delete
Platform: Xamarin.iOS
Function: Save the specified entity by calling insert or update, if the entity already exists.

public static class SQLiteExtensions
   /// <summary>
   /// Save the specified entity by calling insert or update, if the entity already exists.
   /// </summary>
   /// <param name="pk">The primary key of the entity</param>
   /// <param name="obj">The instance of the entity</param>
   /// <typeparam name="T">The entity type.</typeparam>
   public static int Save<T>(this SQLiteConnection db, object pk, object obj) where T : new()
       if (pk == null || db.Find<T>(pk) == null)
           return db.Insert(obj);
       return db.Update(obj);
   /// <summary>
   /// Delete entities based on a predicate function
   /// </summary>
   /// <param name="predicate">The predicate specifying which entities to delete</param>
   /// <typeparam name="T">The entity type.</typeparam>
   public static void Delete<T>(this SQLiteConnection db, Expression<Func<T, bool>> predicate) where T : new()
       var records = db.Table<T>().Where(predicate).ToList();
       foreach (var record in records)

Ryan Davis:
Snippet Name: InlineTableViewSource
Platform: Xamarin.iOS
Function: A subclass of UITableViewSource that allows you to define UITableViewDataSource and UITableViewDelegate methods inline, rather than subclassing.

var cellId = new NSString("cell");
var tableView = new UITableView(View.Frame, UITableViewStyle.Grouped) {
    Source = new InlineTableViewSource {
            _NumberOfSections = (tv) => 2,
            _RowsInSection = (tv, section) => 5,
            _TitleForHeader = (tv, section) => String.Format("Section {0}", section),
            _GetCell = (tv, indexPath) => {
                var cell = tv.DequeueReusableCell(cellId) ?? new UITableViewCell(UITableViewCellStyle.Default, cellId);
                cell.TextLabel.Text = "hi";
                return cell;

Find even more speedy code snippets for your apps in the Get The Gist forum thread, and a big thanks to all who participated in the Give Us the Gist of It Contest!

February 26, 2015 4:15 GMT

Join Xamarin for GSMA Mobile World Congress 2015

Mobile World Congress LogoXamarin will take the stage alongside Airwatch, Box and Salesforce in Barcelona at Mobile World Congress next week.
Xamarin’s Director of Enterprise Mobility, Steve Hall, will join the Steve Hall“Airwatch Presents a New Standard for Enterprise App Development” panel discussion on March 2nd. Employees expect – and need – fast, on-the-go access to company data, and we’ll share how enterprises can successfully build and distribute secure mobile apps.

AirWatch Presents a New Standard for Enterprise App Development featuring Box, Salesforce & Xamarin

Tuesday, March 3, 1:30 – 2:25 pm CET
AirWatch Connect Stand
Hall 3, Stand 3D10
All MWC Attendees are welcome to attend.

See you in Barcelona!

February 25, 2015 9:17 GMT

How To Keep Your Android App Size Down

On my recent visit out to Tonto National Forest to visit one of my best friends, Luke Karrys, I started to realize the importance of trying to keep your app size down when shipping Android apps to Google Play. Working from the middle of the forest is relaxing, productive, and just plain fun, but there is one huge issue, internet and cell reception barely exists in the the middle of no where. 

When I woke up one morning and saw that I had 10 app updates ready to be installed from Google Play I was pretty excited to see what was new and fixed. However, dropping in an out of 3G service combined with an internet connection that will become crippled for everyone else if you download any files resulted in less than stellar results, and had me completely cancel all of my app updates. It had me thinking, why does the Facebook app really need to be 30MB and are all of my apps oversized as well?

There are a few ways you can take to make your app smaller when developing with Xamarin. Additionally, any Android developer can do one simple thing when deploying to Google Play to reduce their app size.

Linking Your Libraries

Xamarin applications use a “linker” in order to reduce your app size. You can browse through the documentation and find out how this works, but to simplify things, it uses static analysis to your app to remove assemblies and types that are not used in your app to bring down your app size. This is for any Xamarin app, so you should also try this out in your iOS app because it can reduce your app size in a default “Hello, World” application from 16MB down to 2.9MB! There are three settings that you can supply from the projects settings:

Don’t Link will do just that, it won’t link anything and you will be left with All of Mono, mscorlib, Xamarin.Android, and a bunch of other stuff:

Link SDK assemblies only is your safest bet and should be your default as it will only attempt to strip things out of Xamarin.Android and any of your third party libraries will not be touched. However, to really bring down your app size you should try out Link All Assemblies, as it will investigate everything and bring down your app size. Be sure to FULLY test your app as it is possible that the linker may be agressive and strip out something you need, and if that is the case you can actually use a [Android.Runtime.Preserve] flag or set a linkskip in your MSBuild to ensure that not all of your libraries get linked. 

So employing this practice with my Bike Now app, which uses Json.NET, Android Support v4, v7, Google Play Services, and Xamarin.Insights, we can compare and contrast the app size when we build our app to support all three ABIs (we will talk about this next!).

  • Don’t Link: 40.7MB
  • Link SDK Assemblies Only: 18.7MB
  • Link All Assemblies: 13MB

As you can see linking correctly can make a huge impact, but we can do even better! 

Splitting your APKs

On Android, there are ABIs (Application Binary Interfaces) that you can support when you ship your application. The most used will be the armeabi-v7a, however there are still tons of devices that support and run the old armeabi ABI and even x86 devices as well. So to ensure your app is reaching the most users you most likely have come into the project settings and selected every single ABI (I know I do!).

However, for every ABI that you select you are actually bundling a separate libmonodroid and sgen with your app. Don’t believe me then rename your .apk to .zip and take a look in the lib folder:

This of course makes sense as you would need a different version of monodroid and sgen that supports that ABI. The issue is that you now have all of these libraries bundle into a single APK and your users will be downloading all of them! The solution for any Android developer (even Java devs) is to simply split up your APKs and upload all of them to Google Play! This way you have a smaller app size across all three APKs. You can do this now with a simple check in your project options:

Now, instead of just a single APK to upload I have three with different and smaller sizes (note it will take longer to create your packages):

  • armeabi-v7a: 10.2MB
  • armeabi: 10.3MB
  • x86: 10.4MB


You may need to close XS after selecting check box and ensure this flag is set in your csproj:


Additionally, your new APKs will be in your /bin/Release folder and will be marked with Signed in their file name.

Keep your users happy and keep down that app size with these quick tips. 

February 25, 2015 5:56 GMT

Triggers in Xamarin.Forms

Triggers were introduced in Xamarin.Forms 1.3 along with Behaviors, which we covered previously. Triggers allow you to declaratively express actions in XAML that are executed when a specified condition is met. Xamarin.Forms support four types of triggers:

  • Property Trigger – executed when a property on a control is set to a particular value.
  • Data Trigger – same as the property trigger but uses data binding.
  • Event Trigger – occurs when an event occurs on the control.
  • Multi Trigger – allows multiple trigger conditions to be set before an action occurs.

Let’s take a look at each one in detail.

Property Trigger

Property Triggers (represented by the Trigger element) are added to a control’s Triggers collection. The Setter collection inside is executed when a specified property equals the specified value.


Wouldn’t it be nice to provide some visual indicator that an input control has focus? To achieve this, we can set the BackgroundColor property when the property IsFocused of the Entry element is true.

<Entry Placeholder="enter name">
        <Trigger TargetType="Entry"
             Property="IsFocused" Value="True">
                Value="Yellow" />

Alternatively, we can set them in styles so that they can be attached to every Entry element in the screen.

     <Style TargetType="Entry">
       <Setter Property="AnchorX" Value="0" />
         <Trigger  TargetType="Entry"
           <Setter Property="BackgroundColor"
                   Value="Yellow" />

Data Trigger

DataTriggers are very similar to PropertyTriggers, except that instead of specifying the Property, we specify the Binding for the trigger. This Binding generally refers to another VisualElement’s property on the page or it could reference a property in a ViewModel.

The code below shows how to disable the button when the entry’s Text.Length property is 0.

<StackLayout Spacing="20">
<Entry x:Name="emailAddress" Text="" Placeholder="email address"/>
<Button Text="Send">
    <DataTrigger TargetType="Button"
         Binding="{Binding Source={x:Reference emailAddress},
      <Setter Property="IsEnabled" Value="False" />

Event Trigger

Event Triggers execute user-defined code when a specified event occurs.

In the above Property Trigger example, we saw how to change the background color of an Entry element based on the IsFocused property entirely in XAML. Alternatively, we can use an Event Trigger to execute an action written in C# based on the TextChanged event of an entry to perform some basic validation.

Define the TriggerAction in code

Every action that we define has to inherit from TriggerAction<T> where T is the element to which a trigger is attached. When a trigger is fired, the Invoke method will be called. In the code below, we change the Entry’s BackgroundColor to indicate whether the input is valid or not.

public class NumericValidationTriggerAction : TriggerAction<Entry>
   protected override void Invoke (Entry entry)
      double result;
      bool isValid = Double.TryParse (entry.Text, out result);
      entry.BackgroundColor =
            isValid ? Color.Default : Color.Red;

TriggerAction in XAML

To use the C# code, just declare a namespace for the assembly (xmlns:local in this sample) and add the NumericValidationTriggerAction element to the event trigger:

<Style TargetType="Entry">
    <EventTrigger Event="TextChanged">
        <local:NumericValidationTriggerAction />

Multi Trigger

A MultiTrigger looks similar to a Trigger or DataTrigger except there can be more than one condition. All the conditions must be true before the Setters are triggered.

In the code below, we enable the button when either the email or the phone entries are filled in by the user. Each condition is true when the length of the text input is zero (ie. nothing has been entered). When both conditions are true (ie. both are empty) then the trigger’s Setters are called, which in this case disables the button. When either have text entered, the overall condition becomes false and the button is enabled.

<Style TargetType="Button">
  <MultiTrigger TargetType="Button">
          Binding="{Binding Source={x:Reference email},
          Value="0" />
          Binding="{Binding Source={x:Reference phone},
          Value="0" />
    <Setter Property="IsEnabled" Value="False" />

To see how to build a “require all” trigger (like you’d use in a login page, for example) check out our Triggers sample on GitHub that uses an IValueConverter along with a MultiTrigger.

For even more information on Xamarin.Forms, be sure to check out the detailed documentation.

Discuss this post in the Xamarin forums

February 25, 2015 1:44 GMT

Email is a thing, apparently: Some of the better weekly email newsletters

Well, "better" is subjective, but here's the ones I subscribe to and actually read. It's nice to get it in your inbox - easier to scan than an RSS feed, less noise than twitter.

Development related

General stuff

  • Matter. It's a sub area of Medium, and I don't remember how I got on it, but there is some awesome long form content in here.
  • Instapaper Weekly. Especially useful if you are already an IP user
  • Benedict Evans newsletter. Analyst for a16z.
  • Charged. Owen is a kiwi, but also an astute dude. Always something interesting here.
February 24, 2015 8:27 GMT

Easily launch the iOS Simulator from the command line

Launching the iOS Simulator is easy to do when we have a project already loaded in Xcode, Xamarin Studio, or Visual Studio. Simply run the project, and the iOS Simulator will automatically launch.

There are other times, though, when it would be nice to quickly launch the simulator to test something out, or maybe run an existing app. Xcode includes simctl to control the simulator, but there is an even easier way.

The ios-sim project from Phonegap provides a very nice command line interface to control the simulator

"The ios-sim tool is a command-line utility that launches an iOS application on the iOS Simulator. This allows for niceties such as automated testing without having to open Xcode." - ios-sim repository

We can easily install ios-sim using npm:

npm install ios-sim -g

Make sure to explore the API once it's installed. In order to launch a simulator, we can open terminal and run:

ios-sim start --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-6-Plus

To make this even easier, I have created aliases in my ~/.bash_profile file for the common iOS devices I use:

alias iPhone4s="ios-sim start --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-4s"

alias iPhone5s="ios-sim start --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-5"

alias iPadAir="ios-sim start --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPad-Air"

alias iPhone6Plus="ios-sim start --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-6-Plus"

alias iPhone6="ios-sim start --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-6"

Now, launching a simulator is as easy as typing iPhone6Plus

February 24, 2015 4:45 GMT

Live APAC Webinar: Go Mobile with Xamarin

Photo of Mayur Tendulkar

Join Xamarin Evangelist Mayur Tendulkar for this live webinar timed just for our APAC customers, where you’ll learn how to leverage your existing Microsoft .NET and C# skills to build iOS, Android, and Windows Phone apps using Visual Studio and Xamarin. We’ll also talk about how to maximize code sharing and reuse existing .NET libraries.

At the end of the webinar, you’ll have the skills you need to create your first iOS and Android apps in C# with Xamarin in Visual Studio.

Wednesday, March 11
11:30 AM – 12:30 PM IST


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

February 23, 2015 8:28 GMT

Redesigning the Hungarian Euro

I love it when people redesign currency. It's a project with some serious security constraints - and most of the redesigns take this very seriously - but the results are usually stunning.

This one is no exception.

I especially love the security "black light" view at the very bottom. Hat Tip to sidebar.io

February 23, 2015 7:48 GMT

Adding Real-world Context with Estimote Beacons and Stickers

It’s no secret that iBeacons have created a buzz in the development community. Leveraging these Bluetooth Smart devices enables developers to add contextual awareness to their mobile apps with just a few lines of code. iBeacons were everywhere at Evolve 2014, including at the forefront of the Evolve Quest scavenger hunt and the conference mini-hacks, as well as taking the main stage for an in-depth session.

sticker_bikeEstimote, a leader in the iBeacon space, recently introduced Estimote Stickers, a low-powered device to go alongside their traditional beacons. Stickers can be attached to almost anything and turn any everyday item into a “nearable” – a smart object that can transmit data about its location, motion, temperature, and environment to nearby apps and devices. Today, we’re pleased to announce the Estimote SDK for iOS, available on the Xamarin Component Store, enabling developers to easily detect Beacons and Estimote Stickers with a beautiful C# API that includes events and async/await support.

Detecting Nearables

Nearables have a new, simplified API. Each Nearable has a specific NearableType that can be used to detect, for example, Car, Dog, or Bike. You can decide to range for a specific type or all nearby Nearable devices.

Let’s see how easy it is to get up and running with Nearables by scanning for all Nearables that are close by.

Install the Estimote SDK for iOS

The very first task is to set up a new Xamarin.iOS project and add the Estimote SDK for iOS from the component store.


In addition to the SDK, you must specify NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription in your Info.plst file with a description that will be prompted to your users, since iBeacons use CoreLocation functionality.

Setting Up App ID

When you log in to your Estimote Cloud, you are able to manage all of your Beacons and Stickers in addition to creating API keys for your mobile apps. Once you have an app set up in the Estimote Cloud, you can config the app in your AppDelegate’s OnFinishedLaunching method:

Config.SetupAppID ("<appId from cloud>", "<appToken from cloud>");

While not required, it’s recommended to set up your app ID so that the SDK can now communicate with the Estimote Cloud to pull in unique attributes.

Ranging Nearables

Using the new NearableManager you can easily range for Nearables by subscribing to the RangedNearables event.

NearableManager manager;
public override void ViewDidLoad ()
  base.ViewDidLoad ();
  manager = new NearableManager ();
  manager.RangedNearables += (sender, e) => {
    //Nearables detected, load into TableView or pop up alert
    new UIAlertView("Nearables Found", "Just found: " + e.Nearables.Length + " nearables.", null, "OK").Show();
  //Specify the type of Nearable to range for. In this instance return All types.
  manager.StartRanging (NearableType.All);

Estimote Nearables Detected

The real power of Nearables is the additional attributes that are received when they are detected, such as their temperature, orientation, acceleration, and more. As an example, you could easily use these attributes to detect a Bike Nearable in motion for over 45 minutes and prompt your user to perhaps take a break.

NearableManager nearableManager;
public override void ViewDidLoad ()
  var identifier = "94064be7a9d7c189"; //Identifier ranged earlier
  var durationThreshold = 45 * 60; //45 minutes
  nearableManager = new NearableManager ();
  nearableManager.RangedNearable += (sender, e) => {
    var bike = e.Nearable;
    if(bike.IsMoving && bike.CurrentMotionStateDuration > durationThreshold) {
      Console.WriteLine("Bike is moving and has been in motion for over 45 minutes!");

Triggers and Rules

In addition to ranging and monitoring Nearables, there is an advanced trigger system in the Estimote SDK that enables you to specify several rules that would trigger a notification. Let’s say you want to be notified every time a Nearable changes orientation and is laid down in a horizontal position. You would simply create a OrientationRule and use the TriggerManager to wait for the Nearable’s state to change.

TriggerManager triggerManager;
public override void ViewDidLoad ()
  var rule = OrientationRule.OrientationEquals (NearableOrientation.Horizontal, NearableType.Shoe);
  var trigger = new Trigger (new Rule[]{ rule }, "TriggerId");
  triggerManager = new TriggerManager ();
  triggerManager.StartMonitoring (trigger);
  triggerManager.ChangedState += HandleTriggerChangedState;
  triggerManager.ChangedState += (sender, e) => {
    Console.Log("Shoe nearable has been placed horizontal");

More complex rules can be configured that are based on DateTime, temperature, proximity, and more.

Enhanced C# Beacon API

Xamarin.iOS has been able to detect iBeacons from any vendor since the feature was introduced in iOS 7 in CoreLocation. However, the Estimote SDK greatly simplifies the tasks of requesting and a simplified API for ranging and monitoring for beacons. In addition, if you are using Estimote Beacons you can tap into advanced features, such as their accelerometer.


Learn More

The Estimote SDK for iOS has plenty of great samples for both Nearables and Beacons for you to start out with, including a full Getting Started Guide. In addition, Estimote has SDK reference documentation and a developer portal with more information.

If you are interested in adding iBeacon functionality to your Xamarin.Android apps, be sure to check the component store for multiple libraries that you can take advantage of.

Discuss this post on the Xamarin Forums.

February 23, 2015 3:43 GMT

Deploying a database file with a Xamarin.Forms app

Sample code is available at my Github repo

It's very common for a mobile application to utilize a local sqlite database. The combination of Sqlite.net and Xamarin.Forms makes this very easy. One of the reasons that we choose Sqlite as our mobile database is that it's a single file and easily works cross platform. The same file can be created and opened on iOS, Android, Windows, Mac, Windows Phone, and WinRT.

Sometimes we may want to create our database from scratch the first time our application runs. Sqlite.net will automatically create the file if it doesn't exist the first time we attempt to connect to it. We can then use the CreateTable<TModel>() method on the SQLiteConnection class to create our tables from our C# models.

Other times though, we will want to ship a prepopulated database with the application. We may have some lookup tables that need have records in them, or default data that the application needs in order to function. Fortunately, this is easy to accomplish as well.

The steps

  • Create the database file
  • Link the database file to each platform specific project
  • Copy the database file from the application bundle to a writable location on the file system
  • Open the database file for reading and writing

Create SQLite database

Create SQL Schema

We can create a Sqlite database file using a variety of tools on both Mac and Windows. I use DB Browser for SQLite, a cross platform tool which will allow us to create the database, define the schema, and add records to the database. For this example, we'll be creating a file named "people.db3".

Create the Model

When using Sqlite.net, it's important that the C# models match the table definitions. If there is a discrepancy between the model and the table, we will have unexpected results. We may accidently create new tables, new columns in existing tables, or get no results from queries.

[Table ("people")]
public class Person  
    [PrimaryKey, AutoIncrement, Column("Id")]
    public int Id { get; set; }

    [MaxLength (250), Unique, Column("Name")]
    public string Name { get; set; }

Link database file

Once we have created the database on our desktop, we need to include it with each platform specific project (iOS/Android/WP8). We can keep the file anywhere on the desktop's file system, although including it within our solution in source control is recommended. We're going to use File Linking to include the exact same file in each project.


For iOS, we will link the db3 file into the Resources folder. Be sure to set the Build Action to BundleResource.

Link database file to iOS


On Android, we will link the db3 file into the Assets folder, and set the Build Action to AndroidAsset.

Link database file to Android

Windows Phone 8

Windows Phone will link the database file into the root of the project, and set the Build Action as Content.

Link database file to Windows Phone 8

Copy the database file

Although we've now included the database file with our application, and it will be part of the bundle that gets installed on the user's device, the app bundle and its included files are read-only. In order to actually change the database schema or add new records we'll need to copy the file to a writable location. Each device contains a special folder for each app, known as the app sandbox, to store files. We'll use each platform's file APIs to copy the file from the app bundle to the app sandbox.


[Register ("AppDelegate")]
public partial class AppDelegate : FormsApplicationDelegate  
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        Forms.Init ();

        string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");

        LoadApplication (new App (dbPath, new SQLitePlatformIOS ()));

        return base.FinishedLaunching (app, options);
public class FileAccessHelper  
    public static string GetLocalFilePath (string filename)
        string docFolder = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        string libFolder = Path.Combine (docFolder, "..", "Library", "Databases");

        if (!Directory.Exists (libFolder)) {
            Directory.CreateDirectory (libFolder);

        string dbPath = Path.Combine (libFolder, filename);

        CopyDatabaseIfNotExists (dbPath);

        return dbPath;

    private static void CopyDatabaseIfNotExists (string dbPath)
        if (!File.Exists (dbPath)) {
            var existingDb = NSBundle.MainBundle.PathForResource ("people", "db3");
            File.Copy (existingDb, dbPath);


[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity  
    protected override void OnCreate (Bundle bundle)
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);

        string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid ()));
public class FileAccessHelper  
    public static string GetLocalFilePath (string filename)
        string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        string dbPath = Path.Combine (path, filename);

        CopyDatabaseIfNotExists (dbPath);

        return dbPath;

    private static void CopyDatabaseIfNotExists (string dbPath)
        if (!File.Exists (dbPath)) {
            using (var br = new BinaryReader (Application.Context.Assets.Open ("people.db3"))) {
                using (var bw = new BinaryWriter (new FileStream (dbPath, FileMode.Create))) {
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    while ((length = br.Read (buffer, 0, buffer.Length)) > 0) {
                        bw.Write (buffer, 0, length);

Windows Phone 8

public partial class MainPage : global::Xamarin.Forms.Platform.WinPhone.FormsApplicationPage  
    public MainPage ()
        InitializeComponent ();

        SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;

        global::Xamarin.Forms.Forms.Init ();

        string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformWP8 ()));
public class FileAccessHelper  
    public static string GetLocalFilePath (string filename)
        string path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
        string dbPath = Path.Combine (path, filename);

        CopyDatabaseIfNotExists (dbPath);

        return dbPath;

    public static void CopyDatabaseIfNotExists (string dbPath)
        var storageFile = IsolatedStorageFile.GetUserStoreForApplication ();

        if (!storageFile.FileExists (dbPath)) {
            using (var resourceStream = Application.GetResourceStream (new Uri ("people.db3", UriKind.Relative)).Stream) {
                using (var fileStream = storageFile.CreateFile (dbPath)) {
                    byte[] readBuffer = new byte[4096];
                    int bytes = -1;

                    while ((bytes = resourceStream.Read (readBuffer, 0, readBuffer.Length)) > 0) {
                        fileStream.Write (readBuffer, 0, bytes);

Running the app

By including our prepopulated database with our app, we have the ability to give our users a better first run experience and minimize the amount of work that the app needs to do to be able to run for the first time.

Included data

Source Code

You can find a complete sample on my Github repo

February 23, 2015 3:00 GMT

Plugin 03: Phone Calling

In continuation to blog posts in this series on plugins, today we’ll cover a plugin to make phone calls.

As we understood before, all platforms support phone calling (just like emailing, texting, etc…) and Xamarin makes it easier with one common language – C#. However, developers still need to learn

In case of Windows Phone, one can initiate a phone call by using following code. In this case, Windows Phone has special class which allow developers to perform this task.

Screenshot 2015-02-23 10.53.12

In case of Android, developers can use ‘Intent’ and ‘URI activation’ to start a new phone call.

Screenshot 2015-02-23 10.56.09

In case of iOS, same concept of URI activation can be applied. As shown below in the code, developers can create a URI with telephone number and it will launch default application to make a phone call.

Screenshot 2015-02-23 11.13.09

Now, in case of Xamarin.Forms developers can use same Messaging Plugin for Xamarin and Windows plugin to implement phone functionality across the platforms.

Screenshot 2015-02-23 12.31.23

This way, developers can utilize the power of plugins to write one code which can work across different platforms, without bothering about underlying APIs.

Mayur Tendulkar

February 23, 2015 2:52 GMT

Write Automated UI Tests for iOS and Android Apps

Previously in this column, I've written about unit testing iOS apps, but what can you do when unit tests just won't cut it? If you're a Web developer you're probably already familiar with libraries like Selenium, which allow you to drive automated testing of your Web app's front-end.

Xamarin offers a library named Xamarin.UITest that enable the similar possibilities for your iOS and Android apps. In addition to being able to run those tests locally on an emulator or device, you can even push the same tests out to Xamarin's Test Cloud, allowing you to validate your tests across more than a thousand different devices.

Read the full article over on Visual Studio Magazine

February 21, 2015 11:36 GMT

Apple Watch Kit round-up

It's Saturday, a good excuse for a 'fun' post. Here's a little collection of tidbits about the Apple Watch...

Apple: Watch Kit - if you're thinking of developing for the platform, might as well start at the source :)

Wareable: The best Apple Watch apps... - some great screenshots of apps already being built, including Clear, BMW, and Nike. It's interesting to see the UI design approach being taken by different developers. Check out the similar list on ibtimes.com

FastCompany: How the Apple Watch will work... - a couple of thoughts on app design, and screenshots of Todoist.

eleks labs' unofficial Tesla app - more design thoughts and prototype video (unofficial development, not affiliated with Tesla)..

Daring Fireball: On the Pricing of the Apple Watch - so yeah, "starting at $349" sounds like it's going to be the understatement of the year.

WatchKit FAQ - Awesome collection of questions and answers (and cute watch drawings too).

MartianCraft: Designing for the Apple Watch with Briefs - even if you don't use the tool (which looks great) this is a lovely post on Watch app design.

If that's got you interested in building apps for the Apple Watch, it's time to check out Xamarin's Watch Kit Preview and how to get started (inc video) and my first watch app.

I've also got a couple of samples, including Magic 8 Ball, Calculator, Insta, and Todo for you to try.

^ watch frame screenshots generated with Bezel thanks to the fine folks at infinitapps.
February 21, 2015 10:47 GMT

Tips For Uploading Apps to Organizations in HockeyApp

Like many others right now, we're in the process of migrating our testing infrastructure from TestFlight to HockeyApp before the TestFlight shutdown next week. As we did in the past with Xamarin and HipChat, we also open sourced the FAKE helper we made for uploading builds to HockeyApp.

For example, to upload a build to HockeyApp and then send a notification to a room in HipChat you can do:

HockeyApp (fun p ->  
  {p with 
    ApiToken = Environment.GetEnvironmentVariable("HockeyAppApiToken")
    File = ipaOrApkPath
|> fun response ->
    HipChatNotification(fun p ->
      {p with 
          AuthToken = Environment.GetEnvironmentVariable("HipChatAuthToken")
          RoomId = Environment.GetEnvironmentVariable("HipChatNotificationRoom")
          Message = ("Successfully deployed to HockeyApp: " + response.ConfigUrl)
          Color = "green"
      }) |> ignore

As part of the transition, we created an organization for the company, and a couple teams within that organization. We then proceeded to run into a few stumbling blocks in getting things working properly, which I wanted to share to hopefully help others avoid the aggravation we went through. It's also entirely possible that we were just doing something wrong or missing something entirely - if that's the case, please do let me know!

API Tokens and Ownership

All of our uploads happen through automated CI builds, so the next thing we did was go to create an API token to use. I was a little disappointed to see that API tokens are managed at the user level, rather than the organization. It's not the end of the world, but it would be nicer if that lived under the organization so that multiple people can manage the same tokens.

The main problem we hit as a result of this is that builds uploaded using this API token would be tied to the user that created the key and not the organization. This makes sense based on the fact that the token is tied to a user and not the organization, but the documentation for uploading a build makes no mention of a way to set the owner for an app. It's possible to transfer the app to the organization on the website through a series of somewhat clunky steps, but this really wouldn't scale well for the volume of apps we process in our system.

Thankfully when I raised the question on Twitter earlier today, HockeyApp was nice enough to respond very quickly with a way to achieve what we needed. The solution is to pass in an owner_id parameter with the upload payload, which can be used to set the owner for the app using its ID. You can get the ID out of the URL when viewing the organization on the site. Here's what that looks like in cURL syntax:

-F "owner_id=3141592" \

Hopefully they add this to their documentation soon. We'll also be publishing an update to the FAKE helper soon that will include the ability to set this ID from your build scripts.

Visibility to Users

Once we got the organization ownership working the next thing we realized was that despite our assumptions, the builds weren't visible to anyone else on my team, despite the fact that I'd added them to the Owners team. There are a couple ways you can go here. First, HockeyApp does have an endpoint at /api/2/apps/APP_ID/app_teams/ID that you can use to assign a team to an app programmatically. This is fine, but what we really wanted was for people in the owners group to automatically get access to everything.

After some digging we came across this checkbox when you're adding/editing an owner for an organization:

User settings

Somehow we'd overlooked that option when initially setting things up. Personally I think this should be the default behavior, since to me an "owner" should be someone with full admin rights across the organization.

Overall things seem to work pretty well in HockeyApp but the user experience definitely leaves quite a bit to be desired, especially given that it's a paid product. Hopefully we'll see some nice updates coming to HockeyApp in the coming months now that they're part of Microsoft.

February 21, 2015 7:53 GMT

Presenters in MvvmCross: Nested Modal Navigation in iOS

When navigating to a new view controller in iOS there are two primary ways to do so: pushing it to the navigation stack (the standard way), or "presenting" it which results in a modal-like experience where the new view comes up from the bottom of the screen. This interaction can be useful to convey context to the user, since it feels like a modal interaction that will return them to the current screen afterwards, rather than a navigation away from what they're doing.

MvvmCross ships with a variety of presenters in the box that you can make use of, two of which support modals - MvxModalSupportTouchViewPresenter and MvxModalNavSupportTouchViewPresenter. If you're using one of these presenters you can simply add the IMvxModalTouchView marker interface to a view class and they will automatically be presented as a modal. This is great, but these presenters have one main problem in their current implementations: if you're in a modal view, you can't present another modal view. If you try you'll be greeted with an exception saying "Only one modal view controller at a time supported". Let's take a look at how you can extend the built-in presenters to add support for this, allowing views at any nesting level to either pop a new modal, or navigate to a non-modal view.

Views and View Models

First we need some view models:

public class NonModalViewModel : MvxViewModel  
    public IMvxCommand PopModalCommand
        get { return new MvxCommand(() => ShowViewModel<ModalViewModel>()); }

    public IMvxCommand CloseCommand
        get { return new MvxCommand(() => Close(this)); }

public class ModalViewModel : MvxViewModel  
    public IMvxCommand PopModalCommand
        get { return new MvxCommand(() => ShowViewModel<ModalViewModel>()); }

    public IMvxCommand GoToNonModalCommand
        get { return new MvxCommand(() => ShowViewModel<NonModalViewModel>()); }

    public IMvxCommand CloseCommand
        get { return new MvxCommand(() => Close(this)); }

Then we'll need some simple views to trigger those commands:

public class NonModalView : MvxViewController  
    public override void ViewDidLoad()

      View = new UIView { BackgroundColor = UIColor.White };

        var popModal = UIButton.FromType(UIButtonType.System);
        popModal.Frame = new CGRect(10, 100, 300, 50);
        popModal.SetTitle("Pop modal", UIControlState.Normal);

        var close = UIButton.FromType(UIButtonType.System);
        close.Frame = new CGRect(10, 300, 300, 50);
        close.SetTitle("Close", UIControlState.Normal);

            var set = this.CreateBindingSet<NonModalView, NonModalViewModel>();
            set.Bind(popModal).To(vm => vm.PopModalCommand);
            set.Bind(close).To(vm => vm.CloseCommand);
            set.Bind(close).For("Clicked").To(vm => vm.CloseCommand);

public class ModalView : MvxViewController, IMvxModalTouchView  
    public override void ViewDidLoad()

        View = new UIView { BackgroundColor = UIColor.White };

        var popModal = UIButton.FromType(UIButtonType.System);
        popModal.Frame = new CGRect(10, 100, 300, 50);
        popModal.SetTitle("Pop modal", UIControlState.Normal);

        var goToNonModal = UIButton.FromType(UIButtonType.System);
        goToNonModal.Frame = new CGRect(10, 300, 300, 50);
        goToNonModal.SetTitle("Go to non-modal", UIControlState.Normal);

        var close = new UIBarButtonItem(UIBarButtonSystemItem.Cancel);
        NavigationItem.RightBarButtonItem = close;

        var set = this.CreateBindingSet<ModalView, ModalViewModel>();
        set.Bind(popModal).To(vm => vm.PopModalCommand);
        set.Bind(goToNonModal).To(vm => vm.GoToNonModalCommand);
        set.Bind(close).For("Clicked").To(vm => vm.CloseCommand);

Presenter Setup

Now we can start building out our new presenter. One option would be to inherit from one of the existing modal presenters and extend it that way, but for this example I'll just inherit from MvxTouchViewPresenter to show how little code is actually required to make this work:

using System.Collections.Generic;  
using System.Linq;  
using Cirrious.MvvmCross.Touch.Views;  
using Cirrious.MvvmCross.Touch.Views.Presenters;  
using Cirrious.MvvmCross.ViewModels;  
using UIKit;

namespace NestedModalPresenterDemo  
    public class NestedModalPresenter : MvxTouchViewPresenter
        public NestedModalPresenter(UIApplicationDelegate applicationDelegate, UIWindow window) 
            : base(applicationDelegate, window)

Next, we need to maintain a stack of modal views:

private readonly Stack<UIViewController> _modalViewControllers = new Stack<UIViewController>();

protected override UIViewController CurrentTopViewController  
        return _modalViewControllers.FirstOrDefault() ?? MasterNavigationController.TopViewController;

private UINavigationController CurrentNavigationController  
    get { return (CurrentTopViewController as UINavigationController) ?? MasterNavigationController; }

It's important here to override the base implementation of CurrentTopViewController so that any operations that should apply to the top view, like navigating, are always happening to the correct one. Since each modal we pop is going to be wrapped in its own UINavigationController to allow it to do non-modal navigation as well, we also add a property here for grabbing the current navigation controller.

Showing Views

With that in place, we can add the logic needed to show both modal and non-modal views:

public override void Show(IMvxTouchView view)  
    var viewControllerToShow = (UIViewController)view;

    if (view is IMvxModalTouchView)
        var newNav = new UINavigationController(viewControllerToShow);

        PresentModalViewController(newNav, true);


    if (MasterNavigationController == null)
        CurrentNavigationController.PushViewController(viewControllerToShow, true);

public override bool PresentModalViewController(UIViewController viewController, bool animated)  
    CurrentNavigationController.PresentViewController(viewController, animated, null);


    return true;

If you've done any other presenter work before this should look pretty familiar, since there's not much going on here. For this example we'll stick with looking for IMvxModalTouchView to signal the modal, but if you're like me and not a fan of marker interfaces you could easily swap this out to look for something else like a custom attribute. When a modal view is shown it gets wrapped in a UINavigationController and then added to the modal stack to keep track of the state.

Closing Views

Now that we can show the modals, we just need to add the ability to properly close them:

public override void CloseModalViewController()  
    var currentNav = _modalViewControllers.Pop();

    currentNav.DismissViewController(true, null);

public override void Close(IMvxViewModel toClose)  
    if (_modalViewControllers.Any() && CurrentNavigationController.ViewControllers.Count() == 1)



When a close request comes in when we're in some level of modal nesting and the current navigation controller's backstack is empty we close the modal and remove it from the modal stack. If the backstack is not empty we just pop the view normally.

I've omitted it here for simplicity, but it's also often a good idea to do some view model type checks to make sure you're operating on the correct views for the request.

February 21, 2015 9:06 GMT

XhackNight by Xhackers - A journey to relish

Let me start our XHacknight postmortem with a quote which summarizes our pre-Xhacknight journey

The amount of effort you put in is the amount of results you end up with- Catherine Pulsifer

It all started when we, the Xhackers launched our Xhacknight website -http://xhackers.co/xhacknight and invited cross-platform app/game development enthusiasts to sign up for a two day overnight hackathon- our first public Xhackers hackathon.

The response was overwhelming and it was a full house at the venue by 10 AM.
Audience Audience

On Feb 7th, the first day we had sessions stretching on Xamarin, Microsoft Azure and CocosSharp, which guided participants to get started with Xamarin and CocosSharp -APIs, libraries, components, IDE, Tools, Azure services to use as backend for their apps/games. Let's name this chapter of our journey as Learn to Code

There were sessions and demos by

  • Pooran on Xhacknight Sponsors, Rules & Prizes
  • Nishanth from Xamarin on Mobile Excellence, Hello iOS, Architecting for Cross-Platform, Xamarin. Forms, & Windows Phone
  • Vic on Hello, Android
  • Abhishek and Sagar Bhanudas from Microsoft on Mobile First, Cloud First and Azure Mobile Service
  • Vidyasagar on Go Gaming with CocosSharp.

Participants showered their love for the sessions and their valuable feedback through tweets on twitter (#Xhackers)

On the same day evening at 5 PM, KirtiSagar from Xhackers team announced 5 hacks with the choice left to participants to choose one. We call this chapter of our journey as Code to Win - Hack Begins

The hacks had some simple rules and stressed usage of GeoTagging, GeoFencing, GeoLocation APIs, Xamarin and CocosSharp libraries + Components. We also suggested them to use Microsoft Azure storage or services as a backend for their apps/games.

We had few panel members, including Senthil reviewing participants' ideas and others helping in setting up their machines with Xamarin software.

Hackers (Participants) were fully charged and continued transforming their ideas into apps/games. XHackers team was roaming around interacting with the teams, helping them in moving forward, encouraging and entertaining them as it was a long night ahead.

The participants were so much into their app/game development using Xamarin that they didn't even bother about dinner and sleep. Their determination forced us to stay awake the whole night. To keep the participants charged, we were running TweettoWin contest.

Day 2 - 9:00 AM, at 17th Hour of XHacknight

Most of the participants have zeroed on their idea and were 30-35% done with their development. There were some interesting ideas getting transformed into Cross platform apps and games.

We organized a session on connecting your xamarin apps to Azure Mobile services by Anubhav from Xamarin to help participants.

At 1PM, we closed the hack and its Judgement time. It was tough for us to judge as more than 50 participants showed awesome enthusiasm and patience in developing cross platform apps/games using Xamarin.

Every team was given 2 minutes to present their idea and app/game. The panel judged each app/game based on a five point criteria - Idea, Number of platforms, UI design, Cloud usage, Xamarin API, Library usage.

Prizes from our sponsors were given under different categories

  • Best cross platform app
  • Best gaming app
  • Best windows app
  • Best Idea
  • Best API usage
  • Best Effort

It's all over and we loved every second of our journey and we thank every participant for making this special and would love to see you again.

We also thank our sponsors Microsoft,Xamarin for the prizes, food and other arrangements.We cordially thank Pluralsight, Telerik(US) for their goodies and support.

Rather than calling this a postmortem, we would love to call this postMomentum.

Tweets from participants

Xhackers Core Team

February 19, 2015 6:29 GMT

Code Sharing Strategies for iOS & Mac

I fell in love with the Xamarin approach to mobile development because sharing code across platforms provided me with huge productivity gains when developing apps. With Xamarin you can share an average of 75% of app code across all mobile platforms and in this blog post, I’m going to give you some strategies to help you share even more code between iOS and OS X. If you’ve recently developed an app for iPhone or iPad using the traditional approach (sans Xamarin.Forms),  you might be surprised to learn how much code you can share between iOS and OS X. With the Mac platform becoming increasingly popular, there’s never been a better time to consider if your apps could benefit from targeting a new platform. Let’s learn some tips and tricks for sharing more code between the platform all in the context of C#.


General Code Sharing Strategies

It’s common knowledge that both iOS and OS X share a common architecture, which results in a great code sharing story. Many classes are compatible on both platforms without modification and with the recent release of the Unified API, we’ve made it even easier to share code between OS X and iOS.

Before we get started on linking all of our existing Xamarin.iOS code in a new Xamarin.Mac project, we need to first look at what we should share and what should remain platform dependent. The most common architectural pattern for iOS and OS X development is the Model View Controller (MVC) pattern. This increases the amount of code reuse in our app as many of the models and controllers will still be relevant regardless of the underlying platform.

Conditional Compilation (Shimming)

Sharing our view code is a little more involved, but is possible with a couple of techniques used by Apple in apps such as Keynote. Your existing iOS apps will be using the UIKit namespace, which is the framework that provides the window and view architecture needed to manage your app’s user interface. Here you will find labels, buttons, colors and other classes that you’ll build your app’s UI with. UIKit is only available for iOS, which means any code utilizing this framework will not run on the Mac without some modification. Let’s take a look at the simple sample problem of sharing colors between platforms.


var xamarinBlue = UIColor.FromRGB(0.26f, 0.83f, 0.31f);


var xamarinBlue = NSColor.FromCalibratedRgba(0.26f, 0.83f, 0.31f, 1f);

The above example is fairly consistent with what I find when looking at customers’ projects. With a little bit of trickery, we can share colors between platforms. Apple calls this “shimming” but you might know it as “conditional compilation”.

public class Color
 #if __MAC__
 public static NSColor FromRGB(nfloat r, nfloat g, nfloat b)
 return NSColor.FromCalibratedRgba(r, g, b, 1f);
 #if __IOS__
 public static UIColor FromRGB(nfloat r, nfloat g, nfloat b)
 return UIColor.FromRGB(r,g,b);

Now in both our iOS and OS X app, we can use the following to create our blue color.

var xamarinBlue = Color.FromRGB(0.26f, 0.83f, 0.31f);

If this is running on iOS, it will return a UIColor and on OS X we will get an NSColor. This is an approach I apply in many areas of UIKit and AppKit. You could for example extend this to UIImage and NSImage.

public static CGImage ToCGImage(string imageName)
 #if __MAC__
 return NSImage.ImageNamed(imageName).CGImage;
 #if __IOS__
 return UIImage.FromFile(imageName).CGImage;

Sharing Your UI with CALayers

If you want to maximize your code sharing, then you might want to investigate using CALayers. UIViews are built on CALayers, which can be accessed by using the Layer property of the UIView. The benefit of using CALayers over UIView is that CALayers can very easily be ported to OS X and there is no performance loss over using UIViews or NSViews. Apple’s Keynote canvas uses CALayers which allows them to share over 1m LOC between OS X and iOS.

In the example below, I’ve inherited from a CALayer and overridden the DrawInContext method to get the view setup. I set the background color, using my shimming method, to be purple. I then override the HitTest, which allows me to respond to touch or click events. In this sample, I want to change the background color of the layer every time the user interacts with it. Despite being a basic example, this code works on both iOS and OS X without any modification.

public class ColorChanger : CALayer
 public override void DrawInContext(CGContext ctx)
   BackgroundColor = Color.FromRGB(0.65f, 0.22f, 0.72f).CGColor;
   count = 0;
   this.Contents = Image.ToCGImage("xamagon.png");
 public override CALayer HitTest(CGPoint p)
   switch (count)
     case 0:
       BackgroundColor = BackgroundColor = Color.FromRGB(0.2f, 0.52f, 0.89f).CGColor;
     case 1:
       BackgroundColor = BackgroundColor = Color.FromRGB(0.26f, 0.83f, 0.31f).CGColor;
     case 2:
       BackgroundColor = BackgroundColor = Color.FromRGB(0.65f, 0.22f, 0.72f).CGColor;
       count = 0;
  return base.HitTest(p);
 int count = 0;


With Xamarin, you’ve always been able to share approximately 75% of your code between the different platforms, and now with the above tips you can share even more. If you’re looking for basic drawing between platforms, you may find Frank Krueger’s CrossGraphics library useful, as it allows for drawing graphics on Android, iOS, Mac, Windows, and ASP.Net using .Net.

February 18, 2015 8:23 GMT

Xamarin App Video Spotlight: Curse Inc.

At Xamarin Evolve 2014, I had the opportunity to speak with Xamarin customer Curse, a multimedia technology company that builds websites and software for gamers. With 50 million users on their websites and 6 million users on their desktop client, Curse turned to Xamarin to help them build out Mac, Android, and iOS apps for their new product, Curse Voice.

Watch the video below to get a better understanding of how the Curse team was able to take their existing Windows code and get their innovative Curse Voice apps up and running quickly on Mac, iOS, and Android with Xamarin.

Learn More

Try out Curse Voice, from Curse, here.

To get started developing with the Xamarin platform, check out our developer documentation, or get live online training with Xamarin University.

February 18, 2015 3:54 GMT

How to send and receive posts safely

By now, all my friends and relatives know that if theyStop right there receive an email, even from someone they know, they should not click on any links. (Danger, Will Robinson).

But I like sending links to important articles or videos.  How can I help my friends and relatives feel safe and yet open the email.

Easy, I send each of my friends and family an email that says:

“Please check this email by writing back and asking if I really sent it, or even better by calling me at 339-201-6010  From now on, when I send you email with a link, I will put the word fadoodle* at the bottom, so that you know it is really from me. Please do the same if you are sending me a link”

*Fadoodle is any made up word and not the one I use

This simple mechanism reassures the recipient that the email really came from you.  You can use any word, but you are best doing what you would do with a password: the longer the better.

There definitely are more secure ways to do this, but this is sufficiently secure for me, and it is painless.


February 17, 2015 9:12 GMT

StepCounter Gets in Shape

Last year we announced the release of My StepCounter for iOS. Since then, the iOS landscape has changed considerably – HealthKit was announced, two new iPhones have been introduced, and the iPad now supports My StepCounter AppIcon the same API for CoreMotion as the iPhone.

The original app was designed purely with the iPhone 5s in mind, as this was the only supported hardware available at the time. With an increase in the number of devices that support the step counting API, I thought it was time to make an update to ensure the app works perfectly on these new devices.

While updating the app, I opted to migrate the user interface from Apple’s older Xib format to a single Storyboard. With this change, you’re now able to visualize how My StepCounter will look from within both Xamarin Studio and Visual Studio. The new approach is great for developers using Visual Studio, as they can minimize the amount of time interacting with Xcode on their Mac build host.


Not only does My StepCounter now support Storyboards, a number of images have been replaced with custom views drawn using code generated from PaintCode. The new change has cut down the number of artwork assets the app needs to ship with, and thus reduces the final binary size.

The benefit of this is huge, as it means the app looks great on any screen size without the binary size bloating from additional images. One of my favorite things about using a tool like PaintCode is that the control is live rendered within our storyboard designer so you can instantly see how your App will look in the designer without having to deploy to the simulator or device.

A few extra little additions to the app include integration with Xamarin Insights, a new share option so you can tweet or post your step count, and improved animations across the entire app.

All of the code is up on GitHub for you to download and explore today.

February 17, 2015 1:00 GMT

Xamarin.Forms Platform Customizing with Device.OnPlatform

Xamarin Forms allows us to quickly build native mobile cross platform applications user interfaces from a single code base. The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the look and feel for iOS, Android and Windows Phone.

Xamarin.Forms gives you the ability to customize the look and feel of the UI. Even with the use of native controls, it is still unfortunately possible to have your Android app looking a little too much like its iOS equivalent. Design guide guidelines for each platform should be used to give your users a familiar and welcoming experience.

Code Reusability

Customization can vary from no customization to fully customized with renderers for each platform. One of the big benefits of using Xamarin.Forms is reusing the single code base on multiple platforms. Having custom renderers for each platform will negate this benefit. The trick is to find a balance and use the customization option appropriately.

Code Reuse Chart

Having to use custom renderers for simple things like setting a background color would not make much sense. To enable this scenario, the developers at Xamarin have given us two methods on the Device class that will execute code only on specific platforms.


The first is the generic static method OnPlatform that takes three values. One for each platform and returns the value for the currently running platform. This method is used for simple things like font size and element padding customizations.

public static T OnPlatform<T> (
    T iOS,
    T Android,
    T WinPhone

// Summary
// Returns a different values depending on the
// Xamarin.Forms.TargetOS Forms is working on.


The second method is the device OnPlatform static method that can take up to four action parameters. All four parameters are named and optional. Three are for the different platforms iOS, Android and Windows Phone and the last is for a default value. Think of this method like a switch statement with a default clause. This method is used for more complex customization. I like to use it when I have multiple customization on the same element or when I have multiple elements with a few customizations. I think the code looks cleaner to have all my customizations bundled together and the default is nice too.

public static void OnPlatform (
    Action iOS = null,
    Action Android = null,
    Action WinPhone = null,
    Action Default = null

// Summary
// Executes different Actions depending on the 
// Xamarin.Forms.TargetOS Forms is working on.

Device.OnPlatform In Action

Let’s try using it in anger to customize a very simple Xamarin.Forms app with a little bit of help from the platform design guidelines. The code below is just a simple Xamarin.Forms app with a single label.

public class App : Application
	public App ()
		var label = new Label ();
		label.Text = "Customizing Xamarin Forms";
		label.XAlign = TextAlignment.Center;

		var stack = new StackLayout ();
		stack.Children.Add (label);
		stack.VerticalOptions = LayoutOptions.Center;
		stack.Padding = new Thickness (10);

		var page = new ContentPage ();
		page.Content = stack;

		MainPage = page;

This is what they look like. Very plain and not very distinctive. What’s really funny is if I change a few things, I could make it almost impossible to distinguish the Android version from iOS.

Android Device-OnPlatform Before
iOS Device-OnPlatform Before

Now let’s not change the code and add some customizations using the platform design guidelines for each platform. For iOS, we are going to change the font and specify a nice translucent background. For Android, we are going to use a background color straight from the Material Design Guide and use a condensed font.

public class App : Application
	public App ()
		#region Page Display

		Device.OnPlatform (
			iOS: () => {
				page.BackgroundImage = "back.png";
				label.FontFamily = "HelveticaNeue-Thin";
				label.FontSize = 20;
			Android: () => {
				page.BackgroundColor = Color.FromHex ("#AA66CC");
				label.FontFamily = "sans-serif-condensed";
				label.FontSize = Device.GetNamedSize (NamedSize.Medium, label);

		MainPage = page;

With just a few lines of customization, here is what our applications looks like.

iOS Device.OnPlatform After
The ability to customize the UI for each of the mobile platforms enables Xamarin.Forms to deliver on its promise of a single UI code base that is deployable on all three major platforms.  You don’t have to use custom renderers that hurt your code reuse to make small to modest changes in your UI. Using Device.OnPlatform will keep your code reuse metric high while giving your application users a familiar and native user experience.

The post Xamarin.Forms Platform Customizing with Device.OnPlatform appeared first on Syntax is my UI.

February 17, 2015 9:17 GMT

Dipping your feet into Xamarin Animation Extensions

I must admit that I've kind of missed this whole animation thingy that Xamarin put into Xamarin Forms. I've used the Animation classes to animate single properties, but haven't really put any time into exploring the extension methods for the View class. (poorly documented here).

The animation extension methods lets you move, rotate and scale stuff with different duration and easing functions. Duration and easing are optional parameters that you can pass into each animation function. An easing is a function of the rate of change during an animation. For example the BounceIn easing will overshoot its target and "bounce back" to the value required. Hence, bounce...

Anyway, let's move through each function!

The sandbox

So I started out with a single button in a single XAML view. Centered in all directions and just perfect. I've totally ignored all MVVM stuff and directly referenced the button control by name (theButton).

xml version="1.0" encoding="UTF-8"?>

        <Button Text="Click me" x:Name="theButton" 
                HorizontalOptions="Center" />

Step one - Let's move it!

I added code in the code behind to handle the Click event (don't worry, we'll do it MVVM style later on in another post). This simply moves the button itself to a absolute position. You could of course move any other object that inherits from VisualElement. An important thing to think about is that it will move the object to the bounding box's upper left corner. Also, you must supply enough space yourself to make sure that the contents of the view has enough room to display itself.

    public partial class MainView : ContentPage
        public MainView()
            theButton.Clicked += async (object sender, EventArgs e) => 
                   await theButton.LayoutTo(new Rectangle(100, 100, 300, 50));

Step two - Translate this!

Another way to move the button without having to care about the width and height is to use the TranslateTo extension method. The important thing here is that the movement is relative. So translating by {0,0} doesn't do a thing. The example below moves the button left and up by 50.

    await theButton.TranslateTo(-50, -50);

In order to use the TranslateTo extension method you need to keep track of where you start from.

Step three - Scaling and ContinueWith!

You can string animations together since all calls are using async/await. The first way of doing this is to simply declare the method async and add await before each call. (gotta love C#).

    await theButton.ScaleTo(3);
    await theButton.ScaleTo(1);

So then this should work...

await theButton.ScaleTo(3).ContinueWith((a) => theButton.ScaleTo(1) );  

It does not... It works the first time you click the button, but the second time it gets stuck after the initial upscaling.

Step four - RelScale does what?

All the Rel* functions simply add to what ever value the control has before. The code below adds 4 to the scale each time you click it. It becomes really large after a while.

    await theButton.RelScaleTo(4);

This also goes for RelRotate and is pretty much what TranslateTo also does.

Step five - Fade to black

The fade function let's you control the opacity to what ever value you'd like. Nothing fancy, but very useful. To make the button disappear, just fade to 0. The upper limit is one (1) and that means that it's totally visible.

    await theButton.FadeTo(0);

Step six - Rotation

The last of the animation extension methods. Rotates the control to 40 absolute degrees. The RelRotate adds the given value to the current rotation.

   await theButton.RotateTo(40);

Another cool rotate function the RotateXTo and RotateYTo that gives you a 3D effect. Combine it with a FadeTo(0) to make your buttons fold and disappear! :)

Combining them

Can you combine different animations? Well, yes you can! Simply omit the await keyword to continue execution.

   theButton.TranslateTo(-10, -150);
   await theButton.FadeTo(0);

You might wonder why I don't use a fancier way to do the await, like in the example below? It simply doesn't work. The animation "locks up" half way through. Another issue for Bugzilla.

   var t1 = theButton.TranslateTo(-10, -150);
   var t2 = theButton.FadeTo(0);

   Task.WaitAll(t1, t2);


The animation extension methods are cool. Use them. Now!
February 16, 2015 4:02 GMT

Update on ViewModel to ViewModel Navigation in Xamarin.Forms using MessagingCenter

If you're trying to do this as per my previous post here http://blog.alectucker.com/post/2014/07/26/using-messageingcenter-in-xamarin-forms-for-viewmodel-to-viewmodel-navigation.aspx and are getting this error:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

...then you may be tripping over this:

https://bugzilla.xamarin.com/show_bug.cgiand ?id=22228)

(Xamarin.Forms v1.3.2.6316)

It seems to occur when you send a message, a subscriber picks up the message, and either subscribes or unsubscribes to/from the message is its handler. There’s a bit more info, as well as a solution to replicate the issue, in bugzilla if you follow the link above.

The workaround suggest by jruskin does the trick, although I did have to vary it a little. The solution is to put the following into the handler:

await System.Threading.Tasks.Task.Delay(25);

When this line is hit the await will relinquish control to the previous thread, meaning that the internals of the MessagingCenter can finish tidying up (or at least I’m assuming that’s the explanation J ). You’ll see that I’ve waited for 25 milliseconds, as opposed to the 1ms mentioned in the comment on Bugzilla. I’m testing on an HTC Desire, which required a 25ms pause to get rid of the exception.

Here’s an example:

private void SubscribeToMessages()


    MessagingCenter.Subscribe<Messages.NavigationMessage>(this, "Navigation", async (navigationMessage) =>


        // Workaround for bug: https://bugzilla.xamarin.com/show_bug.cgi?id=22228

        // Await a small delay to give up the thread to the caller to finish enumeration of the sender list

        await System.Threading.Tasks.Task.Delay(25);

        switch (navigationMessage.Type)


            case eNavigationType.ShowOneView:

                Navigation.PushAsync(oneView, true);


            case eNavigationType.ShowAnotherView:

                Navigation.PushAsync(anotherView, true);


            case eNavigationType.Back:








February 16, 2015 3:53 GMT

Plugin 02: Email Messaging

In previous blog post we’ve seen how we can use plugins to send text messages and use same API across platforms without bothering about individual platform specific APIs. In this blog post we’ll continue to discuss plugins and see how we can send Email messages.

In case of Windows Phone, we can use EmailManager to send EmailMessage. The code will look like:


For Android, there is no class as such which can handle email messaging. Rather, we use something called as Intent.


In case of iOS, we use built-in controller to pass parameters which can populate the email message and later-on send it.


Now, lets see how we can implement this feature in Xamarin.Forms using Plugins. The plugin which we used last time, is feature rich and also included capability to send emails. Refer Messaging Plugin for Xamarin and Windows in your applications and modify the code as shown below. Depending on the platform on which the code is executing, it will internally call the platform specific APIs.


Once again, using this plugin it becomes easy to send Email on Android, iOS and Windows Phone.

Mayur Tendulkar

February 16, 2015 2:30 GMT

Episode 23: Continuous Delivery for iOS Apps with Felix Krause

Continuous integration and delivery is commonplace in the web development world, but has been notoriously difficult to achieve with mobile apps. In this episode we talk to Felix Krause about his fastlane tools that aim to solve multiple pain points in iOS development and deployment by automating everything.

Hosts: Greg Shackles, Jon Dick

Guest: Felix Krause


Thanks to our Sponsors!


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

February 16, 2015 1:00 GMT

Lego Mobile Device Lab Stand

The other day someone on Twitter made a comment about needing a device stand and that his desk was a mess. I think most of us can relate to other mobile developers with the same problem.

As an avid woodworker this was not a big problem for me. I could have gone into my shop and cranked out a stand with some scraps from other projects. The only problem is the lack of flexibility. New devises and form factors (iPad Pro, Please) would make a universal desk stand pretty hard. What I needed was a flexible platform that I could reconfigure whenever I would get a new toy device.


Yep, not only do I get to play with mobile devices all day, I also get to play with Legos. Did you know that you can special order different parts from Lego directly? Me either. It’s call “Pick a Brick” and ordering was easy, the wait was not. Speedy Amazon they are not.

cable holder

Cable holder


Corner Blocks

holding cell

iPhone 6+

Some Assembly Required

With the combination of the corner blocks, cable holders and a large base board, I can add and remove new and old devices any time. This one is getting a little crowded and is missing Windows Phone.

Lego Device Stand

My woodworking skills did not go to waste on this project. The base board is pretty flimsy and it definitely needed a wooden backer board. The wooden backer board or stand was made from pine and has a picture frame kickstand. Next time, I’ll add some mass to the stand. Sometimes my touches on the devices make the stand walk backwards. Live and learn.

The post Lego Mobile Device Lab Stand appeared first on Syntax is my UI.

February 16, 2015 11:50 GMT

Custom Map Tiles in Xamarin.Forms

Over the past few weeks i have been working on a project which required not only a mapping element but also required custom map tiles to be overlaid on the map. This is actually a really simple process using Xamarin.Forms (I haven’t added Windows Phone here but i will edit this later) which requires only a basic knowledge of custom renderers.

We are going to create a map like this:


Project Setup

Create a new Forms project and add the Xamarin.Forms.Maps nuget package to the core PCL, iOS and Android projects. In the Android project you also need to set the following settings in the AndroidManifest.xml:

  • Access to the Network State – Maps API v2 must be able to check if it can download the map tiles.
  • Internet Access – Internet access is necessary to download the map tiles and communicate with the Google Play Servers for API access.
  • OpenGL ES v2 – The application must declare the requirement for OpenGL ES v2.
  • Google Maps API Key – The API key is used to confirm that the application is registered and authorized to use Google Play Services.
  • Write to External Storage – Google Maps Android API v2 will cache downloaded tiles to external storage.
  • Access to the Google Web-based Services – The application needs permissions to access Google’s web services that back the Android Maps API v2.
  • Access to Location Providers – These are optional permissions. They will allow the  GoogleMap class to display the location of the device on the map.

Call global::Xamarin.FormsMaps.Init() in both your iOS and Android projects at the the same point global::Xamarin.Forms.Forms.Init() is called.

PCL Custom Map Control

Now we have the basic requirements in place lets move on to writing a little code. Create a new class called CustomMapTiles like so:

 using System;
 using Xamarin.Forms.Maps;
 namespace CustomMapTiles
     public class CustomMap 
         : Map
         public string MapTileTemplate

We can now use this new control in a view, we also need to set the MapTileTemplate property.We can obtain this  by creating a new new project at MapBox.com.

This will give you a url like this:


In your new views Xaml add the new control as follows:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
<local:CustomMap x:Name="MyMap"

iOS Custom Map Renderer

Create a new class called CustomMapRenderer in your iOS project with the below code:

using System;
using Xamarin.Forms.Maps.iOS;
using Xamarin.Forms;
using CustomMapTiles;
using CustomMapTiles.iOS.Renderers;
using MapKit;

[assembly: ExportRenderer (typeof (CustomMap), typeof (CustomMapRenderer))]

namespace CustomMapTiles.iOS.Renderers
public class CustomMapRenderer
: MapRenderer

MKMapView mapView;
CustomMap customMap;

protected override void OnElementChanged(Xamarin.Forms.Platform.iOS.ElementChangedEventArgs<View> e)

if (e.OldElement == null)
mapView = Control as MKMapView;
customMap = e.NewElement as CustomMap;

var overlay = new MKTileOverlay (customMap.MapTileTemplate);
overlay.CanReplaceMapContent = false;
overlay.GeometryFlipped = false;
mapView.AddOverlay (overlay, MKOverlayLevel.AboveLabels);

mapView.OverlayRenderer = (mv, o) =>
new MKTileOverlayRenderer((MKTileOverlay)o);

Here we are using the url we added earlier to our control earlier and instantiating a new MKTileOverlay. We add this to the map and we are done with iOS..

Android Custom Map Renderer

Finally lets create a new class in the Android project called CustomTileProvider:

namespace CustomMapTiles.Droid.Renderers
public class CustomTileProvider : UrlTileProvider
string urlTemplate;

public CustomTileProvider (int x, int y, string urlTemplate)
: base(x,y)
this.urlTemplate = urlTemplate;

public override Java.Net.URL GetTileUrl (int x, int y, int z)
var url = urlTemplate.Replace("{z}", z.ToString()).Replace("{x}", x.ToString()).Replace("{y}", y.ToString());
Console.WriteLine (url);
return new Java.Net.URL (url);

Followed by a class called CustomMapRenderer again in your Android project:

using System;
using Xamarin.Forms.Maps.Android;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Xamarin.Forms;
using CustomMapTiles;
using CustomMapTiles.Droid.Renderers;

[assembly: ExportRenderer (typeof (CustomMap), typeof (CustomMapRenderer))]
namespace CustomMapTiles.Droid.Renderers
public class CustomMapRenderer
: MapRenderer
MapView map;
CustomTileProvider tileProvider;
CustomMap customMap;

protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Xamarin.Forms.View> e)

if (e.OldElement == null) {

map = Control as MapView;
customMap = e.NewElement as CustomMap;

var tileProvider = new CustomTileProvider (512, 512, customMap.MapTileTemplate);
var options = new TileOverlayOptions().InvokeTileProvider(tileProvider);

map.Map.AddTileOverlay (options);

Here we have the final running apps with custom map tiles:


Screen Shot 2015-02-16 at 11.18.15 pm


Screen Shot 2015-02-16 at 11.16.27 pm

You can find the code here:


February 16, 2015 7:21 GMT

Animate the Height of RowDefinition

When I first was faced with the requirement to create a kind of accordion-like area that open and closes by the click of a button, I thought to my self that that would be easy...

The solution was pretty easy, but accepting that the most simple solution didn't work was not.

The requirement was based on the image below. When you tap the surface titled "Tap me!" the red surface was going to animate it's height and disappear. I know I'm not going to earn any design awards from this! :)

Grids to the rescue!

I defined a simple three-row grid that gives the layout displayed in the image above.

xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 

            <RowDefinition Height="200" />
            <RowDefinition Height="*" />
            <RowDefinition Height="100" />

        <BoxView BackgroundColor="Red" Grid.Row="0" />
        <BoxView BackgroundColor="Blue" Grid.Row="1">
                <TapGestureRecognizer Command="{Binding Animate}" />
        <BoxView BackgroundColor="Yellow" Grid.Row="2" />

        <Button Grid.Row="1" Text="Tap me!" TextColor="White" 
            VerticalOptions="Center" Command="{Binding Animate}" />
        <Label Grid.Row="0" Text="I'm going to animate" 
            HorizontalOptions="Center" VerticalOptions="Center" />


Attempt one - binding to the height property

I then created a view model with a TopRowHeight property that I bound to the first RowDefinition.

 <RowDefinition Height="{Binding TopRowHeight}" />

This did not work at all. Even though the documentation states that the HeightProperty is bindable it simply does not call the getter. I tried returning an int, float, double and GridLength and any binding mode possible.

The solution - xaml

So what I ended up doing was to give the RowDefinition a name instead. For this example, it's important to keep the Height="200" since it decides what height to open up to again.

Height="200x:Name="topRow" />
            <RowDefinition Height="*" />
            <RowDefinition Height="100" />

The solution - ViewModel

And then a ViewModel that looks like the snippet below. Two things to note first before you bash my code.
  • The INotifyPropertyChanged-implementation is omitted. Use a base class or implement it in any real world example.
  • We take an Action in the constructor, this might not be so good in the world of IoC, but it's there to make for a simpler example.

    public class MainPageViewModel
        private Action _rowAnimation;

        public MainPageViewModel(Action rowAnimation)
            _rowAnimation = rowAnimation;

        public ICommand Animate
                return new Command((o) =>

The solution - The View

And then the actual implementation of the View (the page). What we do here is to create the MainPageViewModel and pass a reference of an Action that takes care of the animation of the grid row.

public partial class MainPage : ContentPage
        private Animation _animation;
        private double _initialHeight;

        public MainPage ()
            InitializeComponent ();

            // Since we can't use binding to animate the row height directly we
            // need to give the ViewModel a method to call when it wants to 
            // animate the row height.
            var model = new MainPageViewModel(AnimateRow);
            BindingContext = model;

            // Store the inital value so we know what to what height to restore to
            _initialHeight = topRow.Height.Value;

        private void AnimateRow()
            if(topRow.Height.Value < _initialHeight)
                // Move back to original height
                _animation = new Animation(
                    (d) => topRow.Height = new GridLength(Clamp(d, 0, double.MaxValue)),
                    topRow.Height.Value, _initialHeight, Easing.SpringIn, () => _animation = null);
                // Hide the row
                _animation = new Animation(
                    (d) => topRow.Height = new GridLength(Clamp(d, 0, double.MaxValue)),
                    _initialHeight, 0, Easing.SpringIn, () => _animation = null);

            _animation.Commit(this, "the animation");

        // Make sure we don't go below zero
        private double Clamp(double value, double minValue, double maxValue)
            if (value < minValue)
                return minValue;

            if (value > maxValue)
                return maxValue;

            return value;


You can download the example from here!
February 13, 2015 6:39 GMT

Xamarin Contest: Give Us The Gist Of It!

When developing, having the right snippets of code handy can give you back a huge part of your day. In this contest, we want you to give us the (GitHub) Gist of your favorite snippets to help your fellow Xamarin developers write amazing mobile apps even faster!

How to Enter:

  1. Create a Gist on GitHub with your favorite code snippet
  2. Tweet your Gist link and name of what your snippet does with hashtags #XamarinGist & #Xamarin
  3. Post your Gist to to this Forum thread
  4. Bonus points: Link a simple sample project that demonstrates your snippet

Need help with a Gist? Click here! Need a Gist template? Try this one:
Snippet Name: iOS Colors
Platform(s): Xamarin.iOS
Function: Hex value to UIColor


public static UIColor FromHex(this string hexValue)
int colValue = int.Parse (hexValue,
return UIColor.FromRGB(
 (((float)((colValue & 0xFF0000) >> 16))/255.0f),
 (((float)((colValue & 0xFF00) >> 8))/255.0f),
 (((float)(colValue & 0xFF))/255.0f));

Example Use:

//Set the text color of the label to 39FF3F.
lblTextResult.TextColor = "39FF3F".FromHex ();

Prize: Exclusive long sleeve Xamarin t-shirt!

5 entries will be chosen at random, so the more snippets you submit,
the better your chances of winning

All submissions must be made by Monday, February 23rd at 12pm EST. We will evaluate each snippet based on concept, code quality, and originality. A valid entry consists of a tweet, forum post, and the Gist of your Snippet. All submissions must be unique. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up. There is no purchase necessary to enter the Give Us The Gist of It Contest!

February 13, 2015 10:23 GMT

Manage the Windows Phone Theme

Wouldn't it be great if you could control the theme of your Windows Phone 8 (silverlight) app? Well, just install the PhoneThemeManager package from nuget written by Jeff Wilcox and add a single line of code to your app.


Read more about it at http://www.jeff.wilcox.name/2012/01/phonethememanager/. Oh, and it seems like the reference isn't added sometimes so just add a reference and drill down into the packages folder until you find the correct dll. In this case JeffWilcox.PhoneThemeManager.dll in the windowsphone8 folder.

Windows Phone 8.1 solves this by letting you request a theme by writing something like

    this.RequestedTheme = ApplicationTheme.Light;

in the constructor (or any other place) of your app.

Check out this article on Stack Overflow you more info!
February 12, 2015 11:58 GMT

Half a Year of Xamarin Weekly

That’s right; Xamarin Weekly just celebrated its 1/2 year anniversary. I know I can hardly believe it myself. Looking back, I can’t believe that I’ve been producing the Xamarin Weekly newsletter for half a year. Time has certainly flew by and the newsletter is getting to be more popular than I ever imagined.

The success of the newsletter would not have been possible without a great bunch of bloggers and writers. Thank you to all that have contributed and especially those writers and bloggers that have contacted me about their own blogs.

Subscribers by Month

Subscription rates have been pretty steady except for a little lull around Christmas and New Years. I can understand that.
On average, we are running over 120 signups a month. Within the next 6 months, we should have over a thousand subscribers.

Hot Topics

Like I said in the previous newsletter progress report, Xamarin.Forms is the hot topic. Xamarin.Forms articles are consistently clicked on more than any other topic.

When looking for newsletter material, I always look for posts that are longer than 200 words and have original content. Rehashes and mini posts are typically not published in the newsletter.  The one area the newsletter is lacking is in Xamarin.Android content. Hint, hint!

Open & Clicks

Running a newsletter is a learning experience and it’s ongoing. Open and click rates are important sign’s of a healthy newsletter. List cleaning is necessary and I’ve had to clean some non active people off the rolls, but not many. The newsletter’s open and click rates are good and I’ll make sure it stays that way by cleaning it off now and again.


To the 1 Year Mark

With the first 1/2 year squarely behind us, I have no doubt that the newsletter will make it to be a full year old. If you blog or know about a blogger that writes about Xamarin or Xamarin.Forms, please get in touch with me at adam [@] XamarinWeekly.com. I would love to get it in the newsletter.


The post Half a Year of Xamarin Weekly appeared first on Syntax is my UI.

February 12, 2015 3:45 GMT

Creating Your First WatchKit App

A new release of Xamarin’s Apple WatchKit support is now available for download, including initial support for the Xamarin iOS Designer. This post walks you through steps to create your first Watch Kit app (described in more detail in our WatchKit getting started guide).

File > New Watch App

Start with a new or existing iOS app, then add a Watch App. Xamarin Studio automatically creates both required projects: a Watch App and a Watch Extension.

Reference the Watch Extension

Before you can use the iOS Designer, or deploy and test in the iOS Simulator, reference the Watch Extension from your iOS app; and reference the Watch App from the Watch Extension.

Don’t forget to set the Bundle Identifiers correctly in each Info.plist.

Design the Watch UI

Double-click to open the Interface.storyboard in the iOS Designer.

Drag a Label and a Button onto the default InterfaceController. Don’t forget to give them a Name in the Properties pane (eg. myLabel and myButton).

Double-click on the button in the Designer to create a handler for when it’s pressed. Press enter to place the method in the code.

Just Add Code

Add the following code to the InterfaceController.cs file, which updates the label each time the button is pressed:

int clickCount = 0;

partial void myButton_Activated (WatchKit.WKInterfaceButton sender)
    var msg = String.Format("Clicked {0} times", ++clickCount);

Test in the Simulator

Ensure the Watch Extension project is set to be the start-up project, then select an iPhone 6 simulator and start debugging. Tip: use Bezel to see the simulator rendered inside an Apple Watch frame.


If you don’t see the simulated watch screen, select Hardware > External Displays in the iOS Simulator.

Video Walkthrough

You can also see the above steps on getting started with WatchKit in action in this short video:

Try it out today!

You can download our WatchKit Preview installers from the Xamarin developer portal (make sure you also have Xcode 6.2 beta 5 from Apple). Start with the WatchKit Preview guides and WatchKit samples.

Discuss this blog post in the Xamarin Forums.

February 11, 2015 10:27 GMT

iOS Tip: Change Status Bar Icon & Text Colors

When iOS 7 was introduced Apple allowed your application to extend all the way up into the status bar region. This was neat because you can scroll content behind it, change the color, and make the entire screen feel completely full. One thing that has upset me is that it isn’t really straight forward as to how to change the color of the time, carrier, battery, and other icons that live in the status bar. So here is my quick tips.

Launch Screen Colors

In general you can just hide the status bar at launch, but if you want the time to overlay on it you will need to head into your Info.plist file. You will find a Status Bar entry and you simply need to change it to Black Transparent and then it will display white text and icons:

Inside UIViewControllers

Now inside the UIViewControllers are a bit different. We first want to style the tint and the bar tint of the navigation bar. I am goign to set it to a blue background with a white tint. I do this in my FinishedLaunching where I create my UINavigationController in the AppDelegate:

navigationController.NavigationBar.TintColor = UIColor.White;

navigationController.NavigationBar.BarTintColor = UIColor.FromRGB(52,152,219);

Now were are getting closer, but still have 2 issues.

  • The text is black

  • The status bar icons and text are black

NavigationBar Text Appearance

To fix the text we head back to our AppDelegate and we have to update the “TitleTextAttributes” of our UINavigationBar.Appearance:

Status Bar

From my findings teh status bar on each UIViewController is actually controlled separatelly, which is very annoying. We must update the NavigationBar.BarStyle and set it to the BlackStyle to get the desired white text and icons. I do this on the ViewDidLoad method.

NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;

There you have it! A nice new themed iOS app. If you find a better way of doign this please let me know in the comments.

February 10, 2015 2:30 GMT

Article - Q&A: Xamarin's Jonathan Pryor on Android 5 Lollipop

Article Url:  http://visualstudiomagazine.com/articles/2015/02/09/xamarin-android-5-lollipop.aspx

Jonathan Pryor, a Xamarin.Android Development Lead, was kind enough to take some time out of a busy weekend to answer a few questions regarding Xamarin.Android and the company's support for the new Android 5 Lollipop update. Here's an interview conducted in late 2014.  At the end of this interview, I've also asked two fellow Android developers, Kevin Darty and Stephen Long, to chime in on their opinions of the new Lollipop features.

February 09, 2015 5:58 GMT

Building and Running .NET's CoreCLR on OS X

What you heard is true, Microsoft has open sourced the CLR and it runs on more than just Windows. They didn’t just dump some ZIP file on an FTP; no, we have another fully functioning, easy to compile, and easy to contribute to CLR hosted on everyone’s favorite file share. Microsoft has even gone so far as to setup a two way mirror with GitHub so that their internal systems stay in sync with what we see. Color me impressed.

Their initial release works on Windows and Ubuntu. That’s nice - definitely a good start - but I’m a Mac guy. Microsoft said they’re planning on OS X support in the future but haven’t gotten around to it just yet. I figured I would take a look at the CLR in some months when they had the chance.

Of course, once things go open source, they tend to get out of hand.

Enter systems programmer extraordinaire Geoff Norton. Geoff knows everything there is to know about the CLR. He worked for years on Mono - the original open source .NET - and has personal experience bringing it to OS X.

Well, if you did the trick once, you can do it again, right?

It all started when Geoff “had some time and made mac work”. Some time… Scanning through his PR, we can see the time went to:

  • Patching the build system to teach it that Linux isn’t the only Unix out there
  • Patching a lot of assembler directives as Mac’s as seems more strict than Ubuntu’s
  • Rewriting bits of high performance assembly in bytes (not opcodes) as Mac’s as refused to generate the desired instructions.
  • Tons of spot unicode changes to appease the LLVM gods

In all, it looks like a lot of high precision and tedious work and I want to thank Geoff for doing it.

It’s not perfect yet. I had to spend an hour with Geoff just to get Hello World printing and, as I write this, there are more bugs. But open source wins out in the end. I went to bed with a bug and woke up with its fix.

But enough preamble! Let’s get going: let’s build .NET, write a bit of code, and then run it.

1. Get the Code

This is the easy part, the CoreCLR is a git repo on github. You can fork that or grab Microsoft’s directly:

git clone git@github.com:dotnet/coreclr.git

You now have more than 2 million lines of sophisticated code (C#, C++, and ASM) for a sophistacated platform designed to make programming easy. I recommend a bottle of wine and a nice grep tool. But before then…

2. Get the Build Tools

CMake is used to build the Core CLR. I recommend installing it with Homebrew:

brew install cmake

In no time, you will have a hot little build tool.

3. Build It!

Yeah, seriously, it’s this easy:

./build.sh amd64 debug

Only amd64 is supported (which is fine, Apple dumped 32-bit like a hot potato), and we choose to do a debug build because it’s early days.

You should see Detected OSX x86_64 and then lots of colors.

Just watch the pretty colors go by for a few minutes. And don’t worry about those red lines; CMake decided, somehow, that red is a good indicator of success.

If you have that bottle of wine, now would be a good time to get some crackers or perhaps a vegetable platter…

4. Admire It

When CMake has decided that you are ready, it will greet you with an inoccuous message:

Repo successfully built.
Product binaries are available at /Users/fak/Projects/coreclr/binaries/Product/amd64/debug

We’ve waited nearly 15 years for this repo to successfully build, and now it has. My hat’s off to Microsoft’s CLR team that took the time to package this build so well. (I’ve downloaded single C files that were harder to build than this thing.)

Anyway, it has placed itself in a directory. Let’s go see what we got:

$ cd binaries/Product/amd64/debug
$ ls -al
total 46032
drwxr-xr-x  5 fak  staff       170 Feb  7 11:47 .
drwxr-xr-x  4 fak  staff       136 Feb  7 12:25 ..
-rwxr-xr-x  1 fak  staff     49836 Feb  7 11:47 corerun
-rwxr-xr-x  1 fak  staff  23503712 Feb  7 11:47 libcoreclr.dylib
-rwxr-xr-x  1 fak  staff      4176 Feb  7 11:47 libmscordaccore.dylib

Those magic colors produced 3 files:


corerun is a little driver that takes a managed assembly, initializes the CLR, then executes that assembly. It is the quivalent of the mono command but has a way worse name. This is the entrypoint for every managed app that you want to run on Mac.

We’ll look at its usage soon.


What would a code base be without an appendix? Something that doesn’t really belong, but someone thought would be really neat to include?

libmscordaccore is that. I’ve heard that it “helps debugging”, but at 4KB, I have my doubts. No, this is just an ugly wart growing off an otherwise prefectly packaged piece of software. Best ignore it.


This is it folks. The big daddy, the heavyweight, the superstar, the high muckamuckstar, the big enchilada.

libcoreclr is three things - a damned good garbage collector, a JIT, a type and metadata system, and a bucket of platform abstractions. OK, it’s a lot of things – all packed into one super sexy dylib.

Remember those 100 MB+ downloads of .NET? Remember how long they used to take to install? Remember how once you upgraded .NET on the machine, all apps had to use it?

No more. No more install. No more DLL hell. No more deplyment hell. You want .NET? Here is a single file (and its appendix) that can be deployed with rsync. Here are all the important parts of .NET in one library weighing in at 24 MB. Not since Silverlight has the CLR been packaged so nicely (and, AFAIK, this is a much more sophisticated CLR than Silverlight’s).

Take a sip of that wine.

You should now save The Book of the Runtime to your favorite Read-it-Later service. When you sober up from this experience, that document will be waiting for you - desperate to impart its decades of knowledge and wisdom on your “I’m too busy to study a runtime” adaled brain.

5. You’re Going to Need a String Class…

You might notice one thing missing from those three files: mscorlib.dll. That is to say, “where’s my String class?”

You see, while libcoreclr knows all about objects and types and how to manage them and keep them happy, it doesn’t actually have any. It’s heard rumors of types frollicking about, but it doesn’t have any to play with itself. It’s sad really.

While the CoreCLR repository contains all the code to mscorlib, it’s all written in C# and the CoreCLR doesn’t ship with a C# compiler! Because there’s no compiler, the build system can’t compile the standard library. It’s funny, in a not really funny kind of way.

The .NET team recommends using a Windows machine to build mscorlib with the command:

>build.cmd unixmscorlib

But, um, yeah, that’s cheating.

Enter, again, Geoff Norton. He has built that code and released it. Download mscorlib.dll from Geoff’s Dropbox.

Just drop it in with the three others:

$ ls -al
total 51776
drwxr-xr-x  6 fak  staff       204 Feb  7 12:34 .
drwxr-xr-x  4 fak  staff       136 Feb  7 12:25 ..
-rwxr-xr-x  1 fak  staff     49836 Feb  7 11:47 corerun
-rwxr-xr-x  1 fak  staff  23503712 Feb  7 11:47 libcoreclr.dylib
-rwxr-xr-x  1 fak  staff      4176 Feb  7 11:47 libmscordaccore.dylib
-rw-r--r--@ 1 fak  staff   2937856 Feb  7 12:34 mscorlib.dll

Congratulations, these four files combine to form a fully functioning implementation of .NET on OS X, courtesy of Microsoft and Mr. Norton.

(Some day we will have to contribute a script to CoreCLR that builds mscorlib with Mono’s compiler.)

I know you’re begging to run something, but let’s take a quick detour to show how to compile C# code using Mono on OS X.

6. Write Some Code

While we now have a fully functioning .NET, we need to give it something to run. If you have some assemblies lying around, they will do nicely, but let’s exam compiling code on OS X. We could use Microsoft’s compiler on Windows then just copy the assemblies over to OS X, but that’s cheating.

We will use Mono’s free C# compiler. Simply install Mono and it will be in your PATH.

Well you know what this is going to be… fire up your favorite editor and pump it out, HelloWorld.cs:

using System;

public class HelloWorld
    public static int Main (string[] args)
        Console.WriteLine ("Hello, world! From CoreCLR.");
        return 0;

Now compile it:

$ dmcs -nostdlib -r:mscorlib.dll HelloWorld.cs

The -nostdlib option tells the compiler not to automatically reference any of its known standard libraries (not just mscorlib, but others too). In this case, we’re just playing things safe by explicitely referencing whatever assemblies we need by hand.

We then reference our mscorlib with -r:mscorlib.dll. This is necessary because of the previous option.

Indeed we can see that the compiler did its job and we have an assembly all ready for execution:

$ ls -al *.exe
-rwxr-xr-x  1 fak  staff  3072 Feb  7 12:48 HelloWorld.exe

(Yes, we just used an open source project written as a free alternative to a closed source product to bootstrap said product when it became open source. The times we live in…)

7. Run That Puppy

$ ./corerun -c . HelloWorld.exe
Hello, world! From CoreCLR.


Sip of wine.

We use corerun to begin executing .NET code. The -c argument is used to point it at the working runtime (the two dylibs and mscorlib). Since I’m doing everything out of one directory, I just point it at . (pwd).

That’s it! We have now have a fully functioning toolchain to compile and execute .NET code on sweet sweet OS X.

8. Contribute Back

Now let me warn you: this port to OS X is literally days old and contains known bugs. You cannot and should not release software using it.

If you are a systems engineer - or want to learn what it takes to be one - dive into that code. Try running your app, note the crash, and then load lldb. Chances are you will be lost, but you will be lost in a fantasic place full of mystery and possibility.

Then come hang out at https://gitter.im/dotnet/coreclr. We’ll be chatting about all things coreclr and especially how to make the stupid thing stop crashing. ;-)

Thoughts on the Future

The CoreCLR is an oddity in my mind - I don’t know quite where to file it away.

We have had a high quality open source implementation of .NET on OS X for years now. I even make my living writing apps using it. I have spent the last 5 years learning it: its quirks and its powers. In addition to the technology, there is an amazing developer community that has grown up and matured around it for more than 10 years.

Microsoft can’t just drop a bunch of code on GitHub and expect a community to grow up around it (as nicely packaged as it is). Indeed, I’m not sure they want one to. Managing a community is a hell of a lot harder than managing pull requests. Higher management at Microsoft seems too concerned with Azure to care what non-Fortune 500 companies are doing with their wares. And, to be honest, that’s fine.

In the short term, Microsoft will continue to contribute to the CLR with their incredible programming and testing skills - we will marvel as they make precision changes to complex C++ code. The open source community will continue to pop up when they break something in our precious platforms or we decide that it’s time to do something novel and incredible with this little gem.

That is to say, for now, this is still Microsoft’s CLR. I am curious to see if it ever becomes ours.

February 09, 2015 11:39 GMT

Don’t Re-Invent the Wheel: Use Components or Plugins In Your Apps

Xamarin provides native, cross-platform mobile application development using language we all know and love – C#. However, it is still required to learn concepts of each platform. For example to send text message (SMS) in all these three platforms there are different set of APIs.

Below API is for Android, which uses SmsManager to send the text message. There is another way to do this using Intents.


In case of Windows Phone, ChatMessage allows us to declare and send text message. This API is available in WinRT platform. In case of SL based apps, we need to use Launchers/Choosers.


In case of iOS as shown below, there is no API as such. But we use URL to launch default messaging app. In this case, we cannot set the message body, which we want to send out.


Life will be much simpler if there will be just one API on all these platforms which will take care of sending text messages and as I developer we don’t need to bother about on which platform it is being called. Here comes components and plugins. My friend James has written a nice blog about ‘What Exactly is a Plugin for Xamarin?’. You can read it here

In our case, we’re going to use Messaging Plugin for Xamarin and Windows which allow us to use same API to send text messages. Below code is written once in a Xamarin.Forms project which depending on platform on which code is executing, send the message using that platform’s APIs.


Using this plugin, it becomes easier to send text messages on Android, iOS and Windows. And this is the magic of Plugins for Xamarin.

In future posts, we’ll cover some of the best plugins and components which can help you build cross-platform mobile applications with single code-base.

I hope you’ve enjoyed this.

Mayur Tendulkar

February 08, 2015 7:26 GMT

Pay: The most secure form of payment

Big Nerd Ranch have a good article up about how ApplePay works, and why it's the most secure method of payment available.

The cryptogram is a layer of security in which part of it is dynamically created per transaction; it links the token to the device and that particular transaction. Tokens can never be used without an accompanying cryptogram and the cryptogram ensures that the token can only be used from the device in which it was originally linked.

The important fact here is that the retailer never has possession of your actual credit card number in any part of the transaction. That is a distinct difference from the credit card magnetic swipe we have today, where the exact credit card number is unmasked and sent directly to the retailer’s point-of-sale system. This is the weak point where hackers have intercepted credit card numbers at Target, Home Depot and others.

Important things to note here:

  • Apple doesn't store your credit card number anywhere. It's ONLY stored in the secure element of your phone. This is not the case with Google Wallet.
  • The merchant doesn't get a copy of your card number, expiry etc. This makes it both more secure, and gives you better privacy as the merchant can't track your spending habits by card.

The last one is also the case for normal NFC payments, too, but it's good to reiterate it. The article is a bit "OMG security" from an American point of view, but as they are maybe 20 years behind the rest of the world, I think thats fair enough.

February 06, 2015 2:29 GMT

Xamarin Weekly Newsletter Issue #26

Join Xamarin at IBM InterConnect 2015
Rob Ross, from Xamarin Inc., announces Xamarin is going big for this IBM conference.

Share UI Code Across Mobile Platforms with Xamarin.Forms
Jason Smith on MSDN Magazine shows off Xamarin.Forms and sharing code between the platforms.

AutoMapper support for Xamarin Unified (64 bit)
Jimmy Bogard pushed a prerelease package of AutoMapper for Xamarin Unified with 64-bit support for iOS.

A Sharper Way to w=Work with Xamarin Forms
Ken Ross gets all sharp and productive with his Xamarin.Forms.

Xamarin Android Gridview With Infinite Scrolling
John Wilson fits thousands of rows of dynamic content into his GridView.

300 Components and Counting
Bill Holmes, from Xamarin Inc., is happy to announce that the Xamarin Store has over 300 components.

What’s New in Xamarin.Forms 1.3 webinar recording
Did you miss the webinar? It’s not a problem, watch it now with this recording.

Xamarin Forms Kickstarter – Update
Learn how to access the native camera from within Xamarin.Forms.

Announcing the Xamarin.Forms Book Second Preview Edition!
Craig Dunn, from Xamarin Inc., announces the second preview of the Xamarin.Forms book.

Making Sense of iOS Provisioning
Ruben Macias explains that one simply does not debug iOS apps without provisioning profiles.

Xamarin.Forms and Design Challenges
Marcos Cobena flexes his Xamarin.Forms animations to copy Twitter’s start screen.

Get device unique identifier in Xamarin Forms
Corrado Cavalli gets all unique on us in Xamarin.Forms.

Video: Brett Favre-Backed Sports App Scores Big with Xamarin
Jo Ann Buckner, From Xamarin Inc.,shares another Xamarin success story.

Mobile Development Platform Performance Part 2 
Kevin Ford performs more test with our favorite framework and the competition.

Force iOS, Android, & WP to Landscape
James Montemagno, from Xamarin Inc., answers a quick question about only supporting specific orientations in Xamarin.Forms.

Xamarin named one of “26 enterprise startups to bet your career on in 2015″ by Business Insider
We knew Xamarin was a good bet.

Animations in Xamarin and Xamarin.Forms
Josue Yeray Julian Ferreiro shows off some Xamarin and Xamarin.Forms animation.

The post Xamarin Weekly Newsletter Issue #26 appeared first on Syntax is my UI.

February 02, 2015 2:12 GMT

Byte array is empty when fetching using Xamarin Forms 1.3 and XLabs 2.0

I stumbled upon a small "bug/feature" after updating a Xamarin.Forms app to 1.3 and XLabs 2.0. The small snippet of code below is called after a pictures is selected or taken.

Photo is a ImageSource that belongs to the ViewModel for the View. I also needed the raw bytes later on so I simply used the Read method of the stream returned.

After the update the bytes-array was simply set to 0 for each byte in the array until I reset the position before the read. No exception, simply just empty.

    Photo = ImageSource.FromStream(() => mediaFile.Source);
    var bytes = new byte[mediaFile.Source.Length];
    mediaFile.Source.Position = 0;

    mediaFile.Source.Read(bytes, 0, (int)mediaFile.Source.Length);

Have a nice day!
January 31, 2015 9:27 GMT

10ish Cool New Products

What follows are products I’ve recently discovered, that now I can’t live without.

Back Pack

Let’s start with the best backpack I’ve ever owned

This is the Cocoon, which sells for about $100.

There are two main pockets. TCocoon pockethe larger has a suspended pocket for your Mac (or if you insist, your Lenovo ) and a second one for your iPad (Surface?).

The outer pocket is where the magic happens.  There are criss-crossed strips of expandable nylon that securely hold everything from your USB stick to your power supply, iPhone or anything else you carry.  It makes finding the wire you need right now, a snap.

Run out of room? They also sell rectangular supplements that do the same, but slip into your backpack, for the stuff you use less often.


I’ve had a number of scanners. They all fail in one way or another, except the Evernote ScanSnap.  First, let me point out that while you can scan directly to Evernote, you don’t have to, you can scan to file and/or you can scan to other similar products such as Eagle Filer (see below).  Scan Snap

Among the great features of this scanner are that it works on your wifi, it automagically detects single sided or double sided documents, can handle documents of different sizes (down to business cards), can differentiate a document from a receipt from a business card and most important, it is fast and it works, reliably, every time.


Next in my effort to get organized are two programs that integrate into most mail programs seamlessly.  The first is SpamSieve.  This eliminates spam using Beyesian logic combined with  “white-listing” anyone in your contacts, or anyone who you “mark as good.”  You can, if you want, look at why a message was allowed or blocked and carefully tweak the algorithm but it isn’t necessary, SpamSieve gets it right, nearly always.

The second is SaneBox.  This incredible and wonderful program looks through my mail and separates my mail into my Inbox, SaneLater (mail that can wait) and SaneNews. SaneMail

There other choices as well.  There are also snooze mailboxes, such as SaneTomorrow and SaneNextWeek, and you can make custom snooze mailboxes.

Training SaneBox as to who is important and who is not is a snap.  Drag an email from SaneLater to your Inbox and that sender will always show up in your Inbox, unless you override that on your dashboard.  There’s much more, but this is truly a great organizer that helps you get through your mail quickly

Before you go, this looks suspiciously terrific. They advertise themselves as a free service that you provide with accurate and out of date contact info from you address books and they anonymize that data with their half billion entries, cook lightly with AI and then return current, completely up to date records back into your address book.   Caveat: I’ve not used this enough to know if it works, and if it is really free, but looks pretty good.


In sheer productivity increase, YouMail (stupid name, great product) is the hands down winner.  This wonderful phone call manager lets you set your greetings and block numbers YouMailfrom telemarketers. In fact, it can give telemarketers a message that says  your phone is no longer in service.

It transcribes messages  and emails them to you.

Your message can be automatically personalized (using your contact list) and can be informal, business like or comic.   For example, here’s my business greeting.

What is even nicer, is that with YouMail you get an extra phone number, which you can give out appropriately, that does not ring your phone but goes directly to voice mail.


I love Evernote and have over 1200 notes, so switching to anything else, even OneNote, is out of the question.

That said, I’ve started using EagleFiler, which does, more or less competes with Evernote, but is really more of a document manager.  Drag just about anything in and find it fast when you need it.  Great way, for example, to archive your email.

EagleFilerOne thing I really like is that it will present a small box on your screen (See image on left) that you can drop documents on to, and hey! Presto! They are in EagleFiler.




Text Expander is one of the best “auto hot key” programs I’ve seen. I under utilize this program, but it is very powerful.  For me, so far, it is enough to have it take short acronyms and expand them into anything I want.  It also has long lists of auto-corrects which it does automatically as you type.

Along with Text Expander, I’m experimenting with Alfred and with Keyboard Maestro.  I’ll get back to you when I know more about these.


I’ll write a proper write-up of iPhone apps I love, but here is the short list of the ones I use every day or find particularly useful (in no particular order):

  • Fantastical (calendar app)
  • Meds, track your health info
  • Event Board (made by Falafel) for conferences
  • Audible
  • Kindle
  • Evernote
  • YouMail
  • Threes (very addicting)
  • HootSuite
  • Skype
  • Netflix
  • ShowTime
  • YouTube
  • IMDB

And that doesn’t include the apps that come with the iPhone, such as Podcasts


January 31, 2015 11:54 GMT

Philip Hue

You may know me as a Developer Evangelist at Xamarin but in a previous life I worked for a lighting control manufacturer based in London developing embedded lighting controllers. These devices are installed all over the world and run some of the most advanced architectural lighting installations ever conceived.

Below is a video of one of the many interesting installation I programmed. This installation in particular was at London’s One Hyde Park. This section of the installation consisted of 90 universes (1 universe contains 512 control channels. Normally the lights are simple RGB fixtures and so only require 3 channels for each ‘pixel’).


Lighting control for the most part has standardised on DMX for the best quality. Philips and the home automation world has opted for to use the ZigBee protocol instead. Currently ZigBee is competing with the Dali protocol which seems to be loosing the battle when we look at the number of devices being made that support each protocol. Both these protocols are fairly limited in the refresh rates which make them less than ideal for creating high quality fades. If we look at the DMX protocol, it refreshes 44 times a second allowing for fine resolution fades to occur. ZigBee on the other hand limits you to only controlling 1 light at a time. If you’re only controlling 1 Hue lamp, you can achieve a respectable 30 updates a second. The problem occurs when you scale and add more lights. It can take up to 2 or 3 seconds for each update to send which makes it impossible to have a controller provide high resolution fades.

If we ignore the awful refresh rate of Philips Hue and hope that they’re working on an radial departure for v2, we’ve still got the issue of HomeKit support. Philips have been very quiet of late about HomeKit support despite being one of the big names touted on the original announcement back in June. The problem Philips face is that each fitting already installed in your home is locked to the original Hue bridge it first connected to. This means you can’t replace the bridge without replacing your lights. You also can’t buy used lights off eBay as they wont work if they’ve already be linked to another bridge. This means they can’t easily ship a new bridge to support HomeKit.

Most people are in agreement that Philips will release another accessory which plugs into your network and enables HomeKit support with your existing bridge and fittings. If this is the case then I can see a number of early adopters being unhappy at having to spend more money on adding something that most assumed would be enabled in a firmware update.

At this moment in time I couldn’t recommend anyone to run out and purchase Philips Hue. I would instead hold off until confirmation on what the story is for this new product. If you’re happy with the current functionality, you don’t want high resolution fades and you’re happy with the HomeKit situation then it might be a great fit for you. I’m going to hold off extended my collection for a few months and see what changes (hopefully HomeKit support!)

The post Philip Hue appeared first on Mike James.

January 30, 2015 11:08 GMT

Hi, I’m James, Developer Evangelist

I have been a .NET developer for over a decade and worked in a wide variety of industries including games, printer software, web services, and more. A little over three years ago I decided to move my entire life from Phoenix, AZ to the most wonderful place in the world Seattle, WA for a brand new job. That new job was to be the lead and only mobile developer at Ceton. My first assignment was to create a series of mobile apps to pair with their DVR hardware and Windows Media Center (Microsoft’s ahead of its time DVR software). These mobile apps of course had to run across all platforms from iOS, Android, and yes even Windows. At that point in my life I only knew C# and had only made one mobile app in my life and it was for Windows Phone. Android, iOS, Java, Objective-C… I had no idea. That is when I found the Xamarin Platform, which enabled me to re-use my C#, .NET, and IDE skills to create beautiful native apps for all of these platforms.

My time at Ceton was awesome and I created a plethora of apps that I am extremely proud of and have tens of thousands of downloads (which is great for a $5 app targeted at Media Center users).

After two years, it was time for a change when I got a phone call from Xamarin asking for me to interview for a Developer Evangelist role. It has been over a year since I joined Xamarin, and I still get questions about what I actually do for a living, so I wanted to take some time to actually describe what a Developer Evangelist at Xamarin is all about and what we do.

What is Xamarin?

This has to be the number one question that I get asked no matter where I am at in the world, and it is one that I have no problem answering and explaining each and every time. This is the core of my job, regardless of wheter I am actually explaining or demoing live code at a coffee shop or a conference, webinar, or developer group. To be honest with you, this is the easy part of my job because I absolutely LOVE the Xamarin Platform. Having been a Xamarin developer for over two years who fell in love with the platform means that I get to show developers my passion for mobile development, something that I love, and think is absolutely unbelievably amazing. Hopefully you will think it is amazing as well :)

Travel & Make Connections

Even though I live in Seattle, I actually spend about half the year away from this beautiful city. I know just about every airport, am comfortable with hotel gyms, and have racked up more Southwest Rapid Rewards points than I know what to do with. Even though I believe everyone should fly to see me in Seattle, I know it is much easier to come to you, and that is something that I couldn’t be happier to do. The great thing is that through this travel I’ve created connections with amazing developers all around the world that I know will last the rest of my life. Locally here in Seattle I have the honor of co-organizing the Seattle Mobile .NET Developers group with one of my best friends, Frank Krueger, which has been an extremely memorable experience.

If I was able to share a few highlight from the year I have to mention getting the chance to meet some of my all time heroes like Scott Hanselman (and the creation of the Hanselman app) and Laurent Bugnion the create of MVVM Light that I had the chance to sit down and discuss Xamarin support for the framework. But of course there is our amazing community including all of our amazing Xamarin MVPs. At Philly Code Camp I had the honor of presenting side-by-side both Brent Schooley and Greg Shackles, which was an absolute blast. Between Evolve, online, and all my travels I have meet so many people that I wish I could list them all: Ryan Hatfield, John Lyon-Smith, Jan Hannemann, Seth Valdetero, Alec Tucker, Beth Massi, Chris Riesgo, Paul Batum, Tomasz Cielecki (The Cheesebaron!), Paul Betts, Nick Landry, and SO MANY MORE!

The easiest way to get a hold of me is via Twitter via @JamesMontemagno. I seem to always be on and have had some of the best 140 character coding conversations ever (although usually they involve GitHub and some Gists).

Of course can not forget my entire Xamarin family, who it is truly an honor to be able to work side by side each and every day. Thanks to Craig Dunn I am now addicted to waffles that I must have each and every time I am in San Francisco.

Present, Present, and Present More!

You may be surprised to hear this, but before I started at Xamarin I had only ever professionally presented once in my life. But last year I presented over 120 times! Many of these presentations are the same, however I like to mix things up. This means if you see me present and see me again presenting the same presentation even the next day, it will be a brand new experience. I handcraft all of my slide decks (aka, I am a PowerPoint pro now) and all of my demos as well. With mobile platforms and the range of products that Xamarin now offers, there is so much to present that it is hard to keep up — but that is the fun part.

Here are just a few badges from 2014!

Build Awesome Libraries, Apps, and Samples

Have you seen my GitHub lately? It is filled with every single sample, library, and app that I have created since I started at Xamarin. One of the best aspects of my role is that I am always learning, trying the latest APIs, and still building full apps that I ship! It is a special feeling though to be able to give so much back to the community.

Write Words

I have been blogging since I first got my hands on a computer around the age of twelve, and it is one of my main responsibilities here at Xamarin. Not only do I fill the Xamarin Blog with a flurry of technical blog posts, how-tos, and even press releases, but I also have my own development blog where I write even more about how to do awesome things with Xamarin. Since I am an Android fanboy, that is probably what you will see the most over there, but often if you ask me a question on the forums or twitter then it might just turn into a blog.

Work With Amazing People

What keeps me going each and every day is the incredible people that I get to work with each and every day here at Xamarin. Even though I work at home here in Seattle, I have never felt so connected to a group of individuals in my life. When I show up in Boston or San Francisco, it is hugs and high fives all around — and that is a special feeling as we are one big family. To top things off, I get to work with and have some of the best conversations with the cofounders of Xamarin: Nat Friedman, Miguel de Icaza, and Joseph Hill. I could not talk highly enough about these three individuals and I am honored to have the opportunity to work side-by-side them each and every day.

Joseph Hill

Joseph Hill, Director of Developer Relations and Cofounder of Xamarin, gets his own special section because he is my boss. I have never worked under a more hard working, honest (sometimes a bit brutally honest in a Louis CK way, but I appreciate that), funny, and all around amazing person in my entire life. I am not just saying this because he is my boss, I am saying this because it is true. When it comes to what Evangelism is and our priorities at Xamarin he completely gets it and we are completely synced on our goals. I talk with Joseph more than anyone in my life currently and it is lovely. I wouldn’t have it any other way.

Join Me!

So, that is what I do as a Developer Evangelist here at Xamarin. Now, that brings me to you! Yes, YOU! If you have read through this thought wow that sounds unbelievably awesome and you yourself are unbelievably awesome then you could come join our Evangelism team here at Xamarin. We have a few roles open right now for not only a full time Evangelist on the East Coast, but also a Community Intern in Boston that gets to work directly with the Evangelism team and with our crazy amazing Community Manager Jayme Singleton! Join me on this awesome adventure and take a look at our other awesome opportunities!
January 30, 2015 8:27 GMT

Force iOS, Android, & WP to Landscape

During this weeks Xamarin.Forms 1.3 webinar I received an interesting question about how you can force your mobile applications to always use a specific orientation. This is actually easy to accomplish on each platform with just a few settings in each project. Let’s take a look:


First thing to do is open up your MainActivity.cs file. At the very top you will see an [Activity] attribute. This attribute is used to describe your activity to the AndroidManifest file that is built for you automatically. It is worth taking the time to look into all of these settings on the Google Documentation site. However, what we will want to add here is a new settings called ScreenOrientation and set it to landscape:

ScreenOrientation = ScreenOrientation.Landscape

So your entire Activity attribute would look like this:

[Activity(Label = “App4”, Icon = “@drawable/icon”, MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape)]


iOS is actually extremely easy to change. Simply right click on your project and go to properties. This will bring up all of the settings for your iOS application and you will want to click on iOS Application, which is a visual representation of your Info.plist. You will see Supported Device Orientations, and you just need to turn off Portrait and you are all set.

Windows Phone

Our last platform will be Windows Phone, which is also easy to get into landscape mode. Open up your MainPage.xaml first and you will see two properties called




Let’s set both of these to Landscape. Additionally, Xamarin.Forms adds a bit of code into the MainPage.xaml.cs uder InitialzeComponent();, which you need to DELETE:

SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;

There you have it! Now your app is always in landscape mode. Here is a video if you want a full walk through:

January 30, 2015 4:13 GMT

Changing from Map property to GetMapAsync() on MapFragment

Recently the Map property on the MapFragment was marked obsolete. Instead, we now have to use the GetMapAsync() method. However, that method expects a callback object. Hence, we need slightly more code to not have our code use obsolete stuff.

For the callback we need to implement the IOnMapReadyCallback interface, which simply has a method which gives us the GoogleMap instance.

As you can see I simply implemented that interface, and as all interfaces coming from the Java world which expects a Dispose() and Handle implementation we need to inherit from Java.Lang.Object. I also added an event to that class instead of passing a reference of my Fragment into that class.

Now you might be using the SetupIfNeeded() method which Xamarin also uses in their samples and is called in OnCreate() and OnResume() and where ever you feel like it. For that purpose I have adapted that to use the callback class.

January 30, 2015 2:26 GMT

Xamarin Weekly Newsletter Issue #25

Xamarin Forms Navigation–Dealing with Login
Morgan Skinner wrestles with adding login to his Xamarin Forms app.

Enabling Xamarin.Forms with MVVMCross on Windows Phone
Marcos Cobeña, from Plain Concepts Inc., finds a huge win when using Xamarin Forms with MVVMCross.

Xamarin Forms StackLayout Recipe
I (Adam) show my love for pancakes and the Xamarin Forms StackLayout.

A Xamarin.Forms Infinite Scrolling ListView
Matt Whetton shows off Xamarin Forms extensibility with a new custom renderer.

Xamarin.Forms Kickstarter – Update
Falko Schindler, from Perpetual Mobile GmbH, has added a small XAML sample to the online book.

Xamarin F# – Experience Report
Faisal shares his experience using F# with Xamarin on mobile.

Ninja Coder for MvvmCross and Xamarin Forms
Check out this Visual Studio Addin to aid in the development of MvvmCross and Xamarin Forms solutions.

Raygun for Xamarin.iOS supports Unified API and native error reporting
Jason Fauchelle, from Raygun.io, announces Raygun4Net has been updated to the Unified API.

Jenkins CI with Xamarin.iOS, Xamarin Test Cloud and TestFlight – Part 1
Jeffry van de Vuurst is getting things automated with his continuous integration.

Xamarin Forms Contacts Search
Morgan Skinner searches his contacts and uses behaviors in his new Xamarin Forms app.

Xamarin MVPs Expand with More Awesome!
Joseph Hill, from Xamarin Inc., added some well deserved recognition to some amazing community members.

View Controller Lifecycle
Adam Kemp clears up what might trip up new developers to iOS.

Android Tips: Hello Material Design v7 AppCompat
James Montemagno, from Xamarin Inc., shows off how you can add Material Design to any of your Android apps.

Unified API Migration Example with the Dutch Spelling App
Michael James, from Xamarin Inc., converts his Dutch Spelling app to the Unified API. The code is available on GitHub.

Genymotion Android Emulator
Josh whips his favorite Android emulator into shape.

Working New Android 5 Lollipop Features into Your Apps
Wallace McClure gives you a dose of sugar in this new post on Visual Studio Magazine.

Simplify Using Xamarin.Auth with Async Tasks
Jim Wilson is making our lives better with this Twitter authentication sample.

New at Xamarin University

Hey everyone, my google minions are now monitoring the Xamarin University course page for new and updated courses. If you’re new to C#, this class might be helpful.

Debugging and Exceptions [CSC108]
New! Humans are involved in the programming process, and as a result, often introduce errors in the programs they write. In C#, these errors are often discovered through exceptions, crashes and logic issues. In this class we will explore the exception model used in C# and the debugging tools available in Xamarin Studio to isolate, identify and fix these errors.

Next Week’s Meetups

January 29: Connecticut Mobile C# – Kickoff meeting

January 31 : Malappuram , Kerala, India :App Fest 2k15

February 3: Seattle, WA: Developing for Android Wear with Jérémie Laval

February 5: Chicago, IL: Diving into Xamarin.Forms

February 5: Barcelona, .NET Mobile Developers Group, Go Mobile with C# and Xamarin


Don’t miss out! Subscribe Today

Do you blog about Xamarin? Get your blog in the newsletter.
Email me at adam [at] XamarinWeekly.com.

The post Xamarin Weekly Newsletter Issue #25 appeared first on Syntax is my UI.

January 29, 2015 7:54 GMT

Working New Android 5 Lollipop Features into Your Apps

Url: http://visualstudiomagazine.com/articles/2015/01/01/new-android-5-lollipop-features.aspx

Who doesn't love some sugar? Android 5, code-named "Lollipop," is Google's latest release of the Android OS for phones, tablets and wearable devices. There are a large number of new features, some you should be aware as you develop apps going forward:

  • Material Design and UI controls and capabilities. Material Design is a bold, colorful, and responsive UI design for consistent and intuitive experiences across all devices. This includes responsive, natural motion, realistic lighting, shadows, and visual elements that make it easier for users to navigate on their device, and new colors, typography, animations, and edge-to-edge imagery assistance to focus user attention.
  • Notifications. The new Notifications provide ways to control when and how users receive messages. Users are able to view and respond to messages directly from the lock screen as well as hide sensitive content for these notifications.
  • New runtime and performance improvements. ART is the new Android runtime (replacing Dalvik). Let's be honest -- who hasn't had problems with a poorly performing app in Dalvik on some device? I know that my Nexus 7 2013 seems to have problems. Over time, I find that apps run slower and slower until a reboot resolves that problem. ART improves application performance and responsiveness.
  • 64 bits. Apple released 64-bit support in iOS in the fall of 2013. The competitive marketplace requires that Android does likewise. With Android 5.0, Google supports the current 32-bit ARM architecture, as well as 64-bit chips from ARM, x86 and MIPS.
  • Accessibility. I have a large number of users at one of my clients that have accessibility issues. Given the vision problems that they have, I personally feel that it's important to make their interaction with my applications work as well as possible. Previously, Android hasn't done a good job in this area. With Lollipop, Android has improved accessibility.

These are some of the high-level improvements in Android 5, but there are many more. Clearly, one article cannot do justice to an update of this magnitude.

This column will focus on one of the new controls in Android 5. Let's get started!