November 24, 2015 4:46 GMT

Introducing Xamarin Evolve Student Scholarships

Xamarin already makes it incredibly easy for students to become cross-platform mobile C# developers – through our integration with Microsoft DreamSpark, you can get started with Xamarin for free with a single click.

Evolve 650__x__178__blog (1)

Today, I’m excited to announce that we are extending our student programs to include scholarships sponsoring full conference and training registration for Xamarin Evolve 2016 – the world’s largest mobile cross-platform developer conference, coming April 24-28 in Orlando, Florida. Experience world-class training from mobile experts, hack on tech toys in our Darwin Lounge, and network with potential employers.

Apply Today

Xamarin Evolve 2016 is the place to be if you are a student interested in mobile development. There are very limited scholarships available, so apply today:

Apply Now

All submissions must be made by Monday, February 1st, 2016, at 12PM EST. To be eligible, students must be actively pursuing a degree and enrolled in a degree or diploma-granting course of study at an accredited college, university, or high school.

Make Your Application Stand Out

Tens of thousands of students have already developing with Xamarin, but we only have a limited number of scholarships to award. To increase your odds of being selected, do any or all of the following:bookshelf

After completing the application for a student scholarship to Xamarin Evolve 2016, be sure to download Xamarin for free today through our integration with Microsoft DreamSpark. We can’t wait to see all of the amazing entries, and to see you at Xamarin Evolve 2016!

The post Introducing Xamarin Evolve Student Scholarships appeared first on Xamarin Blog.

November 23, 2015 6:50 GMT

Getting Started with Xamarin.Forms 2.0’s Windows 10 Preview

With the release of Xamarin 4 came Xamarin.Forms 2.0, introducing new features and optimizations to help you build great native cross-platform mobile apps. In addition to ListView caching strategies, pinch gestures, and new properties came the first public preview of Xamarin.Forms for Windows 10 (UWP) applications. While Xamarin.Forms already supports Windows Phone and Store targets, Windows 10 introduces an Universal Windows project that can target both desktop and phone platforms, allowing you to easily target even more devices.


Getting Started

Before you begin creating Universal Windows 10 apps with Xamarin.Forms, there are a few prerequisites that need to be installed.

Once you have everything installed, it is time to get your Xamarin.Forms project ready. Xamarin.Forms 2.0 not only adds preview support for Windows 10 apps, but also add a plethora of additional features, optimizations, and awesome for your mobile apps. To get started, head over to the NuGet Package Manager in Visual Studio.

Manage NuGet Packages

Select the “Upgrade available” filter and update all of your NuGets to Xamarin.Forms 2.0.


Note: Visual Studio may prompt to be restarted after this step.

Adding the Universal Windows App

Once all your NuGets are up to date, it is time to add a Blank Universal Windows project to your Xamarin.Forms solution. This can be found under Add New Project -> Windows -> Universal -> Blank App.

UWP Project Template

Add NuGets & PCL/Shared Project Reference

When you create a new Xamarin.Forms project, all of the references and NuGet packages are automatically added for you. However, for existing Xamarin.Forms projects that want to target UWP as well, you must add them in manually. First, add the Xamarin.Forms project. Right click on the solution and find “Manage NuGet Packages…”, and from the filter dropdown select “Installed”. Find Xamarin.Forms, and check the UWP project to install the same version of Xamarin.Forms into your UWP app.

Add Forms to UWP

Now, add your shared code that contains your Models, Views, and ViewModels. Inside the UWP application right-click “References”, and select “Add Reference”. Under projects, you will will find all of the projects in your solution. Find your PCL project or shared project, check it, and click OK.

Reference Manager

Update App.xaml.cs

All Windows apps have an App.xaml for application-level configuration. Just like a Xamarin.Forms XAML page, this page also has a C# code behind file for lifecycle events. Open it up and you will find an OnLaunched method.

Find the following line of code:

rootFrame.NavigationFailed += OnNavigationFailed;

and add the Xamarin.Forms Init call:

Xamarin.Forms.Forms.Init (e);

Update MainPage.xaml

Open up MainPage.xaml of the Windows 10 app and remove the default “Grid” that was created for you so that the page is now completely empty. Next, add a new namespace in the XAML and change the Page to be a Xamarin.Forms Page:

Update MainPage.xaml.cs

Update the code behind file to initialize your Xamarin.Forms app:

public sealed partial class MainPage
  public MainPage()
    LoadApplication (new YOUR_NAMESPACE.App());

Replace YOUR_NAMESPACE with the namespace that is found in your Xamarin.Forms Application class, which is usually located in your shared code under App.cs.

Configure App to Deploy

Sometimes Visual Studio may not set new project to build and compile by default. To ensure that it does, right-click the solution and open up the Configuration Manager. Check the UWP app to build and deploy, and you are all set!

Configuration Manager

Add images assets and any other NuGets

The last step is to simply add any image assets or add back in any NuGet or Plugins for Xamarin that you may have as a dependency. Be sure that any of these dependencies have also add Windows 10 (UWP) support for compatibility.

Learn more and provide feedback

To learn more about all of the new features in Xamarin.Forms 2.0 be sure to read through the release notes. You can check out the full source code for the weather sample application shown above on my GitHub. Windows 10 (UWP) support is in preview, so there is a possibility that you may run into some rough edges. To help make Xamarin.Forms for UWP amazing, please be sure to leave feedback by filing an issue if you experience one.

The post Getting Started with Xamarin.Forms 2.0’s Windows 10 Preview appeared first on Xamarin Blog.

November 23, 2015 12:00 GMT

How Visual Studio builds on the Mac with Xamarin

When we started working for Xamarin as consultants, a couple years ago, it was nothing short of amazing for us that Xamarin had already achieved a pretty solid “F5 experience” with an app building on the Mac and debugging like any regular local .NET app. I had the same feeling the first time I did the same thing against an Azure website. Felt like magic (in the Arthur C. Clark way).

During the past year and a half since the we joined Xamarin, we iterated (among other things) on this key component of the developer experience, culminating in our most recent release, Xamarin 4. What started as a (more or less) batch process of “zip sources, HTTP post to Mac, build, run” (with frequent rebuilds needed), is now a fine-tuned granular incremental build system driven by MSBuild, connecting to the Mac over a resilient, auto-deployed and always-on messaging layer running on top of a bi-directional binary protocol over TCP, secured by an SSH tunnel.

At the user experience level, it might seem that little has changed other than a fancy new connection dialog. But as Tim Cook said “the only thing that changed is everything”, so I’ll go over the details of how it works today with the new Xamarin 4 experience.

MSBuild and Incremental Builds

For anything but trivial apps, achieving incremental builds is key for productivity: you don’t want to be copying unnecessary files over the network to the Mac, neither you want to be optimizing PNGs, compiling storyboards and what-not if none of the source files have changed.

MSBuild (and XBuild on the Mac) already support incremental builds, so the first challenge was to move away from batch-style of invoking XBuild remotely, to a fully “MSBuild-native” solution. Also, we wanted to share 100% of the build logic from Xamarin.iOS targets on the Mac. So the way it works today is:

Xamarin MSBuild Flow

You can see that exactly the same targets and tasks are shared between the Mac and Windows. This allows us to minimize inconsistencies between VS and XS builds. The only difference is that the Windows version of the tasks do a remote invocation to the Mac whenever the tasks that need to run on the Mac are executed. We evaluate tasks individually to determine if they must run remotely or if they can be run locally.

The unit of remote invocation to the Mac is the MSBuild Task.Execute

One example of a task that always runs remotely is compiling iOS storyboards, since the tools to do so are provided by Xcode. An example that doesn’t is the C# compiler itself, since the source code can be compiled to IL by Microsoft’s compiler on Windows without requiring a roundtrip to the Mac.

Some parts of the build are done on Windows, some parts on the Mac

The next step was to improve the targets to provide relevant Inputs/Outputs to enable incremental build. An interesting challenge there was that for MSBuild to determine that a given target doesn’t need run again (or that certain outputs are out of date with regards to their inputs), the Outputs files need to exist on the Windows side. But since all we need those output files for is for incremental build support, they are actually written as empty files on Windows :). MSBuild doesn’t care, as long as the timestamp on those files can be compared with the Inputs to detect the out-of-date items.

This mechanism existed prior to Xamarin 4, and we just replaced the underlying remote call protocol, which was almost trivial to do since the core changes to unify XS/VS builds had already been done. Our goal was to have at least comparable performance to our previous releases.

Now that the underlying communication infrastructure has shipped, we’ll focus on fine tuning the targets and tasks to leverage incremental build support even more. Our goal is to achieve substantial performance gains moving forward, and we could certainly use your feedback, especially if you find some cases where builds are considerably slower than local builds on the Mac with Xamarin Studio.

Remote Communication

The underlying communication facilities that Xamarin provides within Visual Studio are consumed by fairly independent components (we call them Agents):

  • Activation: ensures that the Mac is properly activated
  • Build: performs the remote build task invocation
  • Designer: provides the rendering for the iOS designer
  • IDB: provides similar functionality to ADB (Android Debug Bridge), hence the name, an acronym of iOS Debug Bridge (we don’t like the name so much nowadays ;)). Basically exposes list of simulators and devices available on the Mac
  • Stats: we support collecting some stats (execution time, payload sizes, etc.) for diagnostics.

Xamarin Communication Overview

From top to bottom, the flow is:

  1. When Xamarin starts within Visual Studio, it automatically establishes an SSH connection with the Mac, deploys the Broker (if necessary), starts it and then starts all the Agents (which you see in real-time in the status bar or the spinner icon tooltip on the connection dialog)
  2. Agents use the exposed API (IMessagingClient) to send/post/reply messages (remember it’s bidirectional!)
  3. The Messaging layer communicates over TCP/IP within the SSH tunel with the Broker, which forwards the message to the Mac-side agent that registered to receive the message.
  4. The process is the exact opposite if the Mac side agents need to communicate with the VS ones, which are in turn registered to receive certain messages.

In previous versions of Xamarin, an unexpected error on any of the individual components on the Mac could cause the whole build host to stop working, requiring manual intervention by restarting it. In Xamarin 4, we implemented process-level isolation for unrelated components:

Xamarin Process Model

One key change from our previous versions is that now Visual Studio drives the Mac side too. Since it connects remotely to the Mac via SSH as a local interactive user account, it can start processes, copy files, fetch logs, etc.

Visual Studio controls deployment, versioning and manages processes on the Mac

As shown in the previous image, there is another isolation boundary at the Visual Studio process level. This ensures that multiple instances of VS can simultaneously connect to the Mac seamlessly. The broker and individual agents can all be recycled independently too. The ports used by the broker and agents are negotiated automatically to avoid collisions too.

And as soon as Visual Studio disconnects from a Mac, all processes are stopped.

In a future post, I’ll go into more detail on the protocol underlying the Messaging layer. If you’re curious, it’s MQTT :)

November 22, 2015 5:19 GMT

52 Weeks of Xamarin: Week 16 – Creating an iOS Application Part 2

Last week we began creating an iOS application. ToDoList
 We covered most of what is required but we did not tackle persistence, which we will do today.

This post is based on my Pluralsight course Beginning Mobile Development with Xamarin.

We begin by adding a package to our project: Sqlite-net.

When you search for SQLite in Nuget you’ll find there are a number of similarly named packages. The one you want has a dash and a single author, Frank Krueger.


This will add the package as well as a couple files to your project (SQLite.cs and SQLiteAsync.cs).

