April 23, 2014 1:27 GMT

Reviewing Values for iOS UIViewContentMode with Xamarin and F#

Who can remember the scaling behavior of UIView.ContentMode? Not me!

So I wrote this quick little F# program to review them:

    namespace Simple
    open System
    open MonoTouch.UIKit
    open MonoTouch.Foundation
    open System.Drawing
    type ContentView ( color : UIColor ) as self = 
        inherit UIView ()
            self.BackgroundColor < - color

    type ContentModeModel  () = 
         inherit UIPickerViewModel ()

         let T = typedefof<UIViewContentMode>

         let selectionChanged = Event<_>()

         member this.SelectionChanged = selectionChanged.Publish 

         override this.GetRowsInComponent(_, _) = Enum.GetNames(T).Length
         override this.GetTitle(_, row : int, _) = Enum.GetName(T, row)

         override this.GetComponentCount(_) = 1

         override this.Selected(_, row : int, _) = selectionChanged.Trigger(enum<UIViewContentMode>(row))
    type SimpleController ( ) =
        inherit UIViewController ()
        override this.ViewDidLoad () = 
            this.View < - new ContentView(UIColor.Blue)

            let imgView = new UIImageView(new RectangleF(20.0F, 80.0F, UIScreen.MainScreen.Bounds.Width - 40.0F, 100.0F))
            imgView.Image <- UIImage.FromFile("flower.png")
            imgView.ClipsToBounds <- true

            let picker = new UIPickerView(new RectangleF(20.0F, UIScreen.MainScreen.Bounds.Height - 180.0F, 250.0F, 140.0F))
            let model = new ContentModeModel()
            picker.Model <- model 

            model.SelectionChanged.Add <| fun newMode -> imgView.ContentMode < - newMode

    [<Register ("AppDelegate")>]
    type AppDelegate () =
        inherit UIApplicationDelegate ()
        let window = new UIWindow (UIScreen.MainScreen.Bounds)
        // This method is invoked when the application is ready to run.
        override this.FinishedLaunching (app, options) =
            let viewController = new SimpleController()
            window.RootViewController < - viewController
            window.MakeKeyAndVisible ()
    module Main =
        let main args =
            UIApplication.Main (args, null, "AppDelegate")

No real interesting techniques, but another nice quick iOS app in Xamarin using F#.


April 22, 2014 6:43 GMT

Tips & Tricks for Highly Performing Android ListViews

I have been working with Xamarin.Android for a long time now and one question I get asked quiet often is how to optimize the Android ListView. Xamarin apps are native apps, which means that out of the box your app will take advantage of all of the optimizations that come with these views in the framework; however, when Google implemented the ListView they left out a few additional optimizations that developers can take advantage of to ensure a great user experience. Let’s first look at how the ListView and their adapters actually work:

Cell Reuse in Android ListView Adapters

What we see here is that Android is optimized for cell reuse. It will never take the number of cells that are displayed and cycle through them, so as your user scrolls through the list and a cell goes off the screen it is put into a recycle bin and then put back on top to be reused again. Let’s look at the standard code out of the box when creating an adapter and then optimize it:

First I will create a simple item for my adapter. It consists of two TextViews and one ImageView.

A simple android list adapter cell


For this example I have created a new Adapter and inherited from BaseAdapter. When I implement the GetView method, I could simply inflate the view, find the controls, and set the properties on them:

