November 25, 2014

Android Tips: Hello Toolbar, Goodbye Action Bar


It seems like just yesterday that Google introduced the Action Bar for Android. It jump started a revolution for the Android user interface and made developer’s lives easier by providing a great way to provide menu options, tabs, and more for their users. With Android 5.0 Lollipop, all of this is about to change once again with the introduction of the Android Toolbar.


You can think of the Toolbar as the Action Bar’s bigger sibling that has grown up and is free to roam around the house by itself. It’s a generalization of the Action Bar that isn’t bound to an Activity’s window decor, can be placed anywhere in the user interface, and can even be designated as the Action Bar replacement for an Activity. It’s highly customizable, which means you can add navigation buttons, branded logos, titles, subtitle, action menu items, or even your own custom views.

For this sample, I am going to focus on the Android 5.0 (v21) Toolbar. The same can be achieved using the new Support Library v7 AppCompat, which features a backwards compatible Toolbar and is available as a pre-release NuGet.

Applying Your Theme

We will start by applying the Material theme to our Android application, but we will now set two special attributes android:windowNoTitle and android:windowActionBar to tell Android we will be using a Toolbar instead of the Action Bar.

<style name="MyTheme" parent="@android:style/Theme.Material.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <!--We will be using the toolbar so no need to show ActionBar-->
    <item name="android:windowActionBar">false</item>
    <!-- Set theme colors from>
    <!-- colorPrimary is used for the default action bar background -->
    <item name="android:colorPrimary">#2196F3</item>
    <!-- colorPrimaryDark is used for the status bar -->
    <item name="android:colorPrimaryDark">#1976D2</item>
    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <item name="android:colorAccent">#FF4081</item>
  	<!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight and colorSwitchThumbNormal. -->

If you want to learn more about the new themes, be sure to read my Introduction to Material Design blog post and watch my and Jérémie Laval’s sessions from Xamarin Evolve 2014 on Material Design.

Replacing the Action Bar

With our theme attributes set, we can now create our first layout. The Toolbar can be found in your Android Designer’s toolbox, from which you can simply drag and drop it at the top of your layout. Often you will want to use a RelativeLayout to specify that your Toolbar is at the very top.

<Toolbar xmlns:android=""
    android:background="?android:attr/colorPrimary" />

Now in your OnCreate method of your activity, you will need to find your Toolbar. To have it mimic the old ActionBar, you can set a new method call SetActionBar(Toolbar toolbar);.

protected override void OnCreate (Bundle bundle)
  base.OnCreate (bundle);
  SetContentView (Resource.Layout.Main);
  var toolbar = FindViewById<Toolbar> (Resource.Id.toolbar);
  //Toolbar will now take on default Action Bar characteristics
  SetActionBar (toolbar);
  //You can now use and reference the ActionBar
  ActionBar.Title = "Hello from Toolbar";


This is the easiest way to transition from the ActionBar to the new Toolbar, as all of your existing Action Bar menus will automatically work if you are inflating them in your OnCreateOptionsMenu method.

Applying Themes

Since the Toolbar is independent, it can also be themed independently as well. The android:theme is the main theme of the bar, and android:popupTheme is the theme to apply to menu item pop ups. If you are using a light theme, or want the look of a dark Action Bar, you can apply two themes directly on the Toolbar, which would look like this:

<Toolbar xmlns:android=""
    android:popupTheme="@android:style/ThemeOverlay.Material.Light" />



Custom Action Bars

As I mentioned earlier, the real reason to upgrade to the new Toolbar is that it has complete freedom to be placed where you want it and is fully customizable; it can even have a completely separate action menu that you can manage. Let’s say you want to put a Toolbar at the bottom of your screen and theme it in an accent color. You would simply add another Toolbar widget to the bottom and apply a different theme to it:

<RelativeLayout xmlns:android=""
    <!--First Toolbar goes here-->
        <!--Other widgets-->
        <!--Custom second toolbar at the bottom with an accent color for the background.
            Additionally, you can set any custom property and make the height larger or smaller.-->
            android:layout_height="wrap_content" />

Back in the Activity, the last step is to find this new Toolbar. Once found, we will not set it as an Action Bar, but instead we’ll inflate a separate menu and implement a new click handler when the users interact with it.