We’ll need a ToDoItem class to simplify adding and retrieving ToDo items.  That class will have an ID property specifically for the database, and will be attributed accordingly.

 public class ToDoItem {   
     [PrimaryKeyAttribute, AutoIncrement]
     public int ID { get; set; }
     public string TaskName { get; set; }
     public string Priority { get; set; }
     public string DueDate { get; set; }
     public bool IsDeleted { get; set; }   

SQLite Setup

Turn to the ViewController and add a SQLite.SqliteConnection named database, and an object named locker.

public partial class ViewController : UIViewController {
    private SQLite.SQLiteConnection database;
    static object locker = new object();

  The next task is to set the connection.  Normally, we’d use a path on the phone, but for now we’ll use a local path to make working with the database easier.  We set the path and use that to obtain a connection object,

public void SetConnection(){
    var path = /users/jesseliberty/Data/ToDo.db;
    var conn = new SQLite.SQLiteConnection(path);
    database = conn;

Now we are ready to implement the event handler

SaveButton.TouchUpInside += (sender, e) => {
     var toDoItem = new ToDoItem();
     toDoItem.TaskName = TaskName.Text;

Turning to ToDoReviewController, at the top of the method, add these lines:

         public List<ToDoItem> ToDoItems { get; set; }
         static NSString toDoReviewCellId = 
             new NSString("ToDoReviewCell");

Now we can implement the constructor where we first register the class for cell reuse, allowing the most efficient implementation of the table.  
 public ToDoReviewController(IntPtr handle)
     : base(handle) {
     TableView.Source = new ToDoReviewDataSource(this);
     ToDoItems = new List<ToDoItem>();
     var conn = new SQLite.SQLiteConnection(
     var query = conn.Table<ToDoItem>();
     foreach (ToDoItem toDoItem in query) {

All that is left is to implement an internal class: ToDoReviewDataSource that derives from UITableViewSource,

class ToDoReviewDataSource : UITableViewSource {

    ToDoReviewController controller;

    public ToDoReviewDataSource(ToDoReviewController controller) {
        this.controller = controller;

    public override nint RowsInSection(UITableView tableview, 
        nint section) {
        return controller.ToDoItems.Count;

    public override UITableViewCell GetCell(UITableView tableView, 
        NSIndexPath indexPath) {
        var cell = tableView.DequeueReusableCell(
        int row = indexPath.Row;
        cell.TextLabel.Text = controller.ToDoItems[row].TaskName;
        return cell;


Double check that you have a link between the Root View Controller’s Review button and the TableViewController.  Fill in a few ToDo items, saving each and then click review to see them listed.  Close and re-open the project and click review; the items are still there as they have been persisted in the database.

To cap things off, obtain the (free) utility sqlitebrowser and click OpenDatabase.  Navigate to your database and click Open.  The structure of your database is displayed and if you click Browse data you can see your tables and the data within.


The ToDoItem class includes a number of additional fields.  Retrieving, storing and viewing that data is left as a useful exercise.

November 22, 2015 12:00 GMT

NuGet Support in Xamarin Studio 5.10

Xamarin Studio 5.10 was released last week as part of the Xamarin 4 release and it includes changes to the NuGet support.


  • Support NuGet 2.8.7.
  • Open readme.txt when a NuGet package is installed.
  • Support packages.config file named after the project.
  • Local Copy settings are preserved for references when updating packages.
  • Do not show Checking for package updates message in status bar.
  • Do not show warning in the status bar if a NuGet package has PowerShell scripts.
  • Prevent the solution being closed when NuGet packages are being added.
  • Removing a NuGet package does not update the Solution window when multiple solutions are open.
  • Prevent packages.config file being marked as deleted by Git after updating a pre-release NuGet package.
  • Prevent retargeting a NuGet package marking packages.config as deleted by Git.
  • Allow Microsoft.ApplicationInsights NuGet package to be installed.

More information on all the changes in Xamarin Studio 5.10 can be found in the release notes.

NuGet 2.8.7 support

Xamarin Studio now supports NuGet 2.8.7. NuGet 2.8.7 adds support for the Universal App Platform (UAP) target framework to support Windows 10 Application Development.

Open readme.txt when a NuGet package is installed

A NuGet package can contain a readme.txt file which Xamarin Studio will now open and display in the text editor when the NuGet package is installed or updated.

Preserve Local Copy on Updating Packages

The Local Copy setting on an assembly reference will now be preserved when updating a NuGet package or retargeting a NuGet package.

By default Local Copy is set to true for assembly references when installing a NuGet package. If you set Local Copy to false for one or more of these references then this setting will now be preserved when updating or retargeting the NuGet package.

Packages.config file named after project

NuGet supports multiple projects in the same directory each using their own packages.config file. To allow multiple projects in the same directory to each use their own NuGet packages you can name the packages.config file after each project. In the examples below the project filename is on the left and the corresponding packages.config filename is on the right.

  • Foo.csproj => packages.Foo.config
  • Bar.csproj => packages.Bar.config
  • Foo Bar.csproj => packages.Foo_Bar.config

Xamarin Studio now checks for the packages.ProjectName.config file first and will use it if it exists, otherwise it will fall back to the default behaviour and use the packages.config file.

Note that a new project without any NuGet packages will use a packages.config file by default. The basic procedure to enable a project specific packages.config file when creating a new project is:

  1. Create new project called Foo.
  2. Add a NuGet package to the Foo project.
  3. Rename the packages.config file to packages.Foo.config
  4. Reload the solution in Xamarin Studio.

Also note that if you remove all the NuGet packages from a project the packages.ProjectName.config file will be deleted and on adding a new NuGet package the default packages.config file will be used.

Do not show Checking for package updates message in status bar

Previously when Xamarin Studio was checking for NuGet package updates a message would appear in the status bar. This status bar message has now been removed since checking for NuGet package updates is a background task and does not prevent Xamarin Studio from being used.

Do not show warning in the status bar if a NuGet package has PowerShell scripts

Previously if a NuGet package was installed and it contained PowerShell scripts then a warning was shown in the status bar. Now this message is only shown in the Package Console window.

Prevent the solution being closed when NuGet packages are being added

A check is now made when Xamarin Studio is closed to see if NuGet packages are still being installed. If this is the case then a dialog will be displayed indicating that it is not currently possible to close Xamarin Studio allowing the NuGet package to finish installing.

Bug Fixes

Removing a NuGet package does not update the Solution window when multiple solutions are open

With two or more solutions opened at the same time the Packages folder would not be updated for all solutions when a NuGet package was removed. This was because Xamarin Studio was not refreshing the Packages folder for all solutions currently open.

Prevent packages.config file being marked as deleted by Git after updating pre-release NuGet package.

If there was only one pre-release NuGet package installed into a project and then a later version of the NuGet package was installed from the Add Packages dialog then the packages.config file was then being shown as deleted by Git instead of modified.

The packages.config file is deleted by NuGet after the old NuGet package is uninstalled if there are no NuGet packages referenced. A special case to handle this was added in Xamarin Studio 5.3 but that only handled updating a NuGet package from the Solution window. Now updating a pre-release from the Add Packages dialog is also handled.

Retargeting a NuGet package marks packages.config as deleted by Git

This is similar to the previous bug. Retargeting a NuGet package will uninstall and then install the NuGet package. If there is only one NuGet package in the project then the packages.config file is deleted and was causing Git to mark the file as deleted instead of updated.

Unable to install Microsoft.ApplicationInsights NuGet package

Xamarin Studio 5.9.2 added support for NuGet 2.8.5 but it was not possible to install the Microsoft.ApplicationInsights NuGet package into a project. It was possible to install it using Visual Studio with NuGet 2.8.3 or higher installed. The error reported by Xamarin Studio was:

Adding Microsoft.ApplicationInsights...
The 'Microsoft.ApplicationInsights' package requires NuGet client version '2.8.50313' or above, but the current NuGet version is ''.

Xamarin Studio 5.10 now allows the Microsoft.ApplicationInsights NuGet package to be installed into a project.

November 21, 2015 3:59 GMT

My New (First) Book and This Year

eBook: $32 | Print + eBook: $50

This has been a great year so far, I have released multiple new components on the Xamarin Component Store, committed thousands of lines of code into various repositories, and, finally had my book published!

It has been a long time coming, originally scheduled for about 6 months, but working full time had forced me to go a bit slower. So after 12 months of work, Packt Publishing, made my book, "Xamarin Mobile Development for Android Cookbook", available to the world.

Beginning Writing

In September last year, they contacted me about authoring a book focused on more advanced concepts when developing Android apps using the Xamarin platform. I cover concepts ranging from using basic UI elements, to managing view states. I also show how one can make use of Bluetooth and NFC communication. Included in the topics are some that cover modern app development, such as making use of the Android support libraries to create modern apps that run on almost all versions of Android.

I won't lie and say that the book was easy; writing is pretty hard. Once the topic is decided and the code ready, the actual readable text takes a bit of work. I feel that I was able to bring each recipe across in an easy-to-consume manner without compromising on the actual content. This is a lot of work in that it is sometimes hard to write a technical document without knowing the knowledge level of the reader. In addition to that, sometimes I had to research why I did something. I have done something so many times that it has become automatic, and then I have to go and learn why. And then I sometimes realize that what I had been doing all this time was only one way...

All in all, I quite enjoyed writing, even if it meant very late nights. If I was to write another book, well, it might be some time in the future. I hope that my book sells well, not because of money, but it is an accomplishment. How many people can say they have written a book, and how many of those can say they wrote a good book. If this book sells well, then I would have achieved one of my life goals.

After I first found out about software development when I was 9 years old, I wanted to become a programmer. After the release of Windows, I wanted to be the new Bill Gates. I don't think I'll ever get to that level of awesomeness, but I can go for the other things. One of those things is to provide developers with tools that they can use to create the best that can be created.

Why I Started

When I started developing professionally, my projects were ASP.NET websites and Desktop applications. This is great, but typically those apps were company apps and only used during work hours. Mobile apps have always been a passion of mine in that they travel with the user. I have always liked being a back end developer as this is often the area where the "cool" work is done. The UI is great, don't get me wrong, but almost all of them talk to some library or service.

During my years of development, I really grew to love my work more and more. This love grew into something that I want to share with the world. It started off by helping by brother do a bit of development. He now has built several games using many of the game creation tools. One of the coolest, and most cross-platform, is Scirra's Construct 2. Recently, he has started using Unity 3D.

Another way I shared my love for development is though my code. I have several repositories on GitHub, which I try and update. I also use this account to update repositories in the community. Sometimes there is that awesome library, but just doesn't have that feature... For example, there is this tiny library, NLipsum, that allows you to generate a chunk of lorerm ipsum. Although technically not very useful, it is often the simplest way to populate text fields. This library required no changes, but could only be used with desktop .NET platforms. In the age of mobile development, I was able to add a new project that created a Portable Class Library, which can be used everywhere. This is not a headlines-worthy change, but NLipsum is now more cross-platform than ever before.

Writing a book was just another way to share my knowledge and love of development with the world. I hope my book helps both the new guy on the block as well as the other guy that never got around to using In-App billing in his popular Android app. As a result, I am not going to tell you to buy my book... If you want to check it out, or use it to get started with Xamarin.Android apps, you can order it in both an ebook and/or print from Packt Publishing for $32.

November 20, 2015 8:17 GMT

Access the Current Android Activity from Anywhere!

In the world of Android one of my biggest pain points over the years is that often you need access to the apps current Activity when writing libraries or abstracting out common functionality. For years I have been hacking around the issue by setting special Intent flags or more than likely creating a BaseActivity with a static “CurrentActivity” that is set when the page is started up. While this works short term for MY app, it completely falls down when you want to create Plugins or abstract an API into an interface of some sort. 

 When it comes down to it you just need that Activity, and it should be easy! This is why I have solve the issue once and for all with a secret hidden API that Google snuck in during the release of Ice Cream Sandwich (API 14) called ActivityLifecycleCallbacks. This is super undocumented, but from what Jérémie and I can gather Google introduced this so you can at any time figure out what the current activity. It must be implemented on your apps “Application” class and call RegisterActivityLifecycleCallbacks. After this though, you are all done. 

So, let me introduce to you my latest Plugin for Xamarin.Android called “CurrentActivity”. 

You guessed it, this plugin does 1 thing, lets you get access to the current activity. In fact the entire API is just 1 property:

/// The Current Activity
Activity Activity { get; set; }

The magic of this NuGet package and Plugin is that when you install it or if you are using it as a dependency in your own Plugin is that it lays down a “MainApplication.cs” file that ties into and implements the ActivityLifecycleCallbacks. BOOM! Done! Here is what that looks like:

using System;
using Android.App;
using Android.OS;
using Android.Runtime;
using Plugin.CurrentActivity;

namespace $rootnamespace$
	//You can specify additional application information in this attribute
    public class MainApplication : Application, Application.IActivityLifecycleCallbacks
        public MainApplication(IntPtr handle, JniHandleOwnership transer)
          :base(handle, transer)

        public override void OnCreate()
            //A great place to initialize Xamarin.Insights and Dependency Services!

        public override void OnTerminate()

        public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
            CrossCurrentActivity.Current.Activity = activity;

        public void OnActivityDestroyed(Activity activity)

        public void OnActivityPaused(Activity activity)

        public void OnActivityResumed(Activity activity)
            CrossCurrentActivity.Current.Activity = activity;

        public void OnActivitySaveInstanceState(Activity activity, Bundle outState)

        public void OnActivityStarted(Activity activity)
            CrossCurrentActivity.Current.Activity = activity;

        public void OnActivityStopped(Activity activity)

Then if you want to access the current activity anywhere in your Android application, library, or plugin simply call: CrossCurrentActivity.Current.Activity and you will have the current activity.

If you already have subclassed Application, don’t worry as you can just copy and paste some code that I put in a readme text file in the project, or head over to my GitHub and learn more!

November 20, 2015 6:13 GMT

Contest: Show Us Your Favorite Xamarin 4 Feature!

In case you missed it, earlier this week we announced a major release – Xamarin 4.

Xamarin Mobile Development Lifecycle

Xamarin 4 is all about empowering you with everything you need to create great mobile apps. We have made major enhancements to the way you build apps with the Xamarin Platform in Xamarin 4, such as Xamarin.Forms 2.0, rebuilt support for developing iOS apps from Visual Studio, and improvements to both the iOS and Android visual designers. Testing apps has never been easier with Xamarin.UITest 1.0 and the Xamarin Test Recorder preview. Our real-time app monitoring service, Xamarin.Insights, promoted to general availability, enables you to monitor the health of your applications with free crash reporting.

Xamarin 4 is packed with a lot of awesome, but we want to hear from you what your favorite Xamarin 4 feature is! In this contest, we invite you to dive into the new features and enhancements in Xamarin 4 and tell us, in a blog post, your favorite one.


EvolveFutureOfApps  650x178-2

How to Enter

  1. Install Xamarin 4.
  2. Check out the Xamarin 4 features that interest you.
  3. Blog about your favorite feature of Xamarin 4.
  4. Submit your entry for the chance to win free registration to Xamarin Evolve 2016 by tweeting a link to your blog post with the following text: “#Xamarin4 has everything you need to create great mobile apps. Check out my favorite feature: “

How to Win

Want to stack the cards in your favor? Do any or all of the following to increase your odds of winning:

  • Don’t just tell us about your favorite feature – show it in action: Everyone loves pictures, videos, and code samples!
  • Be creative! Build or show something unique and cool.
  • Hard to pick a favorite? Multiple entries will be accepted and reviewed on individual merit.

All submissions must be made by Monday, December 7th, 2015 at 12PM EST. We will evaluate each blog post and choose the winner based on concept, quality, and creativity. A valid entry consists of a tweet containing the text above, along with a link to your personal blog post detailing your favorite Xamarin 4 feature. To be eligible, you must follow @XamarinHQ to enable us to DM you for private-follow up. There is no purchase necessary to enter the Xamarin 4 feature contest.

The post Contest: Show Us Your Favorite Xamarin 4 Feature! appeared first on Xamarin Blog.

November 20, 2015 6:00 GMT

Easily Instrument HTTP Calls in Your Apps

Lately I've been doing a lot of work around adding instrumentation to basically all the things, which naturally includes my apps. It's common practice to instrument things on the server-side of the API using awesome tools like NewRelic, but that's only part of the equation. Obviously we need the server to respond as quickly as possible so being aware of that metric is essential, but on top of that the user also has to wait for that request to get to the server and back over networks that are often pretty slow. How long are you making users watch a loading spinner for when they're trying to get something done?

Depending on what your apps are doing it probably makes sense to instrument more than just HTTP calls to be able to get some visibility into this, but I'll just start with HTTP here. When I was spiking some ideas on how to implement this I went down a few different paths before I realized I was overlooking the most obvious/simple solution that we'll go through here.

HttpClient and HttpMessageHandler

If you're using HttpClient to make your HTTP calls (if you're not, you probably should be!), you may or may not know that it has a constructor that takes in a HttpMessageHandler instance. The awesome part about that is that it means we can create a simple class that will be inserted into the pipeline of every HTTP call being made from that HttpClient instance.

Here's what that a simple implementation might look like:

class InstrumentedHttpClientHandler : HttpClientHandler  
  protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    var successful = false;
    var stopwatch = Stopwatch.StartNew();

      var result = await base.SendAsync(request, cancellationToken);
      successful = result.IsSuccessStatusCode;

      return result;

      // TODO: publish metric

This implementation simply wraps the base implementation of SendAsync with a stopwatch so the behavior will be the same except that now you'll get access to how long the call took via stopwatch.ElapsedMilliseconds, and whether or not it was successful. One thing to be careful of when adding instrumentation is that you don't want to slow things down any more than necessary in order to measure it. In this case there's minimal overhead, especially when dealing with network calls that will reliably take a decent chunk of time anyway.

With this data you can now publish your metrics in whatever way makes sense for your application, be it to the device logs, an API, etc. Not only is it useful to know how you're performing right now, it's even more important to know how you're trending over time? Did your last release make things better or worse? Without tracking it you'll never know.


If you're using ModernHttpClient (again, if you're not, you should be!) you may have noticed that this is the same approach used by that library to intercept requests happening in HttpClient. You can still take advantage of this instrumentation approach if you're using ModernHttpClient. In fact, all you need to do is change the base class of InstrumentedHttpClientHandler to ModernHttpClient's NativeMessageHandler and you're all set!

November 20, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #67

Get Started with Xamarin 4 Today
Bryan Costanich, from Xamarin Inc., invites you to get up to speed on Xamarin 4.0.

Introducing Xamarin 4: Everything You Need to Build Great Apps
Nat Friedman, from Xamarin Inc., announces Xamarin 4.

Sort ListView Alphabetically in Xamarin Android
Val Okafor shows his LINQ powers in this ListView demo.

Advanced Xamarin Forms Techniques – Part 5, Page in Page Embedding
George Cook finishes off his blog series with some Page in Page action.

Pluralsight: Beginning Automated Testing of Xamarin Applications
Greg Shackles teams up to bring you testing for Xamarin.Forms.

Xamarin and Microsoft Create the New Standard for Enterprise Mobility
Joseph Hill, from Xamarin Inc., expands thier partnership with Microsoft.

Yet Another Podcast #142 – Krystin Stutesman on iOS 9
Jesse Liberty has Krystin Stutesman on the podcast talking about iOS9.

Models and Service Layer (Day 6)
Adam Pedley adds Day 6 to his Xamarin.Forms enterprise blog series.

52 Weeks of Xamarin: Week 15 – Creating an iOS Application Part 1
Jesse Liberty adds week 15 to the yearlong blog series.

A Xamarin App: From Idea to Store (Android App Prep)
Chris Swain does all the prep work for the Test Timer Android app.

Don't miss out! Subscribe Today

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

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

November 19, 2015 6:15 GMT

Get Started with Xamarin 4 Today

Xamarin 4 is a fantastic release, designed to make building apps with Xamarin faster, easier, and more delightful than ever before, and the Xamarin Education team has worked incredibly hard to deliver the resources you need to get up and running with it. In both the documentation and Xamarin University teams, we have created a ton of new content as well as updated the existing content to be as fresh as the release. Be sure to check out the following resources to get started with Xamarin 4 today.

Get Up to Speed Quickly with Lightning Lectures

If you’re an experienced Xamarin developer, I recommend starting with our free Xamarin 4 Lightning Lectures from Xamarin University. They focus on quick overviews and introductions of new features:

  • iOS Apps in Visual Studio: Connect to your Mac to develop, build, debug, and deploy applications using our completely rebuilt support for developing iOS apps from Visual Studio
  • XIB Launch Screens: Easily support multiple iOS form factors with a XIB-based launch screen using the designer.
  • Introducing Xamarin Test Recorder: Greatly increase efficiency by creating automated UI tests visually with Xamarin Test Recorder.
  • tvOS with Xamarin: Apple’s tvOS is based on iOS, but has a number of key UI and framework differences. Learn about them and build the next killer tvOS app with Xamarin.
  • Creating iOS Extensions: Allow apps to create a rich inter-app experience by passing documents and context between them.
  • Android Material Design in Xamarin.Forms: Android Material Design is Google’s new design language and Xamarin.Forms now supports it.
  • Adding Insights to your Application: Xamarin 4 saw the public release of Xamarin Insights. Add it to your apps today with this quick walkthrough.

Xamarin University Lightning Lectures are completely free, but if you’re a Xamarin University subscriber, you’ve also got access to new Xamarin 4 classes, as well as updated content across the board to support the Xamarin 4 release.

Dive into Xamarin.Forms 2.0

Xamarin.Forms 2.0 included a number of cool new features and performance enhancements including:

Additionally, Xamarin University has over 15 hours of Xamarin.Forms content, and we’ve updated that content to cover all of the new features of Xamarin.Forms 2.0. Including:

Streamline Your iOS Experience in Visual Studio

Xamarin 4 takes a completely new approach to building iOS apps in Visual Studio with a Mac build machine. With our completely rewritten Visual Studio support, it’s faster, more secure, and easier to set-up and keep your build environment in sync. After you’ve checked out the Lightning Lecture, make sure to check out our new docs on it here.


Build Beautiful Apps with the iOS and Android Designers

Both the iOS and the Android designers have seen significant improvements in performance, as well as a slew of new features.

Xamarin’s Android Designer is faster, and includes new Material Design options to make building attractive Android apps even easier and more visual than before.

The iOS Designer now supports XIB files as well as Storyboards, meaning you can more easily share table and collection view cell layouts and create universal launch screens. We’ve created a recipe that walks through creating a XIB based launch screen, in addition to the lightning lecture mentioned above.

Finally, Xamarin.Mac got a big upgrade with its new support for storyboards via Xcode, enabling seamless synchronization between your C# code and the Xcode graphical UI designer.

Get Testing with Xamarin Test Cloud

Xamarin Test Cloud just got even better. Not only is there a new pricing model that makes it more accessible for everyone, we’ve also launched UITest 1.0, the first official release of our C#-based test authoring package that brings a familiar NUnit-like structure to your automated user interface test code.

Generate Tests Easily with Xamarin Test Recorder

To make it even easier to write tests, we’ve created the Xamarin Test Recorder, which enables you to generate automated UI tests visually.


Xamarin Test Recorder is an early preview tool that lets you build tests without any code at all—simply click through your app to build test cases, and watch Xamarin Test Recorder generate test code for you. You can then edit the test further or upload it straight to Xamarin Test Cloud! Check out the Lightning Lecture, and then dive into the documentation for more information.

If you’re signed up for Xamarin University, make sure to check out the updated Xamarin.UITest (XTC102) class, which now covers Xamarin Test Recorder.

Raise Your App IQ with Xamarin Insights

Xamarin Insights is a fantastic product that’s incredibly easy to add to your apps and can give you valuable insights into how people use them. Without doing any real work at all (simply adding it to your apps), you can track a lot of usage and metrics including app crashes and their cause. With a little more effort, you can build all kinds of useful events into tracking and really understand how people use your app, so you can optimize your development efforts. You can also automatically integrate events into 3rd party services such as GitHub and Visual Studio Online!

Check out the Quickstart guide or Lightning Lecture to get up and running quickly, or learn more about the product’s features in our expanded docs section.

Xamarin University students also have access to a brand new class, Using Xamarin Insights (XAM215) that teaches you everything you need to know to integrate Xamarin Insights into your Xamarin.Forms or native Xamarin application.

Happy Xamarining from the Xamarin Education Team!

The post Get Started with Xamarin 4 Today appeared first on Xamarin Blog.

November 18, 2015 6:53 GMT

Pluralsight: Beginning Automated Testing of Xamarin Applications

Recently I had the pleasure of working with my friend Jesse Liberty on a new Pluralsight course focused on helping you get started building Xamarin apps in a test-driven fashion. In under an hour he walks you through building out a real app using tests right from the start, running those tests on both iOS and Android, and also getting into writing UI tests to run locally as well as in Test Cloud.

If you're looking for a good way to see testing in action with mobile development, please check it out!

Beginning Automated Testing of Xamarin Applications

November 18, 2015 6:29 GMT

Xamarin and Microsoft Create the New Standard for Enterprise Mobility

Today and tomorrow, Microsoft is hosting their annual Visual Studio Connect(); event and we were honored to join with them in the announcement of an expansion of our partnership to include the tools, services, training, and workflow that organizations need to go mobile quickly. During the live streamed event, Microsoft executives and technical experts present new products, integrations, and innovative technologies to the .NET community, including live demos and Q & A. Since launching our global partnership with Microsoft at Connect (); in 2013, we’ve helped countless organizations build amazing apps, and deepened our relationship to include same-day Visual Studio 2015 support and special benefits for MSDN subscribers.

Microsoft + Xamarin logo

This year, we’ve gone even bigger to include an entire DevOps workflow, from design to continuous innovation and developer education. We’re making it easier than ever for our customers to use products and tools they love to deliver the highest quality, enterprise-ready apps, including:

  • Xamarin integrations for Office 365 Services, Azure Active Directory, and Azure App Service: Simplify mobile development by quickly adding scenarios to your apps with Xamarin-compatible NuGet packages, including SSO with Azure Active Directory, Exchange / Outlook email notifications, Office 365 calendaring, and access to OneDrive or Sharepoint 365 files.
  • Xamarin and Microsoft Intune interoperability: Secure your Xamarin apps with Intune’s comprehensive security features, such as SSO, encrypting device data, and restricting specific in-app actions.
  • Xamarin Test Cloud and Visual Studio Team Services integration: Use Visual Studio Team Services to build Android Xamarin apps, kick off automated tests on Xamarin Test Cloud’s 2,000 devices, view test results from your Visual Studio Team Services Test Hub, and connect to TFS CI for completely agile development.
  • Xamarin University for Visual Studio Dev Essentials: Visual Studio Dev Essentials members get free access to select Xamarin University course recordings and materials to jumpstart native app development with expert-led training.
  • Xamarin and Microsoft Imagine enhancements: it’s even easier for students to get started with mobile development by requesting and activating complimentary Xamarin subscriptions straight from the DreamSpark catalog. Students automatically receive VS 2015 bundled with Xamarin project templates. Additionally, Microsoft Student Partners are equipped with hands-on demo workshops and presentations, allowing even more students to go mobile with Visual Studio, Azure, and Xamarin.

The virtual event also showcased a live Xamarin demo, including our wearables support, iOS and Android Designers, and Xamarin 4’s improved experience for building native iOS apps with VS.

With these announcements, we’re looking forward to helping our global customers be more productive and solve business problems at a rapid pace.

To learn more about Xamarin and Microsoft, visit

The post Xamarin and Microsoft Create the New Standard for Enterprise Mobility appeared first on Xamarin Blog.

November 18, 2015 2:35 GMT

Live Stream: Connect(); // 2015

Connect() is an annual, Microsoft-hosted event that is broadcast live from New York City to developers worldwide. Be sure to tune in right here, today and tomorrow for the live stream which features keynotes from Scott Guthrie, Brian Harry, and Scott Hanselman plus interactive Q&A sessions with the engineering teams!

November 17, 2015 3:00 GMT

Introducing Xamarin 4: Everything You Need to Build Great Apps

Today, we are extremely excited to introduce Xamarin 4, a complete mobile solution to help you build amazing mobile apps from start to finish.

Xamarin 4 is packed full of major enhancements to the Xamarin Platform and Xamarin Test Cloud, but today we’re also proud to announce the general availability of our real-time app monitoring service, Xamarin Insights.

Xamarin Mobile Development Lifecycle

The highlights of Xamarin 4 are covered below, but if you want to learn about more of the details and see some demos, please join me and James Montemagno on Friday November 20 for a webinar dedicated to what’s new in Xamarin 4.

Xamarin Platform – native, cross-platform apps

Xamarin.Forms 2.0

Since releasing Xamarin.Forms last year, we’ve been amazed at how quickly developers have adopted it, accelerating their time-to-market for cross-platform native experiences across iOS, Android, and Windows, all while sharing over 90% of their code.

Since then, we’ve more than doubled the engineering team behind Xamarin.Forms, and made major improvements along the way. Today, Xamarin.Forms 2.0 is faster, more reliable, and more functional than ever before. Highlights include support for pre-compiled screens defined in XAML for faster app loads, preview support for Universal Windows Platform apps, support for iOS 9, Android Material Design, and new gestures like pinch and pull-to-refresh.

Native Xamarin.Forms app displayed on iOS, Android, and Windows Phone devices

Visual Studio and iOS

We’ve rebuilt our support for developing iOS apps in Visual Studio from the ground up, and it’s smoother, easier to set up, and more reliable than ever before. Now you can develop, build, deploy and debug iOS apps entirely from within Visual Studio and communication with the Mac build host is now handled via a secure SSH connection. We now also support multiple concurrent Visual Studio instances, which is especially important if you have multiple iOS projects open at the same time. We think you’re going to love it.

Mono/.NET upgrade

In Xamarin 4, we have incorporated large portions from Microsoft’s open sourced .NET codebase into this release, increasing compatibility, performance, and reliability for all use cases.

Android and iOS Designers

We’ve made big improvements to our iOS and Android designers. The iOS designer can now load and save XIB files in addition to storyboard files, and our Android designer now supports Android Material Design. We have also improved the UI for both designers, and switched to using high-performance native design surfaces, for a smoother, faster editing experience.

Xamarin Test Cloud – automated app testing

We built Xamarin Test Cloud to allow you to easily test your app on more than 2,000 real iOS and Android devices in the cloud. With Xamarin 4, we’re making mobile testing more accessible than ever.

Introducing Xamarin Test Recorder

We’re introducing a new preview tool that makes mobile UI testing dead simple: Xamarin Test Recorder. Initially available for Mac, Xamarin Test Recorder records your interactions on iOS or Android apps, plays them back, and automatically creates test scripts that can immediately be run in Xamarin Test Cloud or imported into mobile test projects in Xamarin Studio and Visual Studio. Xamarin Test Recorder records your actions in our C#-based UITest framework so you can automatically execute them as part of your continuous integration process either locally or in the cloud. Download it now to get started.

Xamarin.UITest 1.0

Xamarin 4 includes the 1.0 release of the Xamarin.UITest C# testing framework, with new capabilities for advanced test scenarios. We’re also very happy to announce that Xamarin.UITest is now free for everyone to use, with no limits on test duration, or the use of local devices and simulators. The powerful combination and ease of use of Xamarin Test Recorder and Xamarin Test Cloud will help you immediately improve your apps.

Xamarin Insights – real-time app monitoring



General Availability

We’re proud to announce that starting today, Xamarin Insights is generally available, with free crash reporting for all Xamarin Platform customers and advanced app monitoring features for power users.

Know the Health of Your App, Know Your Users

App monitoring begins with knowing what problems your users are encountering. Is the app crashing or encountering exceptions or errors? Xamarin Insights provides automatic crash reporting and handles both managed and unmanaged mobile crashes seamlessly. You can also explicitly report errors or warnings to Xamarin Insights and track them through the its dashboard. Xamarin Insights makes it easy to rank your issues by impact, spot patterns in app and device usage, and diagnose the corresponding issues.

Xamarin Insights also helps you understand how your app is being used by tracking and timing step-by-step event data. Analyze which screens are the most popular or which actions take your users the longest. You can even see which events led up to a crash, making it easy to reproduce your issues.

You can add Xamarin Insights to your app with just a few lines of code. In Xamarin Studio, new apps immediately get the benefit of Xamarin Insights with templates that utilize the SDK from the very beginning of a mobile project. And your IDE will automatically upload dSYM files for you so that you get symbolicated stack traces with line numbers.

Visit our docs to get started.

End-to-End for Everyone

We think it’s important that every developer be able to benefit from the full range of what Xamarin 4 can do, which is why we’re excited to announce that as a part of their existing subscription, every active Xamarin subscriber will receive:

  • Crash and error reporting from Xamarin Insights with 30 day data retention and detailed issue reports that include step-by-step pre-crash events and crashed-user identification.
  • 60 Xamarin Test Cloud device minutes per month, with access to every single one of the devices in our growing test lab.
  • Complete access to Xamarin.UITest, including tests of unlimited duration running on simulator or device.
  • A 30-day trial pass to Xamarin University, including access to guest lectures and our introductory courses.

Paid Plans

As your business grows and your apps progress, you can buy paid plans of Xamarin Insights and Xamarin Test Cloud that suit your needs.

For companies who want to ramp up their mobile testing, we’re happy to introduce affordable Xamarin Test Cloud pricing plans starting at $99/month (billed annually). If you want to go further with app monitoring, we also provide scalable Xamarin Insights paid plans.

Xamarin Ultimate

Finally, for companies who want a complete end-to-end solution, we’re introducing a new offering called Xamarin Ultimate, which includes full access to all the features of Xamarin Platform, Test Cloud, Insights, and University for your entire team in a complete package at a great price. If you’re interested in learning more about this, please get in touch with our sales team at

Learn more this week

Join me this Friday, November 20 for a webinar overview about what’s new in Xamarin 4. Register for the time that best fits your schedule below:

Europe 1 pm GMT North America 11 am PT
Over the next few weeks we’ll also be doing individual deep-dive webinars on Xamarin Platform, Test Cloud, and Insights. We’ll post dates for these events on the blog in the near future.

Lastly, if you’re new to Xamarin you can get started with a free trial now and explore what Xamarin Platform, Test Cloud, and Insights have to offer!

The post Introducing Xamarin 4: Everything You Need to Build Great Apps appeared first on Xamarin Blog.

November 15, 2015 9:45 GMT

52 Weeks of Xamarin: Week 15 – Creating an iOS Application Part 1

In the previous two posts in this series, I demonstrated how to create a simple to-do listReviewPageWithBorder using Xamarin.Forms.  In this and the next post, I’ll show how to create pretty much the same program for iOS using Xamarin native code.

To begin, open Xamarin Studio and create a new solution, choosing iOS/App -> Single View App and name it ToDoiOS.  We’ll begin by roughing out the UI.  Open the file Main.storyboard.  You’ll find a View Controller.  Go to the toolbox and drag a Navigation Controller onto the storyboard — notice that it brings its own ViewController.

Grab the sourceless segue (the arrow) and move it to point to the Navigation Controller.

sourceless segue

Great.   Now you can delete the original View Controller.

What you’ve done, effectively, is replaced the default ViewController with a Navigation Controller.  The Navigation controller has no UI, but as you might imagine it assists with navigating from one page to another. It is “born” with its own ViewPage which will be the first page in our interface.

Next, drag a Label from the toolbox onto the storyboard and use the Properties window to set its text to “Task” and its font to 17 points.

Properties Window

Next, drag a Text Field onto the storyboard, and using the properties window, set the following values:

  • Name:  ToDoEntry
  • Text:     Leave this empty
  • Font:    14 point
  • Placeholder:  Task Name

Finally, drag two buttons onto the storyboard and set the text for the first to Save and  the second to Review


Not attractive by any measure, but enough to get us started.

Because we want the review page to hold a list of To Do tasks, we’ll drag a TableViewController onto the storyboard.  There are other ways to get a table, but if you want a full page table, this is the easiest approach.  Once you drag the TableView into place,  control-click on the Review button and drag to the TableViewController.  When you let go, you’ll see a segue from the Root View Controller to your Table View Controller.

Click on the black bar at the bottom of the TableViewController and in the properties window set the class to ToDoReviewController.  Notice that Xamarin Studio will instantly and automatically add a new file, ToDoReviewController.cs to your project.

You now have two controllers: ViewController (for the Root View) and ToDoReviewController (for the Table View).

View Controller

View controller’s job is to get the to do items saved over to the review page where they will be listed.  To do so, we’ll create a toDoItem as a string, and a collection, ToDoItems, as a list of strings, which will be initialized in the constructor,

string toDoItem = string.Empty;
 public List<string> ToDoItems { get; set; }
 public ViewController(IntPtr handle)
     : base(handle) {
     ToDoItems = new List<string>();

We will override ViewDidLoad and PrepareForSegue. In the former, we’ll handle the click of the save button,

 public override void ViewDidLoad() {
     SaveButton.TouchUpInside += (sender, e) => {

In PrepareForSqegue, we are going to get an instance of ToDoReviewController and then set the ToDoItems in that controller to the ToDoItems in the root view; effectively passin in the ToDoItems.

 public override void PrepareForSegue(
             UIStoryboardSegue segue, 
             Foundation.NSObject sender) {
     base.PrepareForSegue(segue, sender);
     var ToDoReviewController = 
         segue.DestinationViewController as ToDoReviewController;
     if (ToDoReviewController != null) {
         ToDoReviewController.ToDoItems = ToDoItems;


By the time we get to this controller, its ToDoItems property has already been populated as shown above.

We declare the collection (for convenience, also naming it ToDoItems) and we declare a static member string object toDoReviewCellId

In the constructor, we call TableViews’ RegisterClassForCellReuse which is critical for efficient use of memory.  We also set the Source for the TableView to an instance of ToDoReviewDataSource, which is a class we’ve not yet defined, but which is instantiated with the ToDoReviewController itself.  Finally, we instantiate the ToDoItems collection of strings,

 partial class ToDoReviewController : UITableViewController {
     public List<string> ToDoItems { get; set; }
     static NSString toDoReviewCellId = new NSString("ToDoReviewCell");
     public ToDoReviewController(IntPtr handle)
         : base(handle) {
             typeof(UITableViewCell), toDoReviewCellId);
         TableView.Source = new ToDoReviewDataSource(this);
         ToDoItems = new List<string>();

We now create an inner class, ToDoReviewDataSource which takes the controller and copies it into its member variable controller

 class ToDoReviewDataSource : UITableViewSource {
     ToDoReviewController controller;
     public ToDoReviewDataSource(ToDoReviewController controller) {
         this.controller = controller;

The table needs to know how many rows to create, and we tell it by overriding RowsInSection, returning the number of strings in the ToDoItems collection in the controller.

 public override nint RowsInSection(UITableView tableview, 
                                    nint section) {
     return controller.ToDoItems.Count;

Finally, we override GetCell which allows us to reuse cells that are not displayed and to set the text of the displayed cell to the appropriate ToDoItem,

 public override UITableViewCell GetCell(UITableView tableView, 
                                         NSIndexPath indexPath) {
     var cell = tableView.DequeueReusableCell(
     int row = indexPath.Row;
     cell.TextLabel.Text = controller.ToDoItems[row];
     return cell;

There is more to do, especially including persisting the ToDo items, and we’ll take this up next week.

November 13, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #66

MvvmLight Navigation Extension
Daniel Hindrikes adds a modal navigation extension to MvvmLight.

Building iBeacon apps using Xamarin.iOS Video Tutorial
Jim Bennett launches his new series on YouTube about iBeacons.

Announcing Xamarin’s New Elite Consulting Partners!
Greg Urquhart, from Xamarin Inc., announces Xamarin’s new consulting partner program.

The ViewModel (Day 4)
Adam Pedley adds another post in his enterprise series.

FreshMvvm n+1 Series
Michael Ridland goes over Navigation and IOC in these two new FreshMvvm videos.

Announcing the Xammy Awards at Xamarin Evolve 2016
Joseph Hill, from Xamarin Inc., announces the Xammy Awards are back!

52 Weeks of Xamarin: Week 13 – Writing It Thrice
Jesse Liberty adds week 13 to his year long series.

Storytelling App Storyo Goes Cross-Platform with Xamarin
Jo Ann Buckner, from Xamarin Inc., shows off another app built with Xamarin.

Live Coding with Xamarin iOS
Frank A. Krueger has a new Xamarin Studio add-in that you must try.

Getting Started with Handoff in iOS
Krystin Stutesman, from Xamarin Inc., helps you give your users a seamless experience.

Testing Xamarin Apps: Screen Object Pattern
Greg Shackles loosens up your brittle UI tests with this one pattern.

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

November 12, 2015 5:25 GMT

Announcing Xamarin’s New Elite Consulting Partners!

Since launching the Xamarin Consulting Partner Program in 2012, we’ve experienced exponential growth as a company, due in large part to our robust Consulting Partner network. Our 350+ Consulting Partners drive mobile innovation and transformation for customers worldwide, and we’re excited to announce our latest expansion, including the introduction of Xamarin Elite Consulting Partners.

Xamarin Elite Consulting Partners have our highest endorsement, boast global and multi-regional footprints, and offer a diverse set of services to enterprises, maintaining a high bar for mobile excellence. They’re using their in-house expertise and Xamarin Certified Developers to build transformational apps for consumers and employees, and have demonstrated accomplishments in various organizations. We’re happy to welcome nine Elite Consulting Partners, including:

  • Avanade
  • Cognizant
  • EPAM Systems
  • Magenic
  • Mindtree
  • Neudesic
  • Orange Business Services
  • Pariveda
  • Sogeti

Gold Elite Consulting Partner Badge A few recent success stories from our Elite Consulting Partners include:

  • Vanderlande (Avanade): Vanderlande, the global leader in package and airport sorting systems, turned to Avanade to improve its package sorting processes and improve customer satisfaction. Avanade, with over 25,000 consultants worldwide, used its Xamarin expertise to quickly deliver easy-to-use apps for iOS, Android, and Windows, and ensure mobile quality with Xamarin Test Cloud.
  • Kellogg’s (Mindtree): Kellogg’s offers its merchandiser network several incentives to drive sales of its iconic brands and, with Mindtree’s expert mobile guidance, now seamlessly manages over 40,000 different promotions while optimizing efficiency and tracking success.
  • EasyJet (EPAM): Flying over 65 million passengers a year, EasyJet’s customer experience is critical to its success and EPAM helps them gain competitive advantage with a personalized check-in mobile experience. Airline staff receive real-time flight gating and delay information on their iPads, enabling them to provide status updates to customers at curbside baggage drop-off.

customer logo wall

We’ve completely revamped our Consulting Partner website to recognize all of our Partners’ accomplishments and allow customers to quickly find Partners. Location plays a big role in Consulting Partner selection so we’ll now detect site visitors’ current location to show relevant results immediately, as well as filters for various specializations. From there, it’s easy to contact Partners and request more information with click-to-email contact forms.

Visit today to see what’s new, find a Consulting Partner, or learn more about joining our global Consulting Partner network.

The post Announcing Xamarin’s New Elite Consulting Partners! appeared first on Xamarin Blog.

November 11, 2015 11:00 GMT

Xamarin Studio Tips & Tricks

I live inside Xamarin Studio for most of my coding adventures. I'm pretty happy there, but there are some small things I have learned that help with productivity and feeling more comfortable.

Xamarin Studio


Your //TODO: comments don't have to get lost. You can find them all in a list via the Xamarin Studio -> View -> Pads -> Tasks window. Double-click them to jump right to the code line.

Tasks Pad

Change the Tasks pad to show "User Tasks" and you can create your own to-do list with a checkbox for when it's complete.

Users Tasks

Bonus tip: You can create custom comment keywords in the Xamarin Studio -> Preferences -> Tasks window.

Markers and Rulers

There are a few productivity gems in here that I have recently come to enjoy. Open the Xamarin Studio -> Preferences -> Markers and Rulers menu. Then, try out these settings by checking the boxes:

Markers and Rulers Settings

Some of my favorites that I recently found were available are the "Highlight current line" and "Show indentation guides".

Code Templates

AKA "Snippets". Create and edit them in Xamarin Studio -> Preferences -> Code Templates. Create your customizable areas with this format: $name$. Then, you can click on it and customize the default options. Here is one that I use for quickly scaffolding bindable properties in Xamarin.Forms:

public static readonly BindableProperty $name$Property =  
    BindableProperty.Create<$view$,$type$>(p => p.$name$, default($type$));

public $type$ $name$  
    get { return ($type$)GetValue($name$Property); }
    set { SetValue($name$Property, value); }

Bindable Property Code Template

Source Analysis

This does static analysis on your code and suggests some refactorings when possible. It'll also catch some mistaks or missed references, etc. It's not Resharper, but I find it more useful than not. Turn it on via the Preferences -> Source Anaylsis menu.

Static Analysis

Directory Namespaces

If you would prefer that each code file you add to a subdirectory is created in a namespace that matches, you'll have to enable this in the Preferences -> .NET Naming Policies menu. Check the "Associate namespaces with directory names" box. You have some additional options in there you can customize.

Custom Breakpoints

I find it useful sometimes to create a breakpoint that is hit when any System.Exception is thrown. It's useful for catching errors that might be swallowed or hidden for some other reason. You can do this via the Xamarin Studio View -> Debug Windows -> Breakpoints window. In this window, click the "New Exception Catchpoint" button. Then, add System.Exception in the "When an exception is thrown" textbox.


Edit the Project File

You can edit the project file of a project right inside Xamarin Studio. Right-click on a project and go to the Tools -> Edit File menu. This opens the project file in a text editor. You can quickly make changes in there and then save to reload the project.

Go to File

This is a searching shortcut to quickly open/search for a specific file by name. Press CMD+SHIFT+D on your Mac while in Xamarin Studio. This jumps you up to the search bar in the upper right with the filter file:. Now type in a file name to search for and press enter to jump right to it.

Separate Solution Files

This is not a feature of Xamarin Studio but more of a "best practice" that I like to use. If you a solution that may contain projects that only load on Windows (WPF, WP, etc) you might consider making a separate solution (.sln) file for working in Xamarin Studio on a Mac. XS does a decent job of just not loading incompatible projects with a cute icon to let you know why. You might find it handy to just not have all this loading. Create a new solution file via Xamarin Studio -> File -> New Solution -> Miscellaneous -> Blank Solution and name it something like MyProject.XamarinStudio.sln. Then, save this where you have your other .sln file. Add only the projects you need for solution now. Right-click the solution -> Add -> Add Existing Project. Rinse/Repeat.

If you know of something else that's helped you, I'd love to hear it!

November 11, 2015 10:07 GMT

FreshMvvm n=3: Navigation in FreshMvvm

Here’s the next video in the  FreshMvvm n+1 series. The idea of this series is to get the video’s out to the eager listeners (you) as quickly as possible, therefore these videos are done live with almost no editing.

Episode Title: n=3: Navigation in FreshMvvm

In this episode we discuss:

  • Review FreshMvvm’s built in Navigation Abilities
  • Understand how navigation works in FreshMvvm

I hope you enjoy.

The post FreshMvvm n=3: Navigation in FreshMvvm appeared first on Michael Ridland.

November 11, 2015 7:18 GMT

Announcing the Xammy Awards at Xamarin Evolve 2016

The Xammy Awards will be returning to Xamarin Evolve 2016! You are the future of mobile and the Xammies give you an opportunity to earn global recognition for the impact of your apps!

Apps can be submitted in the following three categories:

Consumer: Tell us how your app changes the way we interact with the world and each other.
Enterprise: Highlight how your app is transforming business.
Emerging Devices: Showcase how you’re pioneering the next generation IoT, wearables and other connected experiences.

Submissions are open from now until December 31, 2015, and winners in the three categories will be announced live on stage at Xamarin Evolve 2016.

Think you have what it takes to be the best? Check out last year’s winners:

Best Consumer App: Storyo

Best Emerging Devices App: APX Labs

Best Enterprise App: Dutch Tax Office

Don’t miss your chance to claim a category for this year’s Xammy Awards—submit your app today!

Submit Your App

The post Announcing the Xammy Awards at Xamarin Evolve 2016 appeared first on Xamarin Blog.

November 11, 2015 4:18 GMT

52 Weeks of Xamarin: Week 14 – Thrice (part 2)

In the previous posting I started a new project in Xamarin.Forms that I will reproduce ToDoReview2in
iOS and Android in coming posts.

Today, we’ll take a look at the second page in the Xamarin.Forms version: ListTasksPage.

This lists the tasks that you entered and persisted in the previous posting.


The Data


We start by creating a new Xamarin.Forms page: ListTasksPage.xaml.  Because we want to get our list from our database, we override OnAppearing in the code-behind,


 protected override void OnAppearing() {
     ToDoList.ItemsSource = App.Database.GetToDos();

This depends on our ToDoDatabase.cs file, which implements GetToDos(),

 public IEnumerable<ToDoItem> GetToDos() {
     lock (locker) {
         return (from c in database.Table<ToDoItem>()
                 select c).ToList();

This in turn relies on the SQLite_iOS method (for iOS),

 namespace ToDo.iOS {
     public class SQLite_iOS : ISQLite {
         public SQLite_iOS() {
         public SQLite.SQLiteConnection GetConnection() {
         var path = "/users/jesseliberty/Data/ToDo.db";
             File.Open(path, FileMode.OpenOrCreate);
             var conn = new SQLite.SQLiteConnection(path);
             return conn;


(Note that we are storing the data on my local hard disk rather than on the phone, to make debugging easier.)

Notice that this class implements ISQLite (to facilitate the dependency injection provided by the dependency service in Xamarin.Forms).  That interface is, as usual, extremely simple,

 public interface ISQLite {
     SQLiteConnection GetConnection();


With the ability to retrieve the ToDo items from the database, we’re now ready to create the XAML itself.  Here’s the top of the file,

         x:Key="dtConverter" />

Notice that the Resources section calls for a DateTimeConverter whose key is dtConverter.  This is defined in the helper class DateTimeConverter,

 public class DateTimeConverter : IValueConverter {
     public object Convert(object value, 
            Type targetType, 
            object parameter, 
            System.Globalization.CultureInfo culture) { 
         var time = (DateTime)value;
         return time.ToString("M/d/yyyy h:mm tt");

As you can see, the convert method takes in a DateTime object and returns a properly formatted string.

Returning to the XAML,

    TextColor=Blue />
                Text={Binding TaskName}
                TextColor=Red />
                  FontSize=10 />
                  Text={Binding Priority}
                  FontSize=10 />
                  FontSize=10 />
                  Text={Binding DueDate, Converter ={StaticResource dtConverter}  }
                  FontSize=10 />

Notice that we are binding to the TaskName, Priority and Date for each of the ToDo items we extracted from the database (above).  Most often, we would declare the ItemsSource property in the XAML but, as you’ll remember, we declared it in OnAppearing (repeated here),

 protected override void OnAppearing() {
     ToDoList.ItemsSource = App.Database.GetToDos();

Notice also that the list calls for an event handler when an item in the list is selected. For now, we just open an alert box to indicate that we have captured the correct item’s selection,

public void OnSelected(object o, ItemTappedEventArgs e) {
    var todoItem = e.Item as ToDoItem;
    DisplayAlert(Chosen!, todoItem.TaskName +  was selected, OK);

The result is the list of ToDo items as shown at the start of this posting.


November 10, 2015 9:36 GMT

Storytelling App Storyo Goes Cross-Platform with Xamarin

Storyo app on iPhone and AndroidBased in Portugal, Nativo Labs was created by three entrepreneurs who experienced firsthand the need for a better way to tell stories using photographs. “The three founders all have young children, and selecting photos becomes a bit of a nightmare. We wanted to help people tell stories using photos,” says Manuel Costa, Chief Technology Officer at Nativo Labs.

The startup needed a way to efficiently develop the app on their own, so they turned to Xamarin. “We used Xamarin for two main reasons,” says Filipe Vasconcellos, CEO of Nativo Labs. “One was time to market, and second was that it allowed the team to focus on the idea rather than the engineering.”

Xamarin helped Nativo Labs build the app much faster than if they were learning iOS development from scratch because the team was able to make use of their existing C# skills. “With Xamarin, the three of us were able to build an app in just six months,” says Costa.

Simplified Cross-platform Development

The app earned five stars in the Apple app store, at one point reaching the top App Store position in Portugal. With this success Storyo, Nativo Labs decided to build a version targeting Android. “None of us had worked with Android before starting this project; it wouldn’t have been possible to do it at all without a tool like Xamarin,” says Vasconcellos. “It helps a lot in the bridge to different operating systems, as in our case when we started with iOS and moved the code to Android.”

“We released the Android version at the end of December,” he continues, “and it was reasonably easy to do. We did the app data using SQLite and rendering is being done through OpenGL, so all of that code is being shared between iOS and Android. With Xamarin, all of the mathematics, all of the tough algorithms are written in C#, and you can share everything with a different operating system very easily.”

Unlimited Possibility

The Storyo app has attracted significant attention from a range of other companies, including music festivals, major consumer brands, and mobile technology companies as a way to engage users more deeply. “With Storyo, a brand can be layered on top of user-generated stories, enabling people to co-create content with the brand,” says Vasconcellos. For example, if a family was visiting a theme park, they could use Storyo to create a photo story, and a branded theme provided by the park would be suggested to them. The user gets a fun way to commemorate their experience without any added effort, and the park gets to extend their brand out into the world.

With the help of Xamarin, Storyo is already hard at work on a new version of the app, pushing the boundaries in terms of what data can say about us and our experiences. “We’re using contextual data and metadata to take photo-based storytelling to the next level. So, for example, groups could use Storyo to tell a group story with different sources of contextual data, which is really cool,” says Costa.

View the Case Study

The post Storytelling App Storyo Goes Cross-Platform with Xamarin appeared first on Xamarin Blog.

November 10, 2015 4:42 GMT

Bayesian Probability

[Originally posted Oct. 12, 2009]

Spent the early hours of this morning reading a great blog post by Jeff Atwoodwhich makes reference to a Elizer S. Yudkowsky’s Intuitive Explanationof Bayesian Probability. The timing was good as I had just finished the (highly recommended) book The Drunkard’s Walk which agreed with Jeff that most humans simply are not wired to deal with probability very well.

The Drunkard’s Walk: How Randomness Rules Our Lives (Vintage) (9780307275172): Leonard Mlodinow: Books
ISBN: 0307275175
ISBN-13: 9780307275172

Yudkowsky poses the following canonical problem:

1% of women at age forty who participate in routine screening have breast cancer. 80% of women with breast cancer will get positive mammographies. 9.6% of women without breast cancer will also get positive mammographies. A woman in this age group had a positive mammography in a routine screening. What is the probability that she actually has breast cancer?

The frightening thing is that according to Atwood, only 15% of doctors get this right. And they’re off by a lot. That is, the average answer is in the range of 80% while the correct answer is 7.8%.  Apparently, there is something about the way we think about the problem that makes 7.8% hard to accept, and Yudkowsky does a great job of walking you through the logic in painfully small steps.

To me, however, there is a pretty straight-forward way to think about this (though it may only be intuitive since I’ve been through this a few times).

What Do We Know & What Does It Imply?

We have three pieces of information:

1% of sample are TRUE  (that is have cancer)

80% of sample who are TRUE will test TRUE

9.6% of sample who are FALSE will test TRUE.

On the face of it, we should guess that the percentage of women who test TRUE who actually are TRUE (test positive and actually have cancer)  is pretty small based on two facts provided: the actual percentage of women from the sample who are TRUE (regardless of testing) is only 1%, and the test has a false positive for 9.6% of those tested.

So, my reasoning to solve this is:

1. Assume we have a sample of 1000 women (I use 1000 to reduce the amount I have to talk about fractional people, but I don’t use 10,000 as I get lost in the zeros).

2. We know that the reality is that of the 1,000 women, 10 will have cancer (1%).

990 = no cancer
10 = cancer

3. Of the 10 who have cancer, 8 will test positive
8 out 1000 women tested will test True and are True

4. Of the 990 with no cancer 9.6% will also test positive = 990 * .096 = 95.04.
95.04 women out of 1,000 will test True but are False.

5. The total number testing true is 8 + 95.04 = 103.04.
Of these, 8 actually have Cancer.

6. So the value for tests positive (103.04) versus is positive (8) is 8:103.4 or 0.773  or 7.8%
(8 of the 103.4 = 8/103.4)

Not Being Misled

The key to this and many problems like it is to realize that what you are trying to find is the relationship between those who Test positive vs. the reality of those who are positive, which is why you need all three numbers.

Probability is Weird and Cancer Is Scary

True story: I have a friend who is the head of breast cancer surgery at averyrespected hospital. I was at a dinner party where he mentioned that a “very small percentage of those who show up with a positive test actually have cancer.”  This caused a lot of confusion, and that is because we (a) don’t deal with probability well and (b) don’t understand policy tradeoffs as a result.

From a policy point of view, it is too expensive (money, time, etc.) to test everyone with a biopsy, etc.  The preliminary screening is sufficient to move your knowledge from the general 1% probability to the more specific 7.8%, which is enough to pursue. The fact that 20% of women with cancer will get a false negative doesn’t mean that it is better to test everyone, and the fact that out of every 1,000 tested 95 will falsely test positive (and be subjected to needless worry) also does not mean that it isn’t worth using the screening test.

That said, it would be good if, before you took the test, you were told that a positive result means you have less than an 8% chance of actually being positive and that in any case, the test doesn’t change the reality of whether or not youarepositive!

This kind of confusion leads to people not flying to countries where there has been a terrorist incident but happily driving across country.

It is estimated that after the 9/11 attack, more people lost their lives by choosing to drive when they otherwise would have flown than were killed in the actual attack.

November 10, 2015 3:58 GMT

Wave Engine: Frustum Culling

Below recipe belongs to Wave Engine’s official Documentation wiki.


Frustum Culling is the technique which does not draw those things which are out of the camera scope. Wave Engine has enabled by default such algorithm, but it is important to highlight some key points in order to assure its correct behavior. You can read more on Frustum Culling technique here.


Every Drawable2D and Drawable3D component supports Frustum Culling technique through the CullingEnabled and FrustumCullingEnabled properties, respectively, which are true by default. In order to Wave Engine detect whether an object is inside or outside the scope of the camera, such needs to pack a collider. Please refer to Detect 3d collisions and Detect 2D collisions which focus on how to work with colliders -this will not be covered here.

FrustumCulling sample graphically shows entities dis/appearing on demand, with a mesh representing the frustum culling area.

With Wave Visual Editor

Since Wave Visual Editor supports seeing in real time the current scene rendered, it also supplies diagnostic info, with culling counters included. Follow Activate diagnostics modeto achieve this. The “Culled” label which will be printed on the top left corner of the Viewport will do just that.

With Visual Studio/Xamarin Studio

This technique can be disabled globally also through RenderManager‘sFrustumCullingEnabled property, setting it as false.

Further, this recipe does not involve source code which would require Visual Studio/Xamarin Studio.


Wave Engine has built-in support for Frustum Culling technique, which does not draw those meshes which are out of the camera scope. Such is activated by default, but require entities to pack a collider.

November 09, 2015 10:28 GMT

Getting Started with Handoff in iOS

handoff_iconThe users of your application should always be at the center of the functionality you implement. With the beautiful, seamless user experiences that exist in popular mobile apps today, users have high expectations for a great mobile experience. Adding handoff to your iOS apps helps easily deliver a seamless user experience between Apple devices logged into the same iCloud account. Also known as Continuity, Handoff was introduced by Apple in iOS 8 and OS X Yosemite. It allows users to start an activity on one of their Apple devices and continue that same activity on another of device. Have you ever noticed an app icon on the bottom left corner of your iPhone’s lock screen? This was an app giving you the option to continue an activity that you had already started on your iPad or your Mac. In this blog post, I will explain how to implement handoff in your iOS apps and the improvements Apple has added to the Handoff APIs in iOS 9, specifically to NSUserActivity.

Introducing the NSUserActivity

One thing that you need to know for this blog post is exactly what a NSUserActivity is and how it works. The NSUserActivity class is the primary object in a Handoff exchange and is used to encapsulate the state of a User Activity that is available to pass between Apple devices. Here’s a diagram of what a Handoff looks like:

Handoff Diagram

In this diagram you’ll notice that the devices need to be logged into the same iCloud account. You can get more details about NSUserActivity class from Apple’s documentation.

NSUserActivity for iOS 9

In iOS 9, the NSUserActivity class that is used for Handoff now gives developers some additional benefits. In iOS 8, Activities were only used for Handoff, but with the release of iOS 9 Activities are used for App Search, Siri Suggestions, and Siri Smart Reminders. This means it’s very easy to add App Search capabilities to an app that is already using Handoff, or vice versa!

How To Implement Handoff

Implementing Handoff in a Xamarin.iOS app requires you to create a User Activity Object, update the object’s state to track the activity, and continue the activity on a receiving device. For this post, we are going to use an app that has four tabs, each with a web browser in them, and Handoff the most recent tab to another device.

Note: Please make sure you enable Handoff in your Xamarin app before you start adding the new functionality.

Getting Set Up

1. Add NSUserActivityTypes to your info.plist.

a. Since I have four tabs in my app, I’m going to add four Activity Types to my info.plist file like this:

Activity Types





2. Add NSUserActivity constants to AppDelegate.

a. Notice that my constants are consistent with the values in my info.plist.

public NSString UserActivityTab1 = new NSString ("com.xamarin.monkeybrowser.tab1");
public NSString UserActivityTab2 = new NSString ("com.xamarin.monkeybrowser.tab2");
public NSString UserActivityTab3 = new NSString ("com.xamarin.monkeybrowser.tab3");
public NSString UserActivityTab4 = new NSString ("com.xamarin.monkeybrowser.tab4");

Creating a NSUserActivity

In my app, I want to create a new NSUserActivity each time a user enters a new URL in the WebView.

1. On each ViewController, I want to add a public NSUserActivity object:

public NSUserActivity UserActivity { get; set; }

2. Now, in the method used to navigate to a new URL, I’ll create a new NSUserActivity (after invalidating the existing one:

if (UserActivity != null) {
     UserActivity = null;
UserActivity = new NSUserActivity (ThisApp.UserActivityTab1){
     Title = "Weather Tab",
     SupportsContinuationStreams = true

3. Finally, I’ll add some User Info to the new Activity and I’ll make it the Current activity.

var userInfo = new NSMutableDictionary ();
userInfo.Add (new NSString ("Url"), new NSString (url));
UserActivity.AddUserInfoEntries (userInfo);
UserActivity.BecomeCurrent ();

Continuing an Activity

1. Add a PerformHandoff method to each ViewController:

public void PerformHandoff(NSUserActivity activity)
     var url = activity.UserInfo ["Url"].ToString ();
     URL.Text = url;
     WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url)));
     UserActivity = activity;
     UserActivity.BecomeCurrent ();

2. Add properties to UIApplicationDelegate for each ViewController so that I can access the PerformHandoff method I just implemented:

public FirstViewController Tab1 { get; set; }
public SecondViewController Tab2 { get; set;}
public ThirdViewController Tab3 { get; set; }
public FourthViewController Tab4 { get; set; }

3. Override the ContinueUserActivity method in App Delegate:

public override bool ContinueUserActivity (UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
     switch (userActivity.ActivityType) {
          case "com.xamarin.monkeybrowser.tab1":
	       Tab1.PerformHandoff (userActivity);
	       completionHandler (new NSObject[]{Tab1});
	  case "com.xamarin.monkeybrowser.tab2":
	       Tab2.PerformHandoff (userActivity);
	       completionHandler (new NSObject[]{Tab2});
	  case "com.xamarin.monkeybrowser.tab3":
	       Tab3.PerformHandoff (userActivity);
	       completionHandler (new NSObject[]{Tab3});
	  case "com.xamarin.monkeybrowser.tab4":
	       Tab4.PerformHandoff (userActivity);
	       completionHandler (new NSObject[]{Tab4});
     return true;

Additional Resources

We have a detailed Introduction to Handoff guide that has more screenshots and details on how to gracefully handle failures with handoff, best practices, and more. There’s also a sample handoff app for iOS 8 that you could easily add some code to that makes each of the NSUserActivity used for Handoff searchable through spotlight.

The post Getting Started with Handoff in iOS appeared first on Xamarin Blog.

November 09, 2015 6:25 GMT

Live Coding with Xamarin iOS

TLDR; I wrote a new Xamarin Studio add-in that dramatically reduces the number of Build and Run cycles you need to perform while developing an app. Please follow the instructions to install Live Code and let me know what you think!

I Love My History

Since the beginning of time, there has been one limitation of running .NET code on iOS using Xamarin - System.Reflection.Emit doesn’t work. That means you cannot dynamically create executable code.

It’s not a serious limitation. .NET has had this ability for years but, as a community, we really only use it for one purpose: to make code fast. In that vain, this missing feature hasn’t really been a problem for us because the slow path is often just fine.

But there’s a second use of Emit: improving the development experience with things like REPLs.

While mono spear-headed the “C# Interactive” movement with the csharp REPL, they hadn’t been able to give us that tech when running on iOS.

Until now.

Xamarin Inspector

Xamarin has released their Xamarin Inspector tool that acts like the developer tools that you get with web browsers.

It’s really nifty. On one hand it gives you an inspectable visual tree of your live-running app - just like the DOM in a webapp. They even have a cool layer breakout 3D view.


On top of that, there is a REPL so that you can type in C# code and see the result. This acts like the “Command” window in the browser dev tools.

Put these two together and you have a fantastic tool to diagnose what a mess you made of the view hierarchy. ;-) Click the link above and install the Inspector, you won’t regret it.

Yes, And

Yes Xamarin Inspector is great, and I want to see more tools along these lines. I especially can’t wait to see if Xamarin uses this tool to help us write UI tests.

And yet, I have always been a bit unenthusiastic about classical REPLs. Surely it’s fun to have a command prompt and play around a bit, but I have never been comfortable with the fact that you are not working with “real code” - the code that actually gets built to ship your app.

Since the second dawn of time, IDEs have integrated REPLs with real code with a simple trick: they allow you to select some code from your real code and send that over as a snippet to the REPL.

Even this stupid little convenience makes a world of difference. I use the heck out of F# Interactive which gives me this exact feature, and it’s amazing.

Thanks to this tool, I find myself doing full app builds far less often.

Builds are the enemy for two reasons:

  1. They lock up the IDE as you wait for big compilers to do their thing and as you wait for your app to restart. Of course, the IDE isn’t frozen, but my mental state is. I cannot edit code because I might screw up the compilation and because the debugger will get lost. So I go into a mental spin-loop watching the progress bar. It’s not healthy. (I used to check Twitter, but fixed that with an edit to /etc/hosts.)

  2. Second, they re-initialize your context. If I’m working on one part of my app that’s far removed from the initial screens, then I have to dig back through the app to get to seeing what I’m actually interested in. If I was a better automated test writer, or a better designer, or a better planner, this wouldn’t be such a problem. But back to the real world…

A little while ago, I took a stab at doing something different from the REPL and wrote Calca. After some futzing around I found an environment that allowed me to see results as quickly as I could type them and it didn’t have the annoying necessity to keep sending code to the evaluator.

I want something like Calca for my day to day work. I want to write code and see the results immediately.

Xamarin Released Something Awesome and I Hadn’t Realized it Yet

While watching James Montemagno’s live stream on the Inspector, I started to wonder how it worked.

I started to wonder if Xamarin snuck in dynamic assembly support into their newest versions. I wrote a quick app that referenced Mono.CSharp which hosts mono’s awesome dynamic evaluator, then tried to run the evaluator and got what I expected:


No dynamic code for you.

After James finished up, I installed the Inspector and laughed at some of my view hierarchies. Great tool.

And on a whim I ran my test app again, and you won’t believe what happened next. The stupid thing ran.

That’s right, installing Xamarin Inspector makes dynamic assemblies work. (On the simulator at least.) I don’t know what dark and old magic makes this possible but the Xamarin engineers have come through again.

Well, we’re given a hint into this dark magic. In the Inspector docs, this passage appears as a “known limitation”:

As long as the Inspector addin/extension is installed and enabled in your IDE, we are injecting code into your app every time it starts in Debug mode

Haha, they call that a limitation. Dear Xamarin, enabling dynamic assemblies in all apps, at least in the development environment, is not only OK but please keep doing it. Please don’t see this as a limitation - this is a feature I never knew was possible and I don’t want to lose it.

When I saw my test program successfully evaluate code dynamically, I was aghast. Shocked because I didn’t expect it to work, and horrified that by all the ideas that occurred to me. With great power comes great, oh forget it.

An Idea

Little known fact: I spam Xamarin with bug reports and feature requests on a monthly basis. They are very tolerant of me and I appreciate it.

One of my last crazy ideas was a tool that I want to see integrated into the IDE that would enable live coding scenarios - all in an attempt to break the Build and Run cycle. It was a play off of Inspector with a little bit of influence from Example Centric Programming (pdf).

The whole premise was that I wanted to see live evaluations of whole classes and modules while I was working on them without having to manually send snippets to a REPL. I wanted the tool to monitor certain classes and to visualize them whenever I changed them.

Imagine creating a UI layout. We have two options: we can use a designer or we can write it in code. With a designer, we pay the price of being separated from logic but are awarded with instantaneous feedback (or instantaneousish if using autolayout). With code, we have the full power of logic and data, but are stuck with the Build and Run cycle.

With live code, we can have the best of both worlds. We write the UI using code, but we see the effects of our code instantaneously.

Time to Hack

In two days I have been able to put together on tenth of the tool I described in my email. But even this small version of it has me really excited.

It is able to do two things:

  1. Send code to the iOS simulator to be evaluated and then visualized. This is to enable classic scenarios where I sometimes just want to know the value of a particular expression.

  2. Monitor whole classes that are evaluated and visualized whenever they are edited. This makes creating UIs super fun and is the part I’m most excited about.

Please go follow the instructions to run it and let me know what you think. (This only works in Xamarin Studio.)

I am not sure how well words can describe the tool, so I took the time to record a video of me using it. The video’s a bit long, but I think you can get the general idea after just a few minutes (and if you skip the first 6 minutes describing installation).

Check it out:

Now What?

I hacked together a cool little tool that I’m pretty sure will become an invaluable asset. I still want to implement more of the features I described in my original design and make it work on other platforms.

Speaking of platforms, there is one major limitation: it only works in C#. While most won’t see that as a limitation, I have been doing a lot of coding in F# lately and would prefer the tool to work with that.

Unfortunately F# doesn’t ship with a simple compiler service like Mono.CSharp and I haven’t tried yet to get the compiler to compile itself under Xamarin. I’m sure that this is technically possible, but gosh that F# compiler is intimidating and I don’t know where to begin.

I’m also interested in seeing how much feedback this blog post and tool get. I often wonder if I’m just a nutter for hating Build cycles and can’t wait to be validated or invalidated by your response.

So say hello to me @praeclarum on Twitter and let me know if any of this looks good to you.

November 09, 2015 2:40 GMT

Testing Xamarin Apps: Screen Object Pattern

Writing UI tests for Xamarin is awesome and easy using Xamarin.UITest, which allows you to write tests in C# that work across both iOS and Android. It provides a nice API to interact with your apps from test code, allowing for performing many common tasks for interacting with an app such as tapping elements, entering text, scrolling, swiping, etc.

Typical UI Tests

Using a tip calculator app as an example, here's what one such test might look like:

public void BrittleAndSadTest()  
    app.EnterText("SubTotal", "100.00");
    app.EnterText("TipPercentage", "20");

    var tipText = app.Query("TipAmount").First().Text;
    var totalText = app.Query("Total").First().Text;

    Assert.AreEqual("Tip: $20.00", tipText);
    Assert.AreEqual("Total: $120.00", totalText);

The test enters values in the text fields for sub total and tip percentage, queries the resulting tip amount and total out of the UI, and then asserts the values are correct. Pretty awesome, right? With just a few lines of code we're verifying the expected behavior from the app from the same perspective as a user, ensuring the app is producing the expected results.

The Problem

One problem with this test is that in addition to validating the behavior of the app, it also has knowledge of how to query the values out of the UI. This is a very common pitfall in UI tests on any platform, and can lead to very brittle tests that start failing quickly as the UI evolves and the tests fall out of date.

All too often I've seen this result in failing tests being ignored as they become incompatible with updated interfaces, and ultimately they get abandoned completely. Thankfully, there's a good solution to this that you should keep in mind right from the start when writing UI tests.

Screen Object Pattern

If you're familiar with writing automated tests for the web using libraries such as Selenium you might already be familiar with the Page Object pattern. This is a pattern that works on any UI platform, and is not limited to just web applications. When working with mobile applications I personally like to refer to this as the Screen Object pattern, but it's still effectively the same thing so feel free to use whichever term you prefer.

The basic idea is that instead of each test having deep knowledge of the UI and how to query it, you define classes that represent each screen and expose the appropriate methods and properties to interact with it. In this model, the screen class is the single place that needs to know how to find elements in the UI so if things change around and the queries need to be updated, you only need to update them in one place. On the other end, consumers of the class (e.g. the tests) get a nice typesafe API for interacting with these screens. This results in more readable and maintainable tests in the end.

Refactored Tests

Let's take a look at what a screen object might look like for this screen:

class TipScreen  
    private readonly IApp _app;

    public TipScreen(IApp app)
        _app = app;

    public void EnterSubTotal(decimal subTotal)
        _app.EnterText("SubTotal", subTotal.ToString());

    public void EnterTipPercentage(int percentage)
        _app.EnterText("TipPercentage", percentage.ToString());

    public string TipText => _app.Query("TipAmount").First().Text;
    public string TotalText => _app.Query("Total").First().Text;

There's not much magic here, which is really the point. The queries for interacting with the UI are all contained here, and exposed are simple methods for interacting with the screen. You can also see that the .ToString() calls on sub total and tip percentage are encapsulated inside of this class as well, so the exposed methods provide a nice typesafe API.

With this screen object in place we can update the test to make use of it:

public void DurableAndAwesomeTest()  
    var screen = new TipScreen(app);

    Assert.AreEqual("Tip: $20.00", screen.TipText);
    Assert.AreEqual("Total: $120.00", screen.TotalText);

Not only is the test more durable and resistant to change, it's also far more readable now. Instead of being polluted with all the noise of UI queries, it now clearly shows the scenario being tested and the expected results of it.

If you're writing any sort of UI tests, even very simple ones, I highly encourage you to start following this pattern. It makes it easier to write more tests and keep your apps stable and covered, and vastly improves the odds of you either losing a lot of time to keeping them up to date as your UI evolves, or even worse, ultimately abandoning them entirely.

Happy testing!

November 09, 2015 1:56 GMT

Automatiserade UI-tester på mobila enheter

Intresserad av effektiv testning av mobila enheter? Med Xamarin TestCloud kan man köra automatiserade UI-tester på mer än 1800 fysika iOS och Android enheter. Jag har skapat en kort introduktion på ca 10 minuter.

November 09, 2015 10:33 GMT

MvvmLight Navigation Extension

When navigating in iOS we can choose to do a modal navigation. That means that we open a page that is on top of the other pages and not included in the navigation stack. When using MvvmLight we only have one method (NavigateTo) when we want to open a new page.

While I want to use MvvmLight and open “modals” I have created a MvvmLight extension for iOS (for storyboards only in this pre version) and Android, If you’re interested in the source, it will be at GitHub,

While this is a pre release, feedback is very welcome!

Using the extension from shared code
To use it in your ViewModels you need to add the namespace to the class.

using MvvmLightNavigationExtension;
var navigation = ServiceLocator.Current.GetInstance<INavigationService>();

We will configure the NavigationService in same way as when we using NavigationService from MvvmLight but we using NavigationServiceExtension() instead of NavigationService and our instance of NavigationServiceExtension should be registered to both INavigationService and INavigationServiceExtension.


 var nav = new MvvmLightNavigationExtension.iOS.NavigationServiceExtension();
 nav.Configure("Page1", "MainView");
 nav.Configure("Page2", "PageView");


 var nav = new MvvmLightNavigationExtension.Droid.NavigationServiceExtension();
 nav.Configure("Page1", "MainView");
 nav.Configure("Page2", "PageView");
November 09, 2015 9:55 GMT

FreshMvvm n=2 – IOC and Constructor Injection

Here’s the next video in the  FreshMvvm n+1 series. The idea of this series is to get the video’s out to the eager listeners (you) as quickly as possible, therefore these videos are done live with almost no editing.

Episode Title: n=2 – IOC and Constructor Injection

In this episode we discuss:

  • Review FreshMvvm’s built in IOC container
  • Setup a decoupled Data Service with interface
  • Use the PageModel Constructor Injection
  • Use a 3rd Party Library in the IOC Container

I hope you enjoy.



The post FreshMvvm n=2 – IOC and Constructor Injection appeared first on Michael Ridland.

November 07, 2015 7:51 GMT

52 Weeks of Xamarin: Week 13 – Writing It Thrice

In this and a number of following posts, I’ll build the same program three times: once in Xamarin.Forms, once in iOS and once in Android.  ToDoListForms

This is directly based on my Pluralsight course, Beginning Mobile Development with Xamarin

To get started, we’ll go through the Xamarin.Forms application fairly quickly as this series has already covered a lot of material on writing Xamarin.Forms applications.   Let’s begin by creating our model class: ToDoItem

We know we want to save the data to a SQLite database, so we’ll add an ID field and the necessary attributes:

 using System;
 using SQLite;
 namespace ToDo {
     public class ToDoItem {
         [PrimaryKeyAttribute, AutoIncrement]
         public int ID { get; set; }
         public string TaskName { get; set; }
         public string Priority { get; set; }
         public DateTime DueDate { get; set; }
         public bool IsDeleted { get; set; }

Create Page

We start by creating our first page, CreateToDo, and its associated file CreateToDoViewModel.  CreateToDo.xaml provides the UI, which includes the buttons Save, Cancel and Review.  Here is the complete XAML page,

 <?xml version="1.0" encoding="UTF-8"?>
         Text="New Task"
         FontSize="18" />
         Placeholder="New To Do Item"
         WidthRequest="150" />
         WidthRequest="150" />
           Text="Due Date"
           TextColor="Green" />
         <DatePicker x:Name="Date"/>
           Text="Due Time"
           TextColor="Green" />
         <TimePicker x:Name="Time" />
         Orientation="Horizontal" HorizontalOptions="Center">

In the code behind we set up the ViewModel.  The constructor is overloaded, either to initialize the vm and the components, or to also retrieve the designated record from the database.

         public CreateToDo(int id) {
             vm = new CreateToDoViewModel();
             BindingContext = vm;
             ToDoItem toDoItem = App.Database.GetToDo(id);
             ToDo.Text = toDoItem.TaskName;
             Priority.Text = toDoItem.Priority;
             Date.Date = toDoItem.DueDate;
             Time.Time = toDoItem.DueDate.TimeOfDay;
             updateID = id;
         public CreateToDo() {
             vm = new CreateToDoViewModel();
             BindingContext = vm;

OnCancel calls clear which just resets the input.  OnReview will push to the review page (covered next week) and OnSave delegates to the ViewModel the job of saving the contents of the input fields,

 public void OnSave(object o, EventArgs e) {
 public void OnCancel(object o, EventArgs e) {
 public void OnReview(object o, EventArgs e) {
     Navigation.PushAsync(new ListTasksPage());
 private void Clear() {
     ToDo.Text = Priority.Text = String.Empty;
     Date.Date = DateTime.Now;
     Time.Time = new TimeSpan(
           DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

The View Model

The work of saving a new task is as simple as taking in the input from the user and then assigning each value to its appropriate property in the model.  The only complexity is in transforming the due date, which is done with a helper method,

 public void AddTask(string todo,
                     string priority,
                     DateTime dueDate,
                     int hour,
                     int minute,
                     int second,
                     int updateID,
                     bool isDeleted) {
     var newToDo = new ToDoItem {
         TaskName = todo,
         Priority = priority,
         DueDate = SetDueDate(dueDate, hour, minute, second),
         IsDeleted = isDeleted,
         ID = updateID,
 public DateTime SetDueDate(DateTime date, int hour, int minute, int second) {
     DateTime retVal = new DateTime(
     return retVal;


As we’ve seen in previous entries in this series, you will need an interface for SQLite and a file, which I’ve called ToDoDatabase which will get the Connection through the DependencyService, create the table and do the CRUD operations.  I won’t reiterate all that code here as it is shown in earlier entries.

Next week: the review page, and then on to iOS and Android.  I’ll take the latter two much more slowly as we’ve not seen as much of native code in this series.

November 06, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #65

Watching some Xamarin.Forms TV
I (adam) am back! Check out my new site XForms.TV and some brand new shows and episodes.

Don’t delay: Try RC1 today!
Miguel de Icaza, from Xamarin Inc., announced a new release candidate.

Keep Users Engaged with iOS 9’s SFSafariViewController
Mike James, from Xamarin Inc., shows you how to display web content in iOS 9.

New Preview: Xamarin Inspector
Miguel de Icaza, from Xamarin Inc., announces the release of the Xamarin Inspector. I hear a Xamarin.Forms version is in the works.

New & Improved Google Play Services for Android
Jon Dick, from Xamarin Inc., it’s smaller, enumerable and Async-able now.

MvvmLight and Xamarin.Android
Daniel Hindrikes, shows you how to hook up Xamarin.Android and MvvmLight.

14 Days To Building An Enterprise Quality Xamarin Forms App
Adam Pedley, has a new site and a 14 part series about Xamarin.Forms Here is day 1, 2, and 3.

Taking Advantage of The (iOS 9) Universal Links on Xamarin iOS apps
Has AlTaiar, from Kloud, is getting into universal links to mobile applications.

Is Your App Ready For iOS 9?
Krystin Stutesman, from Xamarin Inc., covers the most popular and important features of iOS 9.

FreshMvvm n=1 : Your first FreshMvvm Application
Michael Ridland posts live video of him working through his first FreshMvvm app.

Xamarin: Developer Events in November
Jayme Singleton, from Xamarin Inc., has all the developer events for November.

Xamarin iOS swipable multiple step process used for on-boarding
Alwyn Lombaard, from Just Giving, gets users started the right way.

What’s new on XForms.TV

Xplat: Movie Bucks Ep1

Let’s get started making a new Xamarin.Forms cross-platform app. This time we will make a one page app to help us budget our movie money and escape the movie with our wallet intact.

P & C: Xamarin.Forms Label

In this episode of the “Pages and Controls” show we’ll go over the basic properties of the Xamarin.Forms Label, spend a little time on formatting, then dive into some advanced waters with FormattedText.

XS Lab: Search to Navigate

In this episode of Xamarin Studio Lab, we’re going to take a look at Xamarin Studio’s search and “navigate to” keyboard shortcut. These two features of Xamarin Studio make it easy to move around your project without using your mouse.

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

November 06, 2015 12:30 GMT

Watching some Xamarin.Forms TV

Xamarin.Forms is missing something. At first, I couldn’t put my finger on it. Then it hit me. It needs it’s own TV station. A place to watch and learn about Xamarin.Forms, Xamarin Studio, and cross-platform development. Don’t get me wrong, we have other options but I think we can do better.

Xamarin.Forms TV

I’m very happy to announce my new Xamarin.Forms TV station XForms.TV. I have wanted to do this for a while and since we only live once, today is the day it goes live. The station is starting off with a few show.

XForms.TV Shows

Xamarin Studio Lab
Each episode of the Xplat (Splat) show will show you how to build simple cross-platform application for Apple and Android phones.
Author: Adam Wolf | Seasons: 1 | Episodes: 1 | Channel: App Construction
Season 1

In the Box Show
Xamarin.Forms comes with over 40 different UI components. Learning how these Pages and Controls work and interact with each other is the first step in learning and mastering Xamarin.Forms.
Author: Adam Wolf | Seasons: 1 | Episodes: 1 | Channel: UI Central
Season 1

Xamarin Studio Lab
Knowing how to use Xamarin Studio is just as important as knowing how to use Xamarin.Forms for building cross-platform mobile apps. Each episode of XS Lab will focus on Xamarin Studio tips, tricks, add-ins and techniques that will make you a better mobile developer.
Author: Adam Wolf | Seasons: 1 | Episodes: 1 | Channel: Tool Time
Season 1

Coming Soon

There are only a few hours in the day but soon 2 new shows will be added to XForms.TV and both are unapologetically target at Xamarin.Forms and cross-platform developers.

Xamarin.Forms is a wonderfully capable UI framework with a little diligence and common sense great cross-platform apps can be built with it. These two shows will show you all the features of Xamarin.Forms and show you just how capable the framework is.

In the Box Show
Building cross-platform UI’s with Xamarin.Forms is nothing to get angry about. The Joy of Forms show will guide you on how to assemble great looking cross-platform UI from scratch. Home made Xamarin.Forms, Yum!

In the Box Show
Xamarin.Forms is more than just a bunch of pages and controls. Each episode will cover one service or feature to make your cross-platform application more capable and easier to develop.
It’s a wonderful and kind of scary to put out into the world but I think it’s something we need. I hope you watch a few shows, learn a few things and let me know what you think.

The post Watching some Xamarin.Forms TV appeared first on Syntax is my UI.

November 06, 2015 12:00 GMT

Quick Dump of Things I’ve Learned This Week Developing on Apple Watch

It turns out we’re lately at Plain Concepts working on a few iOS apps which involve Apple Watch. And we’re using Xamarin. :-) The one I’m working on is quite simple, but I’ve learned a few things which can be interesting to any other one making a first landing into a similar project.

I’ve noticed some differences with Storyboards on iPhone/iPad (iPod Touch keeps alive?) By default, the Watch App’s UI lives inside an stack layout. You drop an element, it stacks at the bottom of the last one. It opens an small world of interesting effects, as you can hide/show elements to simulate different states of the app life-cycle.

AutoLayout? Well, no more. Margins to the Watch edges aren’t longer needed, since the bezel implicitly has those. Just assume it’ll look good on the device. And labels, buttons, etc. look good also when stacked. Simply I haven’t seen my-self needing those, although we’ve been able to reproduce our Design quite good.

Group is also a joy: just be aware you can set an image as background, it opens also more possibilities.

Typefaces can’t be modified within the Designer, it must be done from the Controller:

var attrString = new NSAttributedString("Foo", 
    new UIStringAttributes 
        Font = UIFont.SystemFontOfSize(14, UIFontWeight.Medium) 

Strip-like animations can be easily done. Just add the whole list of images to the App’s Resources, with a common patten such like “stripX.png”, where X is a number, and the following code will do the rest for you (here the animation is set on a Group’s background, step is an int with a value within the strip limits):

countdownGroup.StartAnimating(new NSRange(0, step), 1, 1);

WormHoleSharp is our friend (James Clancey, thanks for your effort). If the app is quite small, and only needs iPhone to Watch communication, you may find it better to lay on AppDelegate.HandleWatchKitExtensionRequest(). Stop! It can be tricky, at least under my opinion, to forward the communication through the AppDelegate (messaging, for instance, can be an option). Instead, it’s much more elegant, wherever you need to send/receive info (did I mention you can also send info from the Watch back?), to do something like:

    new FooMessage 
        Text = "Hello, Watch!" 

And… that’s all for now. Maybe those small things make you landing on Apple Watch easier.

Happy weekend!

November 03, 2015 8:46 GMT

Mountain Weather UK goes live!

AppIcon1024-512It’s been 12 months in the making and over the last 4 months I haven’t even had time to post on this blog because all my spare time has been devoted to finishing and finally publishing my mountain weather app. Well, finally I am excited to announce the release of Mountain Weather UK, the first and only mobile phone app dedicated to mountain weather in the UK.

Simulator Screen Shot 24 Oct 2015 11.23.42_iphone6_gold_side2The App is entirely written in Xamarin Forms using all the things I have blogged about so far. There have been quite a lot of design changes which I have made over the last 4 months to get the app to where it is now and I am very pleased with the results. I have kept the design very clean and simple and taken much inspiration from Material Design. Here are some of the features in the App.

Mountain Area Forecasts

5-day forecasts for all UK mountain regions providing daily forecast summaries, freezing levels, high and low level temperatures, wind speed and directions, visibility, hill fog and mountain hazards.

Mountain Summit Forecasts

5-day forecasts for all major mountain summits in the UK with 3 hourly forecasts covering weather type, temperature, wind speeds, gusts and direction, visibility, precipitation probability, humidity and UV. Easily find mountain summits using the search feature, including regional maps of all major summits.

Weather Station Observations

24-hour observation data for all weather stations in each mountain area, including, Temperature, Wind Speed, Wind Direction and Humidity, including regional maps of all observation stations.

Weather Forecast Maps

36-hour weather forecast Maps including precipitation, cloud, temperature and surface pressure and synoptic pressure charts.


Recent weather forecasts and weather station observations for quick access to all your favourite weather forecast and observational locations.

Nearest Locations

Nearest geographical area and mountain forecasts from your current location. Automatically updated depending on your location.

I hope to be sharing with you over my next few posts some of the things I have learnt and experienced over the last 4 months to get this app to the app stores. It’s been quite some journey!

Download now on iPhone from the Apple App Store or on Android from Google Play or visit the website at

November 03, 2015 9:19 GMT

MvvmLight and Xamarin.Android

Last week I wrote a blog post about Xamarin.iOS and MvvmLight. Now it’s time for the second post about MvvmLight, this time about how to use it with Xamarin.Android.

Because I put the ViewModels in a separate project I can use the same ViewModels for both Android and iOS.

First we install the NuGet package for MvvmLight to the Android project.

Install-package MvvmLightLibs

The ViewModels that we will use is the same as in the iOS app and it will look like this.

public class MainViewModel : ViewModelBase
        private string _name;
        public string Name
                return _name;
                _name = value;
        public RelayCommand Send
                return new RelayCommand(() =>
                        var nav = ServiceLocator.Current.GetInstance<INavigationService>();
                        nav.NavigateTo(Views.Hello.ToString(), Name);                    


MvvmLight has a INavigationService interface that uses for navigation and each platform will have their own implementation. For Android we will do the configuration in MainActivity. Important is to check if navigation already has been initialized. The code will just run once.

      var nav = new NavigationService();            
      nav.Configure(Core.Views.Main.ToString(), typeof(MainActivity));
      nav.Configure(Core.Views.Hello.ToString(), typeof(HelloActivity));
     _isInitialized = true;

In my example I using Autofac for IoC, we can also use the IoC container that is in the MvvmLight package. When we have created the NavigationService we had to register it in the IoC container as a INavigationService.

var builder = new ContainerBuilder();
var container = builder.Build();
var serviceLocator = new AutofacServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);

To navigate we will resolve the INavigationService interface and use the NavigateTo method.

var nav = ServiceLocator.Current.GetInstance<INavigationService>();
nav.NavigateTo(Views.Hello.ToString(), "Navigation paramter");

To retrieve the parameter we are using the GetAndRemoveParameter in the NavigationService class. Note that this is an Android specific method so we have to cast the INavigationService to NavigationService.

var nav = (NavigationService)ServiceLocator.Current.GetInstance<INavigationService>();
var param = nav.GetAndRemoveParameter<string>(Intent);
ViewModel = ServiceLocator.Current.GetInstance<HelloViewModel>();
ViewModel.Name = param;


When using MVVM we want to use data bindings. In Android we have to create the bindnings in code. MvvmLight will help us with that. In the class for the Activity we hade to add a using to the MvvmLight helpers.

using GalaSoft.MvvmLight.Helpers;

The activity also has to inherit from ActivityBase (GalaSoft.MvvmLight.Views.ActivityBase).

public class HelloActivity : ActivityBase

The MvvmLight helper namespace will contains the extension methods SetBinding and SetCommand.

The fields that vi are creating bindings to need to be declared as public in the Activity.

public EditText Text { get; private set; }
protected override void OnCreate(Bundle bundle)
     var button = FindViewById<Button>(Resource.Id.send);
     Text = FindViewById <EditText>(;
     this.SetBinding(() => ViewModel.Name,() => Text.Text, BindingMode.TwoWay);
     button.SetCommand("Click", ViewModel.Send);

The SetCommand method’s first argument will be which event that will execute the command.

I create the ViewModel in the OnCreate method using the ServiceLocator, I prefer to create it with the ServiceLocator directly instead of wrapping it in a ViewModelLocator which is a common way to do it when using MvvmLight.

The complete code for this sample is on GitHub,

November 01, 2015 9:35 GMT

FreshMvvm n=1 : Your first FreshMvvm Application

Here’s the next video in the  FreshMvvm n+1 series. The idea of this series is to get the video’s out to the eager listeners (you) as quickly as possible, therefore these videos are done live with almost no editing.

Episode Title: n=1 Your first FreshMvvm Application

In this episode we discuss:

  • Creating a New Project adding FreshMvvm
  • Automatic wiring of BindingContext
  • PageModel to PageModel Navigation
  • Automatic wiring of Page events (eg. appearing)
  • Basic methods (with values) on PageModel (init, reverseinit)

I hope you enjoy.


Also, if you want to know more awesome things about Xamarin.Forms then my eCourse is a must do! ‘Secrets of a Xamarin.Forms Ninja




The post FreshMvvm n=1 : Your first FreshMvvm Application appeared first on Michael Ridland.

November 01, 2015 8:46 GMT

Mobile App Testing on 114 Devices in 20 Minutes

My day started off just like any other at the office. I plugged in my machine, launched Visual Studio and opened up the latest Xamarin.Android project I had been working on for the client. On this particular day, I had to make a layout change to ensure that the weighting of two different layouts were updated based on a set of conditions. Sounds easy enough, right?

Well making the change was trivial. Next came the part that I dreaded, which I knew would take up the rest of my day. I walked over to the device cabinet, and grabbed a handful of devices varying in screen size, resolution and OS versions.

Seated at my desk, I attempted to power on the first device. Battery drain. I plugged it in, then attempted to power on the next device. Same thing. By the time I was able to get enough charge on a device to power it on, deploy to that device, and run through the necessary tests, 10 – 15 minutes had passed.  Note that I have to repeat this process on 4 more devices. If the tests all pass the first time, that’s about an hour of testing spent on a small fraction of devices for a single UI change. During my round of testing on the 4th device, I already noticed problems with the layout. This is going to be a really long day.

Even if all of my tests pass, QA will perform these tests on another set of devices at random which may uncover other issues. Even worse, what happens if the QA tests passed, and the application made it to market because there were issues on devices we hadn’t covered? This wasn’t the type of work I wanted to deliver. Ultimately, I want to be sure the layouts look good across as many devices as possible, including the most popular ones on the market.

Now what?

A Better Way

Being out of office for the next week, I wanted to get this change completed to ensure it wouldn’t hold the team up in my absence, and I wanted to feel confident that it would look good on a broad range of devices. I knew this would be an impossible feat if I stuck with the manual testing route. I decided to put Xamarin Test Cloud to use to make short work of this.

Thanks to those Xamarin University’s courses on creating Xamarin UI Tests and deploying to Test Cloud – which I had already taken as a requirement for the Xamarin Mobile Developer Certification exam –  I knew exactly how to get started. I also had some Test Cloud time to burn which comes with being a Xamarin University student – 25 hours to be exact.

I created a new Xamarin UITest project, and used REPL to assist with scripting out the steps. I copied the script into my UITest, and I included commands to take screenshots at specific points in the script. This process took about 10 minutes to complete and test on a local device.

Once I was confident that the UITest I had scripted performed as I expected, I decided to run it in Xamarin Test Cloud, simply by right-clicking on the UITest project in Visual Studio and selecting “Run in Test Cloud…” from the context menu. I was able to quickly and easily select 25 devices to run the test on, all of varying screen sizes, resolutions and OS versions. I was even able to select from devices that were most popular on the market, thanks to a filter provided within Xamarin Test Cloud.

Xamarin Test Cloud Device Selection

Within minutes, my test was deployed to the cloud, and 10 minutes later the test had been completed on all 25 devices. This consumed about 35 minutes of Xamarin Test Cloud device time usage (approx. 1.4 minutes per device). Based on the results, I had to tweak the layout and re-run the test two more times until the change looked good across the board, but this process was simple, fast and efficient. Now that I knew how fast it was to test on 25 devices, I decided to push it a little further. The next run was on 114 devices. Twenty minutes later my changes were ready to review. Again, the total device time used averaged out to 1.4 minutes per device.

Reviewing the UI change across all devices was easy, because they were laid out on a single page in grid format. It was easy to scroll down the page and quickly point out any nuances which needed to be addressed. I could even filter and sort the view to quickly see the devices of interest.


Test run results of the Xamarin Store Demo app

What could have been 1 – 2 days of effort for a simple UI change, was completed in less than 2 hours, and I had covered more ground in those 2 hours than I ever would have in manual testing.

In addition to that, Xamarin Test Cloud provided metrics on the application’s CPU and memory usage, as well as device and test logs. The history of all tests run are maintained in my account so I can go back to review them at any time.

Lessons Learned

That was the scenario for the effort needed to test a simple UI change. Now compound that effort with a greenfield application, which requires the team to fully test each screen and feature on as many devices as possible. Expecting that a mobile development team and QA will be able to cover ground through manual device testing is pretty far-fetched. Not to mention the costs the company would have to absorb to continue to purchase new devices as they are released in order to be able to stay on top of a changing market.

Many companies balk at the price of Xamarin Test Cloud without considering how much money is being wasted on the current processes in place.

As the company’s team continues to build out the organization’s flagship mobile app and releases multiple versions, the QA Team becomes swamped and unable to test fast enough to cover ground on all those devices in that trusty cabinet. Developers barely have enough time in the schedule to fully develop the features needed, let alone allot the actual time needed to fully test across devices.

Eventually, the company considers hiring a new QA member to ease the work load. Do you think it is possible to hire someone into that role at $5/hour? No? Well, that’s the cost of Xamarin Test Cloud – $5 per device hour when you break it down. Considering I was able to run a single UI test across 114 devices using about 2.5 hours of device time, that would work out to be the best $12.50 ever spent. Not to mention, that’s also 1 full day of developer time that is reclaimed to focus on the actual development of the product, rather than fiddling around with device after device to run manual UI tests. Last but not least, your QA team will be more focused on testing the application’s functionality rather than being bogged down with logging UI related issues.

If you’re still skeptical at how Xamarin Test Cloud can help accelerate your mobile app testing time, make use of the free 60 minutes of Xamarin Test Cloud time you’re given each month with your Xamarin Platform Subscription.

Final Thoughts

Spend a little, save a lot, and keep your mobile product team happy in the process.


October 30, 2015 2:39 GMT

Spooky Halloween Twilio Hackpack

Halloween is a great holiday to light things up and have a little fun. I woke up a few days ago with an idea in my head for a cool Halloween hack using one of my favorite LED-toting device, the Twilio Hackpack. I've written about the Hackpack before in terms of the basic building blocks but haven't shown much of the cool things you can do with it.

What I built for Halloween is a couple of animated images that can be set on the hackpack using SMS. One of them is a ghost and the other is a bat. They both have blinking yellow eyes. They look like this on the hackpack:


You can change the image on my hackpack at any time by sending the word bat or ghost to:

(215) 584-4678

The code to make the bat and ghost is written using the Adafruit NeoPixel libraries. You can find the completed code in this Github repo.

The backend for handling text messages is written using the Laravel PHP framework. You can find the completed code for the backend in this Github repo.

I hope you have a very spooky Halloween. If you create any cool hacks for Halloween be sure to let me know on Twitter @brentschooley.

October 30, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #64

What’s Next for Enterprise Developers
Steven Yi, from Xamarin Inc., shares his perception for the enterprise developers.

Create a Custom UI Control
Marcos Cobena helps you create your own UI controls.

Use MvvmLight in Xamarin.iOS
Daniel Hindrikes shows you how to use MVVMLight in your Apple apps.

Welcome Xamarin’s Newest MVPs!
Joseph Hill, from Xamarin Inc., welcomes a new crop of MVP to the Xamarin family.

Compartmentalizing logic
Petar Shomov is in love with Redux and it shows.

52 Weeks of Xamarin: Week 12 – Advanced Customized Controls
Jesse Liberty goes a bit deeper and customizes a BoxView.

Xamarin and Oracle Bring Better Mobile Security and DevOps to Enterprises
Rob Ross, from Xamarin Inc., announces Xamarin’s expanded partnership with Oracle.

Picturex Secures Photo Sharing for Enterprises with Xamarin
Jo Ann Buckner, from Xamarin Inc., has another case study of customers winning with Xamarin.

Designing Mobile Apps as a Developer
Krystin Stutesman, from Xamarin Inc., gives us some good tips for designing our apps.


Don't miss out! Subscribe Today

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

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

October 29, 2015 4:10 GMT

Wave Engine: Create a Custom UI Control

We’re at the team finishing the first bunch of recipes synced with 2.0 version of the engine. Let me share with you this one where we explain quickly how to create your own UI controls. Enjoy it!


It is a common pattern to begin a game though a menu: new game, load game, options, etc. Such elements are built by composition of UI controls, like buttons and labels. Wave Engine ships with a list of predefined controls, along with layer types, which can solve multiple situations in your games.

However, what happens if you need an specific UI element which does not exist? This recipe gives a quick hint to cover this question, providing a simple pattern to build a typical alert box, with accept and cancel buttons.


With Wave Visual Editor

This recipe cannot be done just by using the Editor, although it is needed to create the initial project, and choose the 2D camera (UIs work in 2D mode), by cliking on the 3D toggle button from the icons bar. You will notice it switches to 2D, and the Viewport follows accordingly by switching to the default 2D camera.

In order to continue, please keep reading below section.

With Visual Studio/Xamarin Studio

Once the project is correctly set-up following above instructions, open the C# solution through the File menu.

Our alert control will be added like any other Entity, and will have a Show() method with the following signature:

void Show(string message, Action okAction, Action cancelAction)

, where ‘message’ will be the alert’s title, and the two following Action the specific logic to execute upon clicking on accept and cancel buttons, respectively.

The Alert control will inherit Grid, as it fits perfectly to align the internal controls: aTextBlock, and two Button. The firts step it to configure such Grid to handle such:

public class Alert : Grid
    public Alert()
        : base()


        this.IsVisible = false;


By default, the control will be hidden upon creating it, and Show() will “wake” it up on demand when needed.

private void SetUpGrid()
    this.Width = 320;
    this.Height = 240;

    this.IsBorder = true;

    this.HorizontalAlignment = HorizontalAlignment.Center;
    this.VerticalAlignment = VerticalAlignment.Center;

    this.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2, GridUnitType.Proportional) });
    this.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Proportional) });
    this.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Proportional) });
    this.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Proportional) });

As it can be appreciated, the latest lines configure the Grid rows and columns, which will later allow us to place the rest of controls:

private void CreateHeader()
    this.headerTextBlock = new TextBlock
        Width = this.Width,
        Height = this.Height / 3,
        Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        TextWrapping = true,
        TextAlignment = TextAlignment.Center,
        VerticalAlignment = VerticalAlignment.Center

    this.headerTextBlock.SetValue(GridControl.RowProperty, 0);
    this.headerTextBlock.SetValue(GridControl.ColumnProperty, 0);
    this.headerTextBlock.SetValue(GridControl.ColumnSpanProperty, 2);


CreateHeader() must be called within Alert ctor. In the same way, the other two buttons:

private void CreateCancelButton()
    var cancelButton = new Button()
        Text = "Cancel",
        HorizontalAlignment = HorizontalAlignment.Center,
        VerticalAlignment = VerticalAlignment.Center

    cancelButton.Click += (sender, args) =>
        this.IsVisible = false;

        if (this.cancelAction != null)

    cancelButton.SetValue(GridControl.RowProperty, 1);
    cancelButton.SetValue(GridControl.ColumnProperty, 0);


private void CreateOKButton()
    var okButton = new Button
        Text = "OK",
        HorizontalAlignment = HorizontalAlignment.Center,
        VerticalAlignment = VerticalAlignment.Center

    okButton.Click += (sender, args) =>
        this.IsVisible = false;

        if (this.okAction != null)

    okButton.SetValue(GridControl.RowProperty, 1);
    okButton.SetValue(GridControl.ColumnProperty, 1);


The code is almost the same on both cases, but are placed on different spaces within the main Grid.

Finally, Show() will make the control visible again, triggering the specific Action when the user interacts with it:

public void Show(string message, Action okAction, Action cancelAction)
    this.headerTextBlock.Text = message;

    this.okAction = okAction;
    this.cancelAction = cancelAction;

    this.IsVisible = true;

Within a sample use scenario, this would be the final result:

protected override void CreateScene()

    this.alert = new Alert();

protected override void Start()

    this.alert.Show("Would you like to download the game assets?",
        () => Debug.WriteLine("Yes"),
        () => Debug.WriteLine("No"));


You have learned how to extend the existing UI, through composition, to build a new alert control.

October 29, 2015 1:31 GMT

Use MvvmLight in Xamarin.iOS

I think MVVM is a good design pattern to separate UI and business logic. MvvmLight is one of the most popular frameworks for MVVM. In this blog post I will show how you can use MvvmLight when we’re building a iOS app with Xamarin.

The fist step is to create a view model. I always have my view models in a PCL (Portable Class Library) so I can share the view models with other platforms, Android and Windows for example.

When I have created a new project I will install MvvmLight to it. The easiest way to do that is to install the NuGet package for MvvmLight. The package should be added to both the PCL project and the iOS project.

Install-package MvvmLightLibs

When we are working with MVVM all ViewModels need to implement the INotifyPropertyChanged interface. INotifyPropertyChanged has one event handler, PropertyChanged that we have to implement. When using MvvmLight this is done in a base class called ViewModelBase.

In my example the viewmodel

public class MainViewModel : ViewModelBase
        private string _name;
        public string Name
                return _name;
                _name = value;
        public RelayCommand Send
                return new RelayCommand(() =>
                    var nav = ServiceLocator.Current.GetInstance<INavigationService>();
                    nav.NavigateTo(Views.Hello.ToString(), Name);  


MvvmLight has a INavigationService interface that uses for navigation and each platform will have their own implementation. On iOS you need to create a NavigationService and configure it in the AppDelegate class.

var nav = new NavigationService();
nav.Configure(Views.Main.ToString(), "MainView");
nav.Configure(Views.Hello.ToString(), "HelloViewController");

In my example I using Autofac for IoC, we can also use the IoC container that is in the MvvmLight package. When we have created the NavigationService we had to register it in the IoC container as a INavigationService.

var builder = new ContainerBuilder();
var container = builder.Build();
var serviceLocator = new AutofacServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);

If you’re using storyboards you have to use the Configure(string key, string storyboardId) method. The key is just a key that we set to the view, we will use that key when we will navigate to the view. (See the code fore the ViewModel above. StoryboardId is a property that we’re setting in the storyboard designer.


Data bindings

When using MVVM we want to use data bindings. In iOS we have to create the bindnings in code. MvvmLight will help us with that. In the class for the UIViewController we hade to add a using to the MvvmLight helpers.

using GalaSoft.MvvmLight.Helpers;

The MvvmLight helper namespace will contains the extension methods SetBinding and SetCommand.

When binding to a UITextField we can set which event who will trigger an update of the our ViewModel with the method UpdateSourceTrigger. WhenSourceChange is used to set which property in the ViewModel who will be updated.

The SetCommand method’s first argument will be which event that will execute the command.

public override void ViewDidLoad()
           //Creates a binding to a UILabel
            this.SetBinding(() => ViewModel.Name, () => MyLabel.Text);
           //Creates a binding to a UITextField
            this.SetBinding(() => Name.Text).
                WhenSourceChanges(() => ViewModel.Name = MyTextField.Text);
            //Binding a command to the Button.
            MyButton.SetCommand("TouchUpInside", ViewModel.Send);

The complete code for this sample is on GitHub,

October 28, 2015 11:44 GMT

How To Deliver a Great Technical Presentation

Two years ago marked a major shift in my career as a software developer; I transitioned from a full time mobile C#/.NET developer to a full time developer evangelist at Xamarin. Sure, I had attended a few developer conferences in my days, but I had actually never delivered a technical presentation, which may come to a surprise to some. In the past two years I have learned a lot delivering nearly 200 technical presentations, webinars, and workshops. There are a few things for sure is that I have learned a TON on how to deliver a technical presentation and have had a blast having the opportunity to talk to so many amazing developers across the world. I wanted to take a step back for a minute from the mass amount of code that I am often sharing on my blog and write up a few tips and tricks that helped me and hopefully can help you before getting on stage and presenting in front of ten, fifty, one hundred, or thousands of developers.

Prepare that IDE

I can not stress enough how important it is to properly configure your IDE of choice for “Presentation Mode”. On a day to day basis as a developer we have our IDE environment completely customized to our liking and have code spread out between multiple monitors and know every magical keystroke. The problem here is if your audience can’t read or see what you are doing they aren’t going to take anything away from your talk. Here are a few things to get the IDE setup properly.

Stop Using Dark Themes!

I know, I know! You are probably thinking that James has no idea what he is talking about and he has lost his mind saying to use the Light/Blue/Default theme for Visual Studio or Xamarin Studio. Think about it for a second, it is the DEFAULT theme, which means most developers are going to be used to this option of development. Better yet, go stand at the back of the room and attempt to read what you are typing without getting a headache. The Dark Theme of IDEs have a huge contrast between colors and it actually is a strain on your eyes from across the room. Please, please, please stop using the Dark Theme and switch to the default light theme and together we can stop eye strain at conferences.

Use BIG Fonts

This may seem obvious, but text does not always appear bigger when on a projector. Most IDEs default to a 10 or 12pt font, which is nowhere big enough for any attendee to actually read your code. Combine that with the fact that hardly anyone will sit in the front row and the majority of your attendees attempt to sit as far away from you as possible means that you need to crank that font size up. I know it may seem weird at first, but go into your IDE and set your the font to Lucida Console with a minimum of 16pt font. Each projector is a bit different and as of recent I have been presenting with at 24pt font! Best practice here is to take those 10 minutes before your session and open the IDE with some code and walk all the way to the back of the room and see if you can read it. I recommend adjusting the entire IDEs font because scaling each tab in Visual Studio is very painful and you can easily forget during a presentation, so don’t risk it.

Master Zooming

Even though you have adjusted to nice big beautiful fonts it may not be enough some times when you need to highlight and show off your solutions projects or need to highlight something small on the screen. This is where zooming comes in! Learn to master the zoom tools on both Mac and PC and you will surely impress all of your attendees. On Mac OSX, it couldn’t be easier to setup, just go into Accessibility, Zoom, and turn on zooming with a Command + 2 finger swipe in and out. Practice this though so it is a small, slow, and steady zoom so it isn’t jarring for your attendees.

On Windows there are some Magnifier tools built in, but I personally like the ZoomIt tool from SysInternals. With a Control+1 you can zoom in to a specified area and even draw on the screen! So cool!

Turn off those plugins

I am sorry to say, but all of those fancy IDE plugins such as CodeRush and Resharper that you use on a daily basis should really be turned off. Attempt to get your IDE back to as close to a clean install as possible as you don’t want these tools to be distracting and often they can actually hide what you are trying to show by being too clever. Additionally, I never like to show off additional software that needs to be purchased to make my demo look fancy. If it is in the box then show it off else turn it off.

Get your Machine Ready

As you can see I have put some serious consideration into the optimal IDE settings for presenting and now I don’t even adjust my IDE back to how I used to code. I like to make the joke that I code at 20 pt font, and it is true plus I think it is a bit easier on my eyes. How about the actual machine and operating system itself though? There are plenty of small tweaks that can really ensure that nothing unexpected happens during your presentation and that your demo has the full machines resources needed.

Turn off Notifications

There is nothing worse than an email or twitter notification popping up during a presentation! We have all seen it happen as it is easy to forget to hit that little switch in Mac or Windows to disable all notifications. Usually when screen mirroring this is done for you, but why risk it? Simply turn everything off. On Mac OSX simply hit that odd little trip line on the very very top right of your screen. This will bring out your notification center with a hidden setting you can get to by scrolling/pulling down to put your machine in Do Not Disturb mode (similar to the iPhone).

 On Windows 10 simply tap on the notification icon and disable all notifications.

Disable and close apps

This also sounds silly, but there is nothing worse that having Slack keep bouncing up and down because someone mentioned you in a random channel. Don’t risk any unexpected popups and just close EVERYTHING you don’t need. In addition to less clutter on your machine it also will free up resources on your machine. If it isn’t part of your demo then close it out. This is very important for resource intensive programs such as Google Drive, Dropbox, and others.

Auto Hide The Dock on OSX

Get rid of it! It is using up precious screen space!

Acquire the Right Equipment

You have to have the right tools for the job and presenting is no different. The most essential tool for presenting is a presentation pointer/clicker. If I ever forget mine at home I am completely lost without that button to progress to the next slide. My favorite is the well built, light weight, long battery, and very lovely Logitech Wireless Presenter R400. Buy it and thank me later.

Of course you should also make sure you have all of the cables and devices necessary for giving a technical presentation. You can’t always rely on emulators for everything and may need to do some screen mirroring, so be sure to read my guide on how to properly screen mirror iOS, Android, and Windows. There are of course lots of other things that you may want to think about bringing with you such as a small wireless router, HDMI cable, usb hub, usb cables(Amazon Basics are perfect for this), power adapters, and of course a pad and paper to jot down notes of your presentation.

Oh! Don’t forget a bottle of water before you present. This is one of your most powerful tools that you have in your toolbox. It allows you to stop for 10 seconds, relax, take a sip of water, and carry on because you are crushing it!

Adapters, adapters, adapters!

Buy and carry every single HDMI, VGA, DVI, and Ethernet adapter you possibly can think of. You have no idea what kind of situation you are getting yourself into at a conference and you can’t rely on the organizers to have every little adapter. If you are on a Mac buy official adapters on Amazon, for Surface tablets buy the Microsoft stuff, and of course just get anything else that you can think of. Including a Displayport to HDMI… even if your Mac or PC has a HDMI. It sounds crazy, but trust me you may in fact might only complete the HDCP handshake this way!

Practice, practice, and practice some more!

I can’t stress it enough that it is really really important to practice your slides and of course your demo even if you have presented it in the past. I have a private GitHub repo that is “demo ready” that allows me to revert changes to for any presentation, but things can still go wrong. New updates, new operating systems, small changes in a NuGet package, who knows! Always run, compile, and download every bit that you need and run through your demo at least the night before just to be sure.

Know your slides

Do you know that little box on the bottom of each slide that says “Presenter Notes”? Do you know what they are for??? Presenter Notes! Don’t try to be all fancy and step out in front of your screen and try to Steve Jobs a presentation unless you have your slides memorized to perfection (I have only done this a few times, and it is not easy). Feel free to move, but put your laptop showing a few small notes and the next slide in between you and your attendees and you will be happy you did.

To live code or not to live code?

This is a question that I ask myself going into every presentation I submit. How much actual live coding do I want to do on stage… aka how much risk do I want to put myself into that something could go wrong. To be honest every presentation will be drastically different and it is OKAY to not write a single line of code. Most people will not take away what you tried to type up. My recommendation is use either small snippets or uncomment code for anything too complex and explain it line by line. I honestly do not see any real difference if you actually typed it out for something overly complex. If it is a very very important concept such as XAML or designing a page and showing off a cool feature then my thought here is absolutely go for live coding and people will appreciate it. My one recommendation is to absolutely NOT do a full presentation of just live coding, it is too much to handle. If you want to show code in slides do it side by side what the feature does with a screenshot. Your attendees will appreciate the effort you put into the sample you built and love that they can download it after.

Prepare for the Unexpected

Sometimes you can’t prepare for anything. Just a few weeks ago I was at a Xamarin Dev Days event in Boston where I was showing off a small weather application using’s awesome API. Little did I know that a day or two earlier they changed their “open” API to require an API key! All of my demos failed completely and it caught me off guard. I stopped thought and adjusted the demo to just hardcode fake return data to show off what “would” have happened.

Get ready for bad Networks

I can not lie that I am spoiled at home with Cascade Link offering me up a 1GB data connection up and down in Seattle. I can literally download Xamarin faster then it can install on my machines. This is not the case at conventions, hotels, airports, and of course airplanes! Be sure to download and install every bit you need ahead of time. The day of your presentation be sure to connect all your devices and test that connection. If things are going absolutely horrible and there is no internet make sure you have some sort of hotspot or hotspot enabled plan to tether that sweet sweet data. For really complicated demos be sure to also have an offline demo ready.

Here are the two issues I talked about above in the very famous iPhone 4 demo fails by Steve Jobs:

Notice Steve had a hard time and at some point you have to just carry on with the demo, and that is okay. If you can fix it for future demos then go ahead and do that and joke a bit about it. Just don’t ever say that it was the “demo gods” that weren’t with you, just say “well I’m not sure why this isn’t working” and continue on to the next demo. At most give a demo 60 seconds.

Be cognizant of time

Seems silly I know, but time yourself and know how long your presentation will go. Will you have time for questions during or after your sessions? If not tell the audience and don’t stop to answer questions, simply say you will be available after. I have recently started to put turn on a count up timer on my phone so I can glance down to check my time. I highly highly recommend this.

Be the expert

People packed the room to hear YOU speak. Be the expert that made you submit the talk in the first place. There will always be someone in the audience that knows something you don’t, but for the vast majority you are the expert so be confident in yourself. I know I am asking a lot here, but just do what you know and if you don’t know something when you are asked a tricky question don’t try to fake an answer, simply say “I am not sure, but let’s have a talk after and I will find out or find someone that does”. Honesty goes a long long way.

One last thing here when it comes to being an expert. Do not in any case ever ask or point out to someone in the audience for an answer. Just because you see an expert doesn’t mean they will know the answer or are following along super close. They are there to learn and all of the attention should be focused on you, not a random person in the audience.

You are your own worst critic

Whoa! You just gave a presentation! Stop and first congratulate yourself as you did something that most people will never do in their life. You got up in front of a room of random people or maybe even your peers and talked for 40 to 60 minutes on a topic. That is pretty amazing so be HAPPY! Stick around and answer questions, be nice, and hand out business cards. Don’t worry about mistakes, an odd wording, or that you think you did “bad”, trust me you didn’t. You will always nit pick your presentation and think you did worse than you actually did. Most likely no one noticed that 10 seconds of silence or small typo in your slide that freaked you out, trust me you most likely crushed it.

Have Fun

You have to have fun when presenting, crack some jokes, engage the audience and have a blast even if something does go wrong. Every presentation will not be perfect but each is a learning opportunity for the next one.

There you have it. This is a lot of text to read, but I am sure glad you did. I am in no way perfect and I am always looking to improve my presentation skills, so if you have your own tips and tricks please share them in the comments below.

October 27, 2015 9:21 GMT

52 Weeks of Xamarin: Week 12 – Advanced Customized Controls

Last week we looked at a simple example of customizing a control and creating a SpecialBoxViewcustom renderer.  This week we go a bit deeper.  Our goal is to give a BoxView a border, and to adjust that border dynamically.

[ This content is taken from my forthcoming Pluralsight course ]

As noted last week, we start with an Element and a Renderer.  In our case, the element will be a SpecialBoxView.  Unlike last week, however, this custom class will have contents; specifically the properties we want to be able to bind to.

Bindable Properties

public class SpecialBoxView : BoxView {     public static readonly BindableProperty BorderColorProperty =          BindableProperty.Create<SpecialBoxView, Color>(             p => p.BorderColor, default(Color));     public Color BorderColor {         get { return (Color)GetValue(BorderColorProperty); }         set { SetValue(BorderColorProperty, value); }     }     public static readonly BindableProperty BorderThicknessProperty =          BindableProperty.Create<SpecialBoxView, double>(             p => p.BorderThickness, default(double));     public double BorderThickness {         get { return (double)GetValue(BorderThicknessProperty); }         set { SetValue(BorderThicknessProperty, value); }     } }

Notice that these come in pairs: a bindable property and the public property that we’ll be using to get and set that value.  Thus, we can bind to BorderColor and/or BorderThickness.

Custom Renderer

With that done, we are ready to implement the custom renderer.  To do so, this week we’ll turn to iOS; next week we’ll follow up by creating the Android renderer.

The first step is to derive from BoxRenderer,

 public class SpecialBoxViewRenderer : BoxRenderer {

Within that class, we’ll override two methods: Draw and OnElementPropertyChanged.  In our override of Draw, we will first get the element itself,

 public override void Draw(CoreGraphics.CGRect rect) {
     SpecialBoxView specialBoxView = (SpecialBoxView)Element;

We will then get a context to work with to set our fill and stroke color as well as the width of the stroke.

 using (var context = UIGraphics.GetCurrentContext()) {

We can then get the inset to draw the border.

    var rectangle = this.Bounds.Inset((int)specialBoxView.BorderThickness, (int)specialBoxView.BorderThickness);

    var path = CGPath.FromRect(rectangle);

All that is left is to override OnElementPropertyChanged.  We’ll make sure that it is the BorderThicknessProperty that has changed, and if so we’ll call SetNeedsDisplay which will cause Draw to be called and the border to be redrawn,


protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {
    if (e.PropertyName == SpecialBoxView.BorderThicknessProperty.PropertyName) {

Don’t forget!

If we use this class as is it will build and it will run, but there will be no border, because we haven’t established a link between the renderer and the custom control.  As we did last week, we need to add an attribute outside of any namespace.

 [assembly: ExportRendererAttribute(typeof(SpecialBoxView), 

You will need to add using statements to resolve the SpecialBoxView and the SpecialBoxViewRenderer.


In the XAML we’ll need a name space for the SpecialBoxView,


We can then instantiate a SpecialBoxView.  We’ll want to adjust the width of the border with a slider, so we’ll set the slider to be the BindingContext and the BorderThickness property will bind to the slider’s Value.

     <Label Text="Customized Control" TextColor="Red" FontSize="24"/> 
       BindingContext="{x:Reference Name=ThicknessSlider}"
       BorderThickness="{Binding Path=Value}" />
       BindingContext="{x:Reference Name=ThicknessSlider}"
       Text="{Binding Path=Value}" />
       Maximum="100" />

The result is shown in the image at the top of this posting.