public override View GetView (int position, View convertView, ViewGroup parent)
  var view = activity.LayoutInflater.Inflate (Resource.Layout.OptimizedItem, null);
  var textView1 = view.FindViewById<TextView> (Resource.Id.textView1);
  var textView2 = view.FindViewById<TextView> (Resource.Id.textView2);
  var imageView = view.FindViewById<ImageView> (Resource.Id.imageView);
  textView1.Text = Names [position];
  textView2.Text = Descriptions [position];
  imageView.SetImageResource (Names [position].ToLower().Contains ("xamarin") ?
				   Resource.Drawable.hexagongreen :
  return view;

There are a few issues with this implementation, which is that we are inflating the view and locating the controls each time GetView gets called. So let’s fix that.

Take Advantage of ConvertView

The first optimization we will want to make is to take advantage of the convertView that is passed into this method. In the official documentation for GetView it tells us exactly what the convertView is: “The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view.”

This means that if the convertView is null then we should inflate the view else we can simply fine the controls on view and set them.

public override View GetView (int position, View convertView, ViewGroup parent)
  var view = convertView;
  if(view == null) {
    view = activity.LayoutInflater.Inflate (Resource.Layout.OptimizedItem, null);
  var textView1 = view.FindViewById<TextView> (Resource.Id.textView1);
  var textView2 = view.FindViewById<TextView> (Resource.Id.textView2);
  var imageView = view.FindViewById<ImageView> (Resource.Id.imageView);
  textView1.Text = Names [position];
  textView2.Text = Descriptions [position];
  imageView.SetImageResource (Names [position].ToLower().Contains ("xamarin") ?
				   Resource.Drawable.hexagongreen :
  return view;

Now we will only inflate the view when necessary. This immediately leads to increased performance of our ListView, but we can do even better!

Implement a ViewHolder

The second issue I noted was that we are having to locate the controls with FindViewById every single time GetView is called, which can lead to performance issues. The way to get around having to use FindViewById is to implement a “ViewHolder” design pattern.

We will create a ViewHolder class to store all of the controls that are inside of the view so we can access them immediately without the need to use FindViewById each time. The first thing we will do is create a class to store the information:

private class MyViewHolder : Java.Lang.Object
  public TextView Name { get; set; }
  public TextView Description { get; set; }
  public ImageView Image { get; set; }

You might be wondering why we are inheriting from Java.Lang.Object, well the reason for this is because each view has a Tag property, that can be used to store information. The Tag property is of type Java.Lang.Object, so that forces us to inherit from it. Now that we have the ViewHolder setup we can finish the optimization by populating it, storing it inside the view, and accessing the controls from the holder instead of calling FindViewById:

public override View GetView (int position, View convertView, ViewGroup parent)
  MyViewHolder holder;
  var view = convertView;
  if (view == null) {
    holder = new MyViewHolder ();
    view = activity.LayoutInflater.Inflate (Resource.Layout.OptimizedItem, null);
    holder.Name = view.FindViewById<TextView> (Resource.Id.textView1);
    holder.Description = view.FindViewById<TextView> (Resource.Id.textView2);
    holder.Image = view.FindViewById<ImageView> (Resource.Id.imageView);
    view.Tag = holder;
  } else {
    holder = view.Tag as MyViewHolder;
  holder.Name.Text = Names [position];
  holder.Description.Text = Descriptions [position];
  holder.Image.SetImageResource (Names [position].ToLower().Contains ("xamarin") ?
				 Resource.Drawable.hexagongreen :
  return view;

There you have it, with just a few quick changes you will have your Adapters fully optimized to create the best user experience possible for your app. A few other notes, while I only mentioned the ListView these same optimizations can be used on your adapters for GridViews as well. Additionally, it is recommended to inherit from BaseAdapter instead of using an ArrayAdapter when exposing C# objects to avoid unnecessary bridge interaction when working in Xamarin.Android.

Discuss this blog post in the Xamarin Forums

April 22, 2014 12:09 GMT

iOS UIDynamics Sample

I have been using more and more animations with my iOS Apps recently and thought it was about time I took a good look at UIDynamics. With iOS7 and UIKit Dynamics, there is no longer any need to use CAKeyframeAnimations or UIView animations when looking to spice up your Apps UI.

Below is the animation I wanted to create:




The code:

var redSquare = new UIView(new RectangleF(new PointF(100f, 0f), new SizeF(150f, 150f))){BackgroundColor = UIColor.Red};

//Setup UIDynamics
animator = new UIDynamicAnimator(View);
UIGravityBehavior gravityBehavior = new UIGravityBehavior(redSquare);

UICollisionBehavior collisionBehavior = new UICollisionBehavior(redSquare) { TranslatesReferenceBoundsIntoBoundary = true };

UIDynamicItemBehavior elasticityBehavior = new UIDynamicItemBehavior(redSquare) { Elasticity = 0.7f };

  Download Sample Project

Follow me on Twitter

The post iOS UIDynamics Sample appeared first on Mike James.

April 20, 2014 12:25 GMT

4 Days, 4 Developer Group Talks in Vancouver, BC!

I’m hitting the road again, but this time to Vancouver, BC from April 22nd to 25th for 4 different developer group talks on Xamarin! So if you are in the area make sure to come see me if you have some time. Here is where I will be:

April 22nd 6:30PM: .NET BC (Burnaby, BC)
Topic: Cross Platform Mobile Development for the C# Developer with Xamarin
More info & Register Here

April 23rd 6:30PM: Victoria App Developer Group (Victoria, BC)
Topic: Building cross-platform Apps for Windows Phone, iOS and Android
More info & Register Here

April 24th 6:45PM: Vancouver Mobile .NET (Vancouver, BC)
Topic: Mobile development techniques using C# and MvvMCross
More info & Register Here

April 25th 6:00PM: Windows Phone Developer Group(Vancouver, BC)
Topic: Introduction to Xamarin for WP developers
More info & Register Here

I hope to see you there!

April 18, 2014 11:36 GMT

Shared Code Projects in VS: Windows Phone, Windows Store, and Xamarin!

At Build, Microsoft announced Shared Code Projects to simplify how developers are sharing code between platforms. We have had official portable class library support for Xamarin apps since late last year and it has been wonderful, however once you mix WP8 into the mix the PCL profiles get a bit limited. Shared Code Projects attempt to fix this by allowing you to create a project that are a shell for code that can be added into any project. It is basically glorified file linking with a nice UI to help you debug your code better per project. You will still have to do a bunch of #ifdefs though if you are trying to use functionality that is not available in a specific platform.

Shared Code != Universal App && Shared Code != PCL

So it should be stated that Shared Code projects are not universal apps and they are not PCLs. A Universal App is just a project template for WP8.1 and WinStore 8.1 apps that use a shared code project. The idea of a Universal App is simply that these two platforms have a shared project and maybe they are able to share some of the UI which is XAML (I still have to explore this more). Also, a Shared Code project differs from a PCL because the PCL does not have the ability to call platform specific code without an abstraction layer like the shared code project can. Additionally, they work completely different at Compile vs Deploy time. Remember that PCL’s can compile against a “contract” and implementation, but at build and deploy time the platform specific version will is used. The shared code project is compiling and deploying against what is in each parent project and their references.

So to me this means that a PCL is for library creators and a Shared Code project is for app creators, but an app creator can also live completely in PCL land if they want. I have been and I enjoy it, but I am still constrained to what PCL limits me to, but allows me to easily add platforms in the future without modifying code. So I think I will start more projects with shared code projects in the future.

Get it in VS!

While Miguel tweeted that support for shared code projects will be added to XS in the future if you live 100% of the time in VS then you can get started today with shared code projects. The first thing you need to do is install the shared code project visual studio plugin assuming you already have Visual Studio 2013 Update 2 RC installed.

With that installed we can go ahead and create a new project:

Then you can add in your iOS and Android apps like normal. Once you want to start writing code in your Shared Code Project you will want to add them as a reference to your other projects so you can get intellisense and bring in namespaces.

Once I have added them here you will be able to see the reference in the project references:

What am I coding against?

Shared code project actually have no references… well actually they have every reference of the parent. What is really cool is that you can toggle between each project when you have a file open from the shared code project.

This means you will probably have to do a lot of toggling between everything to make sure it compiles correctly, but it is pretty slick. So now if I wanted to add HttpClient into the mix here I would add the reference to my iOS and Android project like I normally would, and then start writing code in my Shared Code project:

And there you have it, Shared Code projects integrated into Visual Studio for Xamarin projects!
April 18, 2014 5:50 GMT

Part 3: My StepCounter Android: Pretty UI!

I am no UI expert that is for sure, but I really like what Michael James did with the iOS version of My StepCounter. He made a nice background that changed colors from Red to Green, had a chromeless UI, and utilized very nice fonts. I want to take advantage of some of the work he did and also customize it for android.

Transparent ActionBar

I Wanted to ensure that the full screen was being utilized for this app, but still wanted to take advantage of the unique actions that I can put in the ActionBar. Luckily Android is highly customizable with styles and themes. To create a transparent actionbar you need to override your themes.ActionBar style and give the android:background and android:backgroundStacked a transparent colors. Additionally I wanted to only show the title and then style the TextStyle to be a bit larger and also use a sans-serif-light.

This bit of code results in a stunning and beautiful look:

Pretty Fonts

I was really impressed with the font selection and usage on the iOS version and I wanted to bring that over to Android. Since I am targeting Android 4.4 I can use all of the nice Roboto fonts built in. If I was targeting an older version I could have used my Roboto.TextView control, however all I need to do is set the android:fontFamily to:
  • san-serif
  • sans-serif-light
  • sans-serif-condensed
  • sans-serif-thin
These are all great fonts and when combined with a nice background I get a nice visual look:

Fancy Background

In the iOS version Michael created a custom ProgressView that would change the background RGB based on the percentage that you passed into it. I was actually able to re-use nearly all of this code and put it into a shared file. The main difference was just what property I was settings and how I was creating a new color:

As we can see I have to do a lot of #if defs, but it is nice to re-use all of this RGB arrays so we get the same color on the device. The screenshot I showed earlier you saw a blue background, but what I didn’t show you was how I created this. What I actually did was make my root view the ProgressView, which is a FrameLayout, and then I overlaid another FrameLayout with a blue background on it.

This blue frame layout will be animated later, but here are a few screen shots of what the progress view looks like as I move it:

No Boundaries

After having a few people test out the app I got some instant feedback, which was that I should extend the views up to the System Bar and Navigation Bar. This is a brand new feature in Android 4.4 so why not take advantage of it! It was actually really simple. The first thing I needed to do was add android:windowTranslucentNavigation=”true” and android:windowTranslucentNavigation=”true” to my style:

Now to ensure that any content on the bottom of the screen didn’t overlap there is an important property to set, which is: android:fitsSystemWindows=”true”. I had to wrap my two text views in a FrameLayout which is where I set this property:

And here you have it the final UI:

So there is my base UI with the same ProgressView that we are using on iOS now on Android with pretty fonts as well. Next up is Animations!
April 17, 2014 9:27 GMT

Interactive App Product Tours

One of the most important metrics in app development is the retention rate. Unfortunately, often we don't pay much attention to metrics like these in the hustle of designing, developing, and marketing our app. In fact, when testing my own app, Verses, one thing I noticed is that users were having issues learning to use the app. inspireUX lists six ways to help you implement help design patterns to alleviate these issues. While most of these are suitable options, walkthroughs are my favorite. Rather than showing the user what to do, have them do it themselves.

Some people say an app's user experience should be so carefully crafted that it is an entirely intuitive process to learn how to use it. However, I disagree. Think of some of the best apps you've ever used. For me, Tweetbot comes to mind. After a short overview, we are presented with a walkthrough tutorial. OmniFocus, one of the most popular productive apps in use today also utilizes a walkthrough. It's hard to retain users regardless of design or feature set if they don't know how to use your app. The solution is simple: teach them.

Introducing CRProductTour

Quickly and easily build interactive product tours or walkthroughs for your Xamarin.iOS apps with CRProductTour.

Sound awesome? Get it from GitHub.


Create "bubbles" for each UIView you wish to draw attention to and add them to the product tour. That simple. Even better, CRProductTour is 100% customizable. You can change the font of the bubble, the font size, the background color, the text color, and pretty much everything else you can think of.

Special Thanks

  • Clément Raussin wrote the original library in Objective-C. As always, he is deserving of some love if you decide to use this in any of your apps.
  • Luigi Saggese for alerting me to the existence of this library after what seems like an exhaustive search for something similar. Thanks :)
April 17, 2014 4:15 GMT

Part 2: My StepCounter Android: Step Counting in a Bound Service

In Step 1 of bringing My StepCounter to Android I investigate the raw sensor APIs available in Android. It was extremely nice to see that it was easy to tap into the step counter and detectors by simply implementing: ISensorEventListener and register for events. In my first example I was doing this all in my Main Activity, which seems like it would be alright if I was using step counter since it would return a total count since I registered for events, but I would have no way of detecting the current day, if the phone was reset, and just how accurate this data was. So this means that I need to have a background service running so my application can constantly be receiving notifications that steps have been happening.

Services have a few ways of notifying applications that data has changed. We can either use a broadcast and a receiver to parse the data or we can create a bound service from our main activity. The latter is what we will want to do as I don’t trust the speed of the broadcast receiver compared to a nice bound service which gives our activity full access to the services properties. This is sort of what it looks like:

Luckily the Xamarin documents have great documentation on bound services so it was really easy to implement. We need to create 3 different things:
  • StepServiceBinder: Is set in our activity when it requests a BoundService and gives it access to the Service
  • StepServiceConnection: Our activity starts a connection which does the binding to the ServiceBinder.
  • StepService: This is our service, now doing all the processing!

This code is pretty straight forward actually, which all it does is pass in a reference to the service or a reference to the activity which it wants to bind to:

Our service now is pretty powerful and doesn’t have to do anything special to become a bound service, it will just automatically bind. However one thing that I wanted to have happen was for my Main Activity to be able to get property change notifications so it knows when to update the UI when we step. So all I needed to do was have my Service implement INotifyPropertyChanged and I created a public property called StepsToday which will have an up to date count of total steps taken:

Now all I had to do was go back to my MainActivity and OnStart I will attempt to bind to my service, OnStop will unbind, and when my StepServiceBinder gets set from the StepServiceConnection I will register for PropertyChangedNotifications:

And there you have it I am now able to get property changed notifications from my background service! Now of course I will want to start this service when the Activity starts, but I will also want to start the service when the user reboots their phone so I don’t loose any information. I will need to give my app it’s only permission it required which is ReceiveBootCompleted:

Then I will go ahead and create a boot receiver which will start my service automatically:

I am all set, now just to calculate proper steps and animate the UI!

If you want to learn more about bound services please watch Nina Vyedin video from Monkey Space.

Backgrounding/Multitasking in Mobile - Nina Vyedin from Monkey Square on Vimeo.

April 17, 2014 12:56 GMT

Easy In App Purchases for iOS

Xamarin.iOS makes it easy to use Apple’s StoreKit API to include In App Purchasing in our iOS mobile applications. However, there’s quite a bit of repetitive code that has to be created for every app that includes it.

That’s where the new Xamarin.InAppPurchase component can help!

Xamarin.InAppPurchase in Use

Using Xamarin.InAppPurchase, we can easily and quickly add iTunes App Store In App Purchasing of products, features or subscriptions to our iOS mobile applications. All without any of the repetitive code required when calling StoreKit directly.

Working with Product Identifiers

By decorating our Product Identifiers with specific keywords, we can have Xamarin.InAppPuchase automatically handle things such as the product type, subscription duration, consumable quantities and downloading of hosted content from the iTunes App Store.

For example, we can use product.nonconsumable to define a non-consumable product, gold.coins.consumable_x25 a consumable package of 25 gold coins, magazine.subscription.duration1month an auto renewing monthly subscription and antivirus.nonrenewingsubscription.duration6months a non-renewing six month subscription.

So let’s take a look at how easy it is to get a list of available In App Products from the iTunes App Store with Xamarin.InAppPurchase by using the following code:

using Xamarin.InAppPurchase;
using Xamarin.InAppPurchase.Utilities;
public InAppPurchaseManager PurchaseManager = new InAppPurchaseManager ();
// Ask the iTunes App Store to return information about available In App Products for sale
PurchaseManager.QueryInventory (new string[] {

After this code runs, the PurchaseManager will contain a list of any valid products with all of the localized information read from the iTunes App Store, ready for us to display to the end user.

When the user is ready to buy a given item, we can use the following code to start the purchase process with the iTunes App Store:

// Ask iTunes App Store to purchase product
PurchaseManager.BuyProduct (Product);

We can then monitor several of the events exposed by the PurchaseManager to update the app’s UI or activate new content or features. At any time we can ask if a given product has been purchased using:

// Was the feature purchased?
if (PurchaseManager.ProductPurchased("my.nonconsumabe.feature")) {

In addition, Xamarin.InAppPurchase will automatically track our consumable product quantities and subscription expiration dates and provides methods to work with them easily.

Secure Automatic Persistence

The Xamarin.InAppPurchase component includes ways to automatically and securely persist the user’s purchased products. This information can be stored either to the app’s user preferences, a local file, iCloud, or our own custom persistence methods.

Now, let’s look at restoring previous purchase history that has been automatically saved by the Xamarin.InAppPurchase component. We’ll add the following code before our call to QueryInventory above:

// Setup automatic purchase persistence and load any previous purchases
PurchaseManager.automaticPersistenceType = InAppPurchasePersistenceType.LocalFile;
PurchaseManager.PersistenceFilename = "AtomicData";
PurchaseManager.shuffleProductsOnPersistence = false;
PurchaseManager.RestoreProducts ();

With this code in place the Xamarin.InAppPurchase component automatically saves any changes to the user’s purchased products and restores that history when our iOS app starts.

Simulating the iTunes App Store

There are several situations that can arise when working with In App Purchases, many of which can be hard to test for. The Xamarin.InAppPurchase component provides the ability to simulate interaction with the iTunes App Store so we can fully test out our application. This helps to ensure and provide a smooth, issue free In App Purchase experience for our users.

Xamarin.InAppPurchase running in simulation

When running in the simulation mode, decorate your product identifiers with specific keywords to test such things as invalid product IDs, failed purchases, hosted content download, etc. You can even test products before they are added to iTunes Connect and can test In App Purchases inside the iOS Simulator on a Mac.

Let’s look at how easy it is to run the Xamarin.InAppPurchase component in the simulation mode. We’ll modify our code above to look like the following:

// Initialize the purchase manager
PurchaseManager.simulateiTunesAppStore = true;
// Ask the iTunes App Store to return information about available In App Products for sale
PurchaseManager.QueryInventory (new string[] {
// Setup the list of simulated purchases to restore when doing a simulated restore of purchases
// from the iTunes App Store
PurchaseManager.simulatedRestoredPurchaseProducts = "product.nonconsumable,antivirus.nonrenewingsubscription.duration6months,content.nonconsumable.downloadable";

Now we can run our iOS mobile app and test interactions such as the purchasing of a product failing, downloading of hosted content failing halfway through, or any other event that can happen with In App Purchases.

For more details about the Xamarin.InAppPurchase component and to get a full demo iOS application built using it on the Xamarin Component Store.

April 16, 2014 3:56 GMT

Epic Evolve Sessions

Last year, Xamarin Evolve 2013 hosted over 80 training and conference sessions on a vast array of topics. This year will be even bigger. Join us in October for Xamarin Evolve 2014, with a full extra day to make room for even more amazing sessions. If you didn’t get to attend last years conference or just want to catch up on the great sessions that were presented you can watch online right now. Here are just a few of our favorites from Xamarin Evolve 2013 that you don’t want to miss:

How C# Saved My Marriage, Enhanced My Career, and Made Me an Inch Taller

with Scott Hanselman

Multiplatformism: Lessons Learned Bringing Bastion to Six New Platforms

with Andrew Wang

Getting the Most from Xamarin Studio

with Michael Hutchinson

Push Notifications with PushSharp

with Jonathan Dick

Buttons are a Hack

with Josh Clark

If you enjoyed these sessions, we have all the videos from Xamarin Evolve 2013 online. And you definitely don’t want to miss Xamarin Evolve 2014 in October — two full days of training from Xamarin University followed by three days live sessions from Xamarin and Industry experts. Don’t wait, Register for Evolve 2014 today!

April 15, 2014 10:31 GMT

C# Meetups featuring Google Glass, Bluetooth LE & More

Community growth continues to be explosive with new Mobile .NET developer groups starting all over the world. This month, we have already seen the inaugural meeting for a new group in Paris, France, and we are pleased to announced two new groups in Tampa Bay, FL and Madison, WI! So, April isn’t over yet as it packed full meetups happing everywhere on vast topics from MvvmCross, Intro to Xamarin, and Bluetooth LE!

Mobile .NET Developers Meetups April 2014

Here are some upcoming Xamarin developer group meetups:

New Group: Tampa Bay Xamarin User Group usa flag

  • Tampa Bay, FL: Wednesday, April 16th 7:00PM
  • First TBXUG Meeting – Intro to Xamarin

Boston Mobile C# Developers Group usa flag

  • Cambridge, MA: Thursday, April 17th 6:30PM
  • Developing for Google GlassChris Hardy, Xamarin

.NET BC canada flag

  • Vancouver, BC: Tuesday, April 22nd 6:00PM
  • Cross Platform Mobile Development for the C# Developer with XamarinJames Montemagno, Xamarin

New Group: Madison Mobile .NET Developers Group us

  • Madison, WI: Wednesday, April 23rd 5:30PM
  • Introduction to Xamarin

Dutch Mobile .NET Developers Group Netherlands flag

  • Aalsmeer, Netherlands: Thursday, April 24th 6:00PM
  • Responsive design and Bluetooth LE

Vancouver .NET Mobile Developers Group Canada

  • Vancouver, BC: Thursday, April 24th 6:30PM
  • Mobile Development Techniques using C# and MvvMCross

Detroit Mobile .Net Users Group us

  • Southfield, MI: Monday, April 28th 6:00PM
  • Build / Xamarin Recap, Humanitarian Toolbox

Sydney Mobile .Net Developers Group Australia Flag

  • Sydney, Australia: Tuesday, April 29th 6:30PM
  • Build 2014 and Cross Platform Visual State Management

If you don’t see your city listed above, don’t worry as new events and developer group meetups are being added frequently on the Xamarin Events forum.

If you are interested in starting a developer group in your city we are here to help you get started. We have tips and trick on staring a developer group, a brand new introduction to Xamarin slide deck, and of course our community sponsorship program to get you on your way. We also want to hear from you so please feel free to send us an email or tweet @XamarinHQ so we can help spread the word and continue to grow the Xamarin community.

April 14, 2014 8:25 GMT

Integrating Localytics

With all of the great analytics platforms out there, it's tough to pick the right one. Obviously, there is no silver bullet. It all depends what you are looking for. If you want to integrate analytics with your backend, you may go with something like Azure Mobile Services, Parse, or Buddy. Perhaps you go with a more traditional and familiar provider like Flurry or Google Analytics. For me, I just wanted a simple provider that has straightforward pricing, a beautiful web dashboard, and a simple API without all of the complexities of the usual analytics services. That’s when I found Localytics.

Localytics can take as little as ten minutes to integrate into your Xamarin.iOS app. By default, Localytics doesn't ship an assembly compatable with Xamarin.iOS, so I used Objective Sharpie and bindings to create Xamarin.iOS-capable version.

Get Localytics for Xamarin.iOS Today


The setup process is the same, regardless of the app you are building. A detailed guide on the setup process can be found in the repository for the binding.


Have you ever seen a promotional line around the following “Over 1,000,000 tasks completed!” for an app? This information can be collected via events. Events can provide valuable insight into what users are doing within your application. You can see what features the users like, as well as the ones they don’t like (or don’t know about).

Integrating events into your application can be done via one line of code:

LocalyticsSession.Shared.TagEvent ("EventName");

Localytics offers a detailed guide on when to use events, as well as some general best practices.

Screen Flow

Screen flow can provide valuable insight into how exactly your users are interfacing with your application. Screen flow can help track down the reasons behind a particular feature being used, or help show that a particular process is too tedious. Again, Localytics outdid themselves. You can integrate screen flow with one line of code (AGAIN!?):

LocalyticsSession.Shared.TagScreen ("FirstViewController");

Localytics is an analytics vendor with a simple API that doesn’t bog me down with tedious information that would be tough to find useful. Many of the integrations are just one line of code, making the entire process of collecting data within your app painless. They even have some marketing APIs you can tap into, though the binding doesn’t support those yet.

April 14, 2014 2:36 GMT

Observable UITableViews

"Lists are the core mobile interaction." - Nic Wise

If lists are the core mobile interaction, why are they sometimes such a pain to work with? I'm currently building an app for iOS called Verses. The basic premise is to store verses and prayers for later viewing, and to allow for verse memorization at your own pace. Because the app is mostly UITableViews (iOS' concept of lists), I found myself annoyed with everything involved with adding and deleting items. Whenever a new item is added, I have to update the collection holding the item, the database, and the UI. Keeping things in sync is a pain.

Then I found Frank Krueger's ObservableTableViewController. I will never write another app without it. The idea: use C#'s INotifyCollectionChanged to help keep the table in sync with the data source. Even better, I don't have to reload the entire table. When the collection is changed, the corresponding rows are either added or deleted, rather than reloading everything in the table. The result: simple, fast tables.

What does observable even mean?

Simply put, an object is being observed for any changes that alter that object's state. If you have worked with C# for a while, you are probably familiar with an interface called INotifyPropertyChanged. Subscribing clients, often UI objects, are alerted whenever the value of a particular property is changed. There is also a lesser-known (at least to me) interface named INotifyCollectionChanged. As you would probably guess, this alerts subscribing clients whenever a collection implementing the interface is altered, be it with a new addition, deletion, or even an object being moved within the collection.

Okay, so what collections can I use?

You can use pretty much any collection you would like, as long as it implements INotifyCollectionChanged. Frank recommends ObservableCollection<T>, and I agree. If you have experience working with Windows 8 development, chances are you already familiar with this. If not, it works just like any other generic collection you have ever used. The absolute best part is you don't have to change your model at all to support this. ObservableCollection<T>'s constructor takes in any type of IList<T>, so you can seamlessly integrate in your existing model. In fact, that's exactly what I did with Verses.

If you want to use a collection that doesn't implement the interface, that's fine too! You just won't be exposed to the same level of magic.

Demo: "Observe" the Magic

You can observe the magic by downloading the solution from GitHub.

As a high-level overview of the demo, there is a Person class which will serve as our data model. Additionally, there is a PersonTableViewController that inherits from ObservableTableViewController. The former is Frank Krueger's brainchild which contains all of the logic for keeping the data source and table in sync. PersonTableViewSource serves as the table's source, a combination of both the data source and delegate classes. Note that it really doesn't look any different than a typical UITableViewSource.

One of the awesome parts of ObservableCollection<T> is that we don't have to update our model to spit out something compatible with our observable collection. In this example, I assume our model returns a List<T>. (Remember from earlier all this has to do is be an IList<T>.) To get this working with our ObservableCollection, just pass it in as an argument into the constructor of our collection. That's it! Additionally, make sure you assign the DataSource property to your collection so the table knows what data to be observing for changes.

    public PersonTableViewController (List<Person> people)
        data = new ObservableCollection<Person> (people);
        DataSource = data;

If you run the app, you will notice two UIBarButtonItems. The one on the right does exactly as you would expect, it adds an item to the collection. Notice the pure magic. I don't update the data source, reload the table, or worry about anything. I just add the item to the collection and ObservableTableViewController does the heavy lifting.

    void AddItem ()
        data.Add (new Person { Name = "New Person", State = "New State" });

So far I have neglected to talk about asynchronous operations. With Xamarin, I can leverage awesome C# features like the Task Parallel Library in my mobile apps to make them as responsive as possible. What happens when I try to update the collection on another thread?

        Task.Factory.StartNew (() => {
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
            Thread.Sleep (2500);
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;

            data.Add (new Person { Name = "New Async Person", State = "New State" });

Click the left button on the navigation bar. The activity indicator pops up for a bit, disappears, and the table updates. Notice that you can click the right button and add items synchronously while the asynchronous operation completes. It just works. Magic.

What about sorted lists?

If you have run the demo, chances are you have noticed that the item is just added to the bottom of the UITableView. While this is fine for many apps, others require sorted tables. Not a problem. We just need a collection that meets two requirements:

  1. Implements INotifyCollectionChanged
  2. Keeps the collection sorted

Demo: More Magic

None of the collections packaged in the .NET framework meet both of these requirements for sorted lists. After some googling, I found ObservableSortedList<T> from Roman Starkov. As you would expect, nothing changes with our UI from our previous example. All we have to do is change the types of ObservableCollection<T> to ObservableSortedList<T>. As far as the model is concerned, there are two small changes required:

  1. Implement INotifyPropertyChanged
  2. Implement IComparable

Luckily, both of these are very quick and easy updates to our model. You can see a sample implementation of these on the Person class on GitHub. Change the startup project for the solution by right-clicking Project -> Set as Startup Project. Run the app again and you will see that the items are correctly added in sorted order without reloading the whole table. Awesome!

Wrapping Things Up

You were probably a bit skeptical when I said I will never write another app without it, but as you saw it is very true! By utilizing the feature set already present in C#, we were able to vastly simplifiy the way we write tables on iOS.

Without Frank Krueger's ObservableTableView, obviously this wouldn't be possible. If you plan on using this in your apps, please thank Frank Krueger for his hard work! If you will be utilizing sorted tables, both Frank and Roman Starkov are in need of some love!

Of course, without C# none of this is possible. If you like the idea of writing native, cross-platform apps in C#, Xamarin is your answer. And as always, if you have any questions, comments, or just want to talk, I can be found on Twitter @pierceboggan. Oh, and the comments section is always there as well!

Update: Tons of people on Twitter are pointing out ReactiveUI is great for stuff like this as well.

April 13, 2014 11:57 GMT

Codemania 2014 - Native, Cross platform, Mobile

Last week, I talked at Codemania about cross platform mobile apps, and specifically the Xamarin tools. The talk appeared to go well (it's always hard to tell from this side of the stage), and I hope people enjoyed it and want to check out the Xamarin tools.

The slides are here, on speakerdeck

And the code is on github.

If you were at Codemania, and have any feedback (good or bad), feel free to get in touch, either via email or twitter.

Thanks to Ben and Ian for organising (another) awesome conference. I suspect I'll be back next year as an attendee.

April 12, 2014 9:24 GMT

Part 1: My StepCounter Android: Step Sensors

In February, my fellow Xamarin Michael James published a wonderful app for iOS called My StepCounter. This app uses the new CoreMotion apis in iOS 7 to track your steps on your iPhone 5s. This isn’t a new concept and there are plenty of devices and apps out there that do step tracking, but what makes My StepCounter special is that Michael gave it a beautiful simplistic UI & beautiful animations. On top of that he created it all to be 100% compatible with Xamarin Starter Edition! This is extremely impressive and demos the power of Starter Edition for anyone to start creating apps in C#.

My StepCounter for iOS

Introduced with Android 4.4 was a new step sensor hardware support, which happens to be supported on my Moto X. So naturally as an Android development lover I wanted to test out these new APIs and create My StepCounter for Android. My goal is pretty simple:

  • Track Daily Steps with new APIs
  • Keep the same look, feel, and animations
  • Maintain Starter Compatibility
  • Maximize code re-use from iOS version
  • Add support for browsing history

So with this in my mind and a Southwest plane ride back from Arizona without internet I started my journey on bring My StepCounter to Android.

Step Counter & Step Detector

Android 4.4 introduced 2 new sensors apis for step tracking:
This sensor triggers an event each time the user takes a step. Upon each user step, this sensor delivers an event with a value of 1.0 and a timestamp indicating when the step occurred.

This sensor also triggers an event upon each detected step, but instead delivers the total accumulated number of steps since this sensor was first registered by an app.

These 2 types seem extremely similar, but the documentation says something very important:

"Be aware that these two step sensors don’t always deliver the same results. The TYPE_STEP_COUNTER events occur with a higher latency than those from TYPE_STEP_DETECTOR, but that’s because the TYPE_STEP_COUNTER algorithm does more processing to eliminate false positives. So the TYPE_STEP_COUNTER may be slower to deliver events, but its results should be more accurate."

So I wanted to test them out for accuracy. For testing I put my main logic in an Activity, although I know I would probably want to put this in a background service at some point. To be able to get notification sensors I had to implement ISensorEventListener, which has 2 methods in it:
OnAccuracyChanged: called when the accuracy changes.
OnSensorChanged: called when the sensor gets an update.
Before I could start testing out these sensors I wanted to make sure that my app could use them and have a way of detecting if the device my app was running on was compatible. So I had to add a little xml to the AndroidManifest.xml and also created a little helper method:

Now to take advantage of these sensors. I didn’t have to do anything for the accuracy changed since I was not interested in that, but for Sensor changed I had to either increase my step count for the step detector or calculate the total for the step counter so I could test accuracy:

With this code in place the only thing left to do was to register for the sensors. This involves grabbing the SensorManager and attempting to get the default sensor for the specific type and then registering the listener. It has multiple delay types, but normal seems to be the way to go:

Now that my sensors are all setup the last thing to do is put in a little UI to do some testing

Tracking steps with Xamarin.Android

There you have it my very first step counter!…. Alright well it isn’t nearly done at all, but this was just Part 1! Here is what I have mapped out currently on my timeline:
  • Part 2: Step Counting in a Bound Service
  • Part 3: Pretty UI
  • Part 4: Pretty Animations
  • Part 5: Saving Info to ADO.NET Database
  • Part 6: Shipping this app!
April 10, 2014 12:00 GMT

Xamarin Evolve 2014 Registration Now Open

Untitled-1We are very excited to announce the opening of registration for Xamarin Evolve 2014, our worldwide developer conference! Join us and fellow developers from October 6-10 in Atlanta, Georgia for the largest cross-platform mobile development event of the year!

Even Bigger!

This year, we’re doubling capacity and adding an extra day of conference sessions to make room for more great content covering mobile development with C#, Visual Studio, and Xamarin Test Cloud. Evolve sessions will cover a range of topics, including game-changing Xamarin product announcements by Nat and Miguel, best practices in mobile user experience design, advanced cross-platform techniques, memory management, real world app case studies from leading companies, secure data integration, lightning talks and so much more.

World-Class Training

Xamarin University LogoAttend two days of training from Xamarin University spanning all topics from mobile development fundamentals to advanced areas such as security and code-sharing strategies.

Learn from Mobile Experts

Over the course of three days you will have the chance to attend an immense amount of live sessions covering all areas of mobile development by industry leaders and experts. The entire Xamarin engineering team will be on-hand for one-on-one mobile coaching to answer questions, debug code, and provide advance.

Xamarin Evolve Welcomes Top Sponsor, Microsoft

We are also delighted to announce today that Microsoft will be joining Evolve 2014 again as our sole Platinum Sponsor. In recent months, Xamarin and Microsoft have partnered globally to help developers build great apps with C#, Visual Studio, and Portable Class Libraries, and this past week, Xamarin joined with Microsoft to launch the .NET Foundation. Together, Xamarin and Microsoft bring C# to 2.6 billion devices, and together we will make Xamarin Evolve 2014 an event you won’t forget.


Registration Now Open

Tickets for Xamarin Evolve 2014 our second worldwide developer conference, are officially available for purchase today.

Register Now

Team Xamarin

April 09, 2014 10:36 GMT

Swipe To Refresh added to Android

Swipe-to-Refresh animation

Google recently released an update to the Android support library bringing in an exciting new standard implementation of a pattern that they have been progressively introducing through applications such as GMail or Google Now.

This pattern, called swipe-to-refresh, uses an upward pull user feedback to inform the app that a data refresh is requested. This complete another common pattern, infinite scrolling, that instead use a downward movement to load more data.

We have updated our component to expose the new SwipeRefreshLayout class that implements the pattern. To make use of it, simply wrap in your existing Xamarin.Android app layout.

        android:layout_height="match_parent" />

Setting up the SwipeRefreshLayout instance is pretty easy from code. You simply have to define a color scheme and a callback that is invoked when an update operation is requested by the user.

refresher = FindViewById<SwipeRefreshLayout> (Resource.Id.refresher);
refresher.SetColorScheme (Resource.Color.xam_dark_blue,
refresher.Refresh += async delegate {
	await forum.FetchItems (clear: true);
	refresher.Refreshing = false;

The color scheme can be any set of color or the same color. In any case, the first parameter is also used as the initial feedback bar background.

We have also added a dedicated sample that shows how this code can be integrated in a complete scenario, including a complex layout utilizing fragments.

April 09, 2014 9:31 GMT

OpenSSL “Heartbleed” Update

You might have read by now that details of the “Heartbleed” OpenSSL vulnerability were published earlier this week. For those that don’t already know, OpenSSL is a popular, general purpose cryptography library in wide use across the internet. Like nearly every company on the internet, we immediately took audit of our systems, and uncovered some systems using a vulnerable version of OpenSSL. We immediately began updating all Xamarin services that were affected, and as of Tuesday afternoon, no Xamarin systems are subject to this vulnerability.

We have also reissued all HTTPS certificates for all xamarin.com domains with new encryption keys, and have had the previous versions revoked by our issuer, which was also completed Tuesday evening. At this point, we believe that it is extremely unlikely that any of our systems were compromised before we patched OpenSSL; however, for an additional layer of security, we recommend that you take the following steps to safeguard your Xamarin account — especially if you used the same password for your Xamarin account as on other accounts hosted elsewhere:

  1. Sign out of your Xamarin account and then sign back in (you’ll want to do this in the IDE as well)
  2. Change your Xamarin account password

At Xamarin we are committed to your security and privacy. We are continuing to track the issue closely and will keep you up to date if anything new is discovered. For more information on this OpenSSL vulnerability visit www.heartbleed.com

April 09, 2014 11:10 GMT

C#, iOS, and Android Take Center Stage at Build

It was an exciting week for .NET developers with a slew of announcements at this years Build conference in San Francisco.

Microsoft Build Sign

The most anticipated Build session of the week hands down was Miguel’s “Go Mobile with C# and Xamarin”, where over 1,500 developers packed the main hall for a chance to see Miguel talk on the transformation of mobile development. The audience loves seeing his live coding session where he used iOS’ CoreImage and Twitter integration to add Sepia filter to an image and tweet it out to the world!

Packed house at Miguel de Icaza's build talk

Continuing to wow the crowd, Miguel unveiled our brand new Xamarin T-shirt Store app enabling developers to try out Xamarin to build their first app to order their very own limited edition C# shirt that he was rocking on stage.

A major highlight of the week was when C#’s lead architect, Anders Hejlsberg, open sourced the .NET Compiler Platform, Roslyn, live on stage. This marked a major milestone allowing developers to gain access to a plethora of information that compilers have about the code we write each day. Immediately after Anders open sourced Roslyn, our own Miguel de Icaza hit the stage to showcase the power of an open sourced Roslyn by compiling code with a modified version of Roslyn running on Mono inside of Xamarin Studio on a Mac!

If Roslyn wasn’t enough, Xamarin took part in the official launch of the .NET Foundation. This new foundation will foster open development, collaboration and community engagement on the .NET platform. Xamarin initial contribution consists of six open source .NET Projects including Mailkit, Mimekit, System.Drawing, and more! We are excited to join other community leaders including Laurent Bugnion, Niels Hartvig, Paul Betts, and other to aid in advancing .NET open source projects..NET Foundation

The excitement for Xamarin, C#, and mobile apps continued throughout the week with an always packed Xamarin booth. Thousands of developers got to chat and get a hands on demo of creating beautiful Android and iOS apps in C#.

Packed Xamarin booth at //Build/

Build wouldn’t be complete without an epic Xamarin party, and this year was no different. Our friends .NET joined us to co-host a mega party in downtown San Francisco. Thousands of developers packed in to get face time with Nat, Miguel, Joseph, and the rest of the Xamarin crew at a party that is not to be forgotten! We want to thank everyone that was able to stop by the party and booth.

Xamarin Build Event at Mezzanine

If you thought that Build was epic, you will absolutely want to join us for Xamarin Evolve, the largest mobile developer conference of the year. Tickets go on sale on April 10th, so make sure to visit the official Evolve website to sign up for details.

April 08, 2014 4:30 GMT

Xamarin.Android SwipeRefreshLayout for #MvvmCross

I was very excited to see that the latest version of Support v4 for Android was updated to include as most people would says it a “Pull to Refresh”… or as Google would call it a “SwipeRefreshLayout”. It is now available in the Xamarin.Android Support v4 Component so we should probably take advantage of it! This is actually a really slick Layout that you can make the parent of any 1 layout and when the user swipes down on it you will get notified that you are supposed to refresh the content. This means you can now get rid of all of your refresh icon buttons in your UI and follow the same patterns Google has for their apps that your users will be used to.

Naturally I wanted to implement an MvvmCross version of this since I did an MvvmCross binding for UIRefreshControl on iOS a while back. So the goals here are simple:

1.) Execute an ICommand when someone pulls down to refresh
2.) Bind a bool to begin and end the refreshing spinner

So I created a very very simple MvxSwipeRefreshLayout which you can find the Gist for RIGHT HERE! In addition you will just need to implement a bit of code in your .axml layout and in your code behind to set the Refresh command.

April 08, 2014 12:14 GMT

Native Printing with Android

The latest version of Android, KitKat, adds long-awaited printing support to the platform. Android applications can now provide low-level control of print jobs, in addition to print integration for applications incorporating web content. This makes KitKat particularly well-suited to hybrid applications built with Xamarin using Razor templates.

Android KitKat Printing

Printing with a WebView

First let’s look at the easy to use print support offered through the WebView control.

Printing requires 3 steps:

  1. In an Activity, get a reference to the PrintManager system service.
  2. Create an instance of a class that inherits from PrintDocumentAdapter.
  3. Call the PrintManager‘s Print method, passing it the print adapter.

The PrintDocumentAdapter is an abstract class that provides a contract to implement for supplying print content. For web content, the WebView class includes a PrintDocumentAdapter, making printing HTML from a WebView incredibly easy to do:

The following example shows a WebView built using the Android WebView template, which uses Razor as an HTML templating engine:

Android Printing from a Xamarin Razor Template

Although printing can be done using any WebView, integrating printing with Razor and this project template makes it really easy to build a hybrid application that can leverage native features such as KitKat printing.

Printing from the WebView with C# is as simple as adding these 2 lines of code in the activity:

var printMgr = (PrintManager)GetSystemService(Context.PrintService);
printMgr.Print("Razor HMTL Hybrid", webView.CreatePrintDocumentAdapter(), null);

When we call Print Android presents a system dialog, allowing the user to choose the print destination, as shown below:

Android Print Dialog

Custom Print Adapter

To print from native Android views, taking low-level control of the print layout, we can implement our own PrintDocumentAdapter.

For example, let’s say we would like to print the layout from the following screen:

Android Print Activity Low Level

In our implementation of PrintDocumentAdapter, the required methods to implement are:

  • OnLayout – Allows laying out print content based on the PrintAttributes.
  • OnWrite – Allows writing a PDF file with content to print.

In OnLayout, we create a PrintDocumentInfo instance, which contains metadata about the document being printed.

public override void OnLayout (PrintAttributes oldAttributes, PrintAttributes newAttributes,
                               CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
  document = new PrintedPdfDocument (context, newAttributes);
  CalculateScale (newAttributes);
  var printInfo = new PrintDocumentInfo
    .Builder ("MyPrint.pdf")
    .SetContentType (PrintContentType.Document)
    .SetPageCount (1)
    .Build ();
  callback.OnLayoutFinished (printInfo, true);

In OnWrite, we implement the code to draw printed content and write it to the output stream to be printed.

public override void OnWrite (PageRange[] pages, ParcelFileDescriptor destination,
                              CancellationSignal cancellationSignal, WriteResultCallback callback)
  PrintedPdfDocument.Page page = document.StartPage (0);
  page.Canvas.Scale (scale, scale);
  view.Draw (page.Canvas);
  document.FinishPage (page);
  WritePrintedPdfDoc (destination);
  document.Close ();
  document.Dispose ();
  callback.OnWriteFinished (pages);

Printing with our custom adapter is just like using the WebView‘s adapter. Simply pass an instance of the custom adapter, called GenericPrintAdapter in this case, to the PrintManager‘s Print method:

var printManager = (PrintManager)GetSystemService (Context.PrintService);
var content = FindViewById<LinearLayout> (Resource.Id.linearLayout1);
var printAdapter = new GenericPrintAdapter (this, content);
printManager.Print ("MyPrintJob", printAdapter, null);

When the user clicks print, the same system dialog is displayed. In addition to a local printer, you can select Google Cloud Print or print to a PDF file, resulting in the print shown below:

Android Printed to PDF

The printing support added to KitKat is a much welcome feature that is easy to get started with. You can download the code used in this post from my GitHub repo.

Discuss this post in the Xamarin forums.

April 07, 2014 3:30 GMT

Sennheiser Cuts Development Time by 40% with Xamarin

SennheiserlogoSennheiser is a world leader in quality audio experiences.  The company recently launched Sennheiser TeamConnect, an end-to-end enterprise-grade meeting solution that integrates speakers, microphones, and a central control unit.  When it came to the central control unit used by employees to remotely control the telephone line and audio levels of TeamConnect, the company sought simplicity for the product’s user interface.

Rather than creating a physical control panel, the company decided to put the controls into the user’s hands via an iOS app for iPads and iPhones.

Dirk Eismann, the main developer on the project had experience using Apache Flex, PhoneGap, and pure Objective-C for iOS development, but this was the first Xamarin project for him.

Screen Shot 2014-03-24 at 11.27.41 AM

“I knew that Xamarin’s performance advantages over other cross platform tools and its rock-solid support for all of the iOS APIs were just what this project needed.“ Eismann says.

With a long background in Java, and a familiarity with C#, Eismann found it easy to make the transition to Xamarin, and completed the application code within just 6 weeks.

“Xamarin makes it surprisingly easy to do native mobile development,” Eismann says. “I especially liked how concepts common to .NET developers like events and delegates are added on top to the iOS API. This greatly simplifies development for anyone who has worked with .NET code.”

Download the full case study to learn more about the benefits Sennheiser has enjoyed from using Xamarin—including 40% faster development time, precisely mapped APIs, ease of use, and the ability to share code across platforms.

View the Case Study

April 02, 2014 4:45 GMT

SlidingUpPanel port for Xamarin Android!

I spent some of my time yesterday on a bit of porting Java to C#, instead of sitting in the sun and drinking beer. I found this pretty neat little library, AndroidSlidingUpPanel, which adds a panel to your app, which slides up from either the bottom or top of your screen. The code itself is very inspired by the innards of SlidingPaneLayout from Support v4.

Anyways, here is a GIF of what it looks like:

Adding to your project is pretty simple. Simply grab it from the Xamarin Component store or if you prefer, you can clone or download it from GitHub, which also has the component, but also the source code. There is a nice sample which will show you how to use this library, but if you just want to get started quickly. Simply add the following code to the AXML layout file you want this panel in:

So the SlidingUpPanelLayout should be the root of your layout, and then it will have two children. First child is your content layout, what your originally had in your layout. The second child is the contents of the panel. Now you are good to go! For more info look at the docs on either the component store or on GitHub!
April 02, 2014 10:00 GMT

Build a Cross-Platform, Mobile Golf App Using C# and Xamarin - MSDN Magazine Article

One of the fun things about the return of golf season is participating in tournaments that feature events such as a longest drive contest. In these, a person’s first shot off a designated hole is measured against others in the tournament. The longest drive during the day is declared the winner. However, these contests typically don’t have centralized scoring. If you’re in the first group, you don’t know until after the event is over where your shots stand in relation to everyone else’s. Why not use a mobile phone to record the starting point and ending point of drives and store the information in a cloud-hosted database?

The options for building such an app are many, which can be confusing. In this article, I’ll walk through how I built such an app using the back-end options in Windows Azure and how I handled various issues. I’ll show the code for writing an app for Windows Phone as well as iOS using Xamarin.

Several features were required. The app needed to run across mobile devices and multiple device OSes. It had to be a native app that looked just like all of the others on a device. The back-end server had to be always available, with minimal hassle to the developer (me). The cloud services had to provide as much help as possible in the area of cross-platform development. The back-end database needed to provide some amount of geolocation functionality.

Url: http://msdn.microsoft.com/en-us/magazine/dn630648.aspx


Many thanks to Brian Prince, Kevin Darty, Tara Walker, Craig Dunn, and a host of others for reviewing the article

PS. You don't have to go to Build to get this Cross Platform Awesomeness


April 01, 2014 6:50 GMT

Xamarin Component Store and NuGet: A Love Story

I've published a new set of NuGet packages which allow you to depend on Xamarin Store Components in your NuGet packages. These packages, when installed, will add a Component to the target project.

NuGet Packages that have Component Dependencies

If you're writing an Android library, your code often ends up using one of the Google Support Libraries. This goes well until you attempt to package your library into a NuGet package. What to do with the Support Library? If you include it in the package, it will blow up if the target project is already using the Support Library, and if you don't include it, your library doesn't work unless they include the Support Library manually.

This problem isn't solely on Android either - the same applies for certain libraries on iOS as well, such as Xamarin.Auth or Google Maps for iOS. What do we do?

Add xamstore- references

For several Xamarin Components often used in Libraries, I've created "Shim packages". Here's how to use them:

<?xml version="1.0"?>  
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">  
    <title>Helper code for Glass Apps</title>

      <dependency id="xamstore-googleglass" version="1.1" />

The package name is always the prefix xamstore-, then the Xamarin Component ID (in the URL of the store page)

Wait, so should I use this in my app?

Nope, you should just right-click on the Components folder like you did before, the only reason to use these packages is if you're a library author. If you're not writing a .nuspec file, you don't need these!

What witchcraft is this??

Shim packages don't actually contain any binaries - they simply contain a .props file which trigger Xamarin to install the listed Component into your project. Unfortunately, instead of being able to just install the component, we have to ask the user to close and reopen the solution - if anyone comes up with a clever way around this, I'd love a Pull Request!

How do I add more?

Send a pull request to paulcbetts/component-store-nupkg-builder

March 30, 2014 8:18 GMT

Filtering ListView with SearchView in Xamarin.Android

I recently made a video describing how to add a SearchView to your ActionBar, using the Support v7 package to provide backwards support, all this done in Xamarin.Android! I posted it on the Xamarin Forum's, University section, which I have access to, since I am attending Xamarin University. There were some interesting questions, which I found solutions for and I simply wanted to share them, so I am writing this blog post to do so. For background knowledge take a look at this video, which started this, and I am going to use that as a starting point for this blog post.

So the video, shows a very simple implementation of SearchView, which filters simple string elements feeded into the ArrayAdapter, which already has a nice simple Filter implementation, which simply matches the search query to see if it is contained in the items in the ListView. Now this simple implementation might not be sufficient enough for you, because as soon as you need to show something more complicated in a ListView, you will need to implement your own Adapter. Doing so will also require you to implement your own Filter as the Adapter you implement yourself cannot know what arbitrary data you will present.

SearchView filtering ArrayAdapter

Anyways, enough talk, let us dive into the code. So easy mode as described in the video and gist:

So here the magic happens in the OnCreateOptionsMenu method line 39-58, where we find the ActionBar MenuItem and subscribe to the SearchView's ActionView query changes, which invokes the default Filter in the ArrayAdapter.

Reacting on SearchView Expand/Collapse

One of the questions that popped up was, when having the back Action enabled in the ActionBar when using the SearchView, how do you react to the Expand and Collapse events? This is pretty simple, but might not be that super obvious.

You have to create a class implementing IOnActionExpandListener. In this example I am going to remove the filter from the Adapter when collapsing the SearchView.

To hook it up to the SearchView you have to use the helper class MenuItemCompat, to attach it to the MenuItem which you do in the OnCreateOptionsMenu:

Filtering in custom Adapters

Now the other question was, how do I filter my custom Adapter? Very good question if you ask me. As already mentioned, for that you have to implement your own Filter, as the nature of a custom Adapter is that you present custom stuff. Hence the default Filter implementation cannot know how to filter that. I am just going to replicate what the default Filter does on a string property of the model I am going to present in the ListView.

The final solution can be found on → GitHub

So before we begin I have to warn you that FilterResult which is used to store the filtered values temporarily, expects that the object stored is a Java type. So either your model which you populate your Adapter with has to implement Java.Lang.Object or you will have to wrap your values. I will show you the latter, as it will apply to the more use cases, as you probably cannot and probably do not want to implement Java.Lang.Object in your contracts or whatever you are using to store data in, especially when you are communicating and sharing code between platforms.

To wrap up .NET types with a Java type I am using modified code from this monodroid mailing list thread, which looks like this:

The main difference is that the Java holder object is disposed of immediately when it is converted to a .NET object. Also the comparison in the original source, whether the value was null is unsafe, as it does not take value types into consideration. The object disposal is very useful to keep GREF references down to a minimum. I really don't want the app to run high on memory.

Now with that covered, let us get to the actual Adapter and Filter. I have created a class called Chemical, which has Name and DrawableId property. Which are going to be assigned to a custom view, in the Adapter. Not going to cover View creation here, but this one is pretty simple, really.

So Chemical looks like this:

And the Adapter looks like this:

So I am just going to describe what happens in the custom ChemicalFilter, as the rest of the Adapter is pretty trivial. So first thing is that I have to pop in the reference to the ChemicalsAdapter, because I want to store both the original list of Chemicals and the filtered version in the Adapter, so we always can go back to the state we started at. So I always look for matches in the _originalData field, which is looped and matched, lower case, if the Chemical contains anything in the ICharSequence which is passed into the PerformFiltering method. The ICharSequence is just a spartan Java interface providing some simple methods such as lenght, getting a char at at specific position and a sub sequence of chars, nothing too fancy. I simply convert that to a string and match against the Chemical Name property. So the results of that matching is transformed into an array of Java objects, with help of the modifier .NET to Java wrapper I described above using a bit of LINQ. This is done since FilterResults expects an array of Java objects. I also call Dispose on the ICharSquence, as it seems like not doing so builds up the GREF count.

Now in PublishResults the values are converted back to the Chemical .NET type also using a bit of LINQ. The results are set in the Adapter's _item field and the Adapter is notified of the changes in the data set. Both arguments are Disposed of.

So, this is pretty simple stuff. It is just the conversion from Java to .NET and the other way around that can cause some troubles. So just keep in mind, that if your GREF count is rising, then you should probably look into Disposing of some of your stuff.

Again the final solution can be found on → GitHub
March 30, 2014 3:31 GMT

Xamarin.Android Templates Pack!

Xamarin.Android already ships with a bunch of great project templates for Visual Studio, however I find that there are a few things missing. I usually start a new project with a Navigation Drawer and I am always adding new Menus, but I can never seem to remember every little bit of XML that is needed for some complex menus such as share and search. This is why I have created the Xamarin.Android Templates Pack. This is the first release that includes these items that I have listed. You can download it immediately from the Visual Studio Gallery and browse the code on GitHub.

Included in the Menu Items are not only the XML required but also the code behind that will help you implement it. Once you have the Template pack installed you will see the items when you starter a new project or add an item to the menu folder in Resources.

Navigation Drawer:

Menu Item:

Share Menu:

Search Menu:

I am going to be continuing to add more and more templates and please feel free to add an issue or do a pull request if you want to see something.