var toolbarBottom = FindViewById<Toolbar> (Resource.Id.toolbar_bottom);
toolbarBottom.Title = "Photo Editing";
toolbarBottom.InflateMenu (Resource.Menu.photo_edit);
//Add menu click handler
toolbarBottom.MenuItemClick += (sender, e) => {
  Toast.MakeText(this, "Bottom toolbar pressed: " + e.Item.TitleFormatted, ToastLength.Short).Show();

Multiple Android Toolbars

Going Further

The new Android Toolbar allows for a highly customizable developer experience that we never had access to with the standard Action Bar. You can grab the source code for this example and try out other Android L features on our Samples Gallery.

November 24, 2014

Adding Intelligent Analytics and Crash Reporting to Your Apps


At this year’s Xamarin Evolve 2014 we announced Xamarin Insights, a real-time monitoring solution allowing developers to improve their apps by reporting crashes and exceptions. Xamarin Insights MonitorGetting started with Xamarin Insights is as simple as adding just one line of code to your mobile apps, but you can gain even more information by optionally monitoring session, user, and event data.

Creating Your Insights App

To get started, just head over to and log in to your Xamarin account. Once you are logged in, you will see the “Add New App” button in the top right.

Add New App Insights

This will navigate you to a new page where you need to name the app that you would like to monitor. You will also see an API Key that you will use inside of your app to start monitoring, so keep this handy. When you have filled in all of the information, click the Create New App button.

You can always get back to this information by selecting the settings option inside of an existing app.

Adding Insights to Your App

Insights LogoXamarin Insights supports a wide range of mobile and desktop platforms, including iOS, Android, and Mac apps built with Xamarin. In addition to these, Insights also supports all of the Windows platforms including Windows Phone, Windows Store, and desktop apps. There is even a Portable Class Library that enables you to add reporting to all of your apps from your shared app logic. I’m going to cover iOS, Android, and Windows Phone, however, be sure to read the full API Documentation on how to add other platforms.

To get going, you are able to add Insights through a convenient NuGet package or through the Component Store in Xamarin Studio or Visual Studio.

Install Insights NuGet

With the NuGet or Component installed in your project, you just need to call the Initialization code in each platform to automatically start receiving native and managed crash reporting and usage statistics about your app.


You will want to call the Initialize code where your app starts, such as your main Activity or a custom Application’s OnCreate method. In addition, make sure you have the Internet permission enabled in your AndroidManifest.xml file.

Xamarin.Insights.Initialize("Your API key", yourAppContext);


Simply place the Initialize call in your AppDelegate’s FinishedLaunching method:

Xamarin.Insights.Initialize("Your API key");

Windows Phone

All Windows Phone apps have an App.xaml.cs file that contains the main constructor for the app. This is where you will place the Initialization call.

Xamarin.Insights.Initialize("Your API key");

With this single line of code, your app is set up and ready to go! Once your app is launched, you will start to receive data in your Xamarin Insights Dashboard.

Insights Data

Exception and Warning Reporting

Even though you automatically get crash reporting with the Initialization code in place, you might want to get even deeper insights into where your app is having issues and warnings are caught, or add data to exceptions that are caught and re-thrown.

Insight Warnings

Reporting an exception as a warning is as simple as calling the Report method to pass in the exception:

try {
catch (Exception exception) {

You can add additional data to the exception being caught as well by passing in a Dictionary of string key value pairs:

try {
catch (Exception exception) {
  Xamarin.Insights.Report(exception, new Dictionary <string, string> {
    {"Event Id", "00113"},
    {"Other Data", "Goes Here"}

If you want a warning to bubble up the stack to be handled later, you can still add additional data to the exception by using the exception’s Data field.

try {
catch (Exception exception) {
    exception.Data["AccountType"] = "standard";

Event Tracking

Receiving the full stack trace is great for seeing the root of the issue. However, how do you know what steps your users were taking leading up to the crash? This is where event tracking comes in extremely handy. You are able to track any event with a simple method call.

Xamarin.Insights.Track("QuestCompleted", new Dictionary<string, string> {
    { "Quest", CurrentQuest.ToString() },

Now, when a crash occurs, you will see any event that has also been tracked to help you reproduce the crash.

Session Crash

So Much More

There is so much to Xamarin Insights – including real time usage statistics, identifying information about your users, communication preferences, popular service integration such as GitHub and Visual Studio Online, e-mail notifications, and so much more – that I can’t cover it all in a single blog post. Be sure to browse through the Xamarin Insights Documentation and watch the Xamarin Evolve 2014 keynote to see Insights in action.

November 21, 2014

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


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

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

app screenshot

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

new solution

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

content page

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

<?xml version="1.0" encoding="UTF-8"?>
  Padding="0, 30, 0, 0">
      <Image Source="ball.png"></Image>
      <Label x:Name="label" Text="Magic 8 Ball" Font="Large"
        HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
      <Button x:Name="button" Text="Tell Me!" HorizontalOptions="Center"
        VerticalOptions="CenterAndExpand" Clicked="ButtonClicked" />

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

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

5. Update App.cs to return a BallPage:

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

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

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

The code for this mini-hack is available here:

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

November 20, 2014

Real-Time Code Iteration with Sketches


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


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

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

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

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

sketch results

Viewing Output

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

color visualizer

You can even pin the results to the output area:

color output

Additionally, the output can display graphs of data:

output graph

Visualizing Images

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

image visualization

Graphics Code

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

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

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

Core Graphics sketch

Visualizing Views

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

view visualization

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

forms sketch

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

November 19, 2014

Help Test the Future of Xamarin.Mac


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

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

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

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

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

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

  • Accounts
  • GameController
  • EventKit
  • MapKit
  • MediaAccessibility

in addition to the frameworks provided in the previous alphas:

  • CloudKit
  • GLKit
  • JavaScriptCore
  • LocalAuthentication
  • SpriteKit

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


Xamarin Insights and the Azure Outage


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

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

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

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

Insights - Azure

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

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

To learn more about Xamarin Insights to add real-time monitoring to your mobile applications check out


Live Webinar: Mobile Enterprise Success with Xamarin and IBM


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

IBM and Xamarin Logos

Join IBM and Xamarin technical executives for this previously recorded webinar in which they discuss the IBM and Xamarin partnership, demo the IBM MobileFirst SDK for Xamarin, walk through the IBM Worklight platform, and answer audience questions.

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

Dustin AmrheinDustin Amrhein
IBM Mobile Technical Leader, MobileFirst

Steve HallSteve Hall
Xamarin Director of Enterprise Mobility

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


November 18, 2014

Getting Started with the Xamarin Android Player


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

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

Blazing Fast Emulator

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

Getting Started

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

Xamarin Android Player Images

Even More Features

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

Download Now

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

November 12, 2014

Microsoft and Xamarin Expand Global Partnership


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

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

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

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

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

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

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

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

November 10, 2014

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


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

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

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

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

Thank you to Linknode for sharing your app with us!

Learn More

Visit VentusAR’s website to learn more.

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