July 01, 2015 6:45 GMT

iOS 9 Preview Now Available

ios9 iconWe’re excited to announce that we have just published our first iOS 9 API preview release in Xamarin.iOS. This preview includes support for an array of exciting new features that you can start developing with today, including CoreSpotlight, Model I/O, and ReplayKit as well as improvements to Contacts APIs.

Installing the iOS 9 Preview

You can download the iOS 9 Preview for Xamarin Studio directly from the Xamarin Developer site. Upcoming previews will add even more support for iOS 9, including support for Visual Studio.

Important: Service Release for iOS 9 Compatibility

In addition to our iOS 9 preview release, we have also published an iOS release to our update channels addressing two issues that cause many Xamarin apps to crash on startup on Apple’s OS preview for iOS 9.

At WWDC last month, Apple announced that a public preview of iOS 9 will be made available to iOS users this July. To ensure your published apps run smoothly on Apple’s iOS 9 public preview this month, we recommend that Xamarin.iOS developers download the latest release from our Stable updater channel and rebuild and resubmit their apps to the App Store using Xcode 6. This will enable your apps to run on the iOS 9 OS preview and ensure your apps are ready for the public release of iOS 9 this fall.

You can read more about these updates in our iOS 9 Compatibility Guide.

The post iOS 9 Preview Now Available appeared first on Xamarin Blog.

July 01, 2015 5:45 GMT

Code Mill Minute: Setting Up Xamarin Studio To Work With TFS Online Git Source Control

Today I’m starting a new series of blog posts entitled “Code Mill Minute”. These will be a departure from my normal novel length posts (I’m trying to shorten those too, but that’s another story) and will focus on just fixing or doing something that we developers encounter on a day to day basis.

Short and sweet… to the point… and only takes a minute to read.

So let’s dive into today’s topic … integrating Xamarin Studio on the Mac with TFS Online’s (aka Visual Studio Online) Git source control.

The Problem

By default, the account you login as to Visual Studio Online is your Microsoft account, which is an email address. The problem with that is the “@” symbol. Applications other than Visual Studio have an issue using that symbol to connect with Git.

The Solution

We need to enable another set of credentials in TFS Online, link the new credentials up to our existing VSOnline account, clone the repository with our new user, then have Xamarin Studio perform a remote Git operation, so it can cache the user credentials as well.

Enabling VSOnline Alternate Credentials

The first thing we’ll do is enable alternate credentials in VSOnline. To do so, follow these steps.

  1. Login to VSOnline with your normal credentials
  2. In the upper right corner, you’ll see your name, click on that, then click on “My Profile” in the resulting dropdown.
  3. A screen similar to the one below will appear. Click on the “Credentials” tab and then “Enable Alternate Credentials”.
    Enabling Alternate Credentials

    Enabling Alternate Credentials

  4. Enter the username and password you want to use for Git access with Xamarin Studio (or the command line).

Integrating With Xamarin Studio on the Mac

Next we need to clone the repository with the new credentials, then make sure Xamarin Studio has those credentials cached as well.

  1. First, note the clone URL of the repository from TFS Online. (This can be found from the “clone” button while viewing the top level source code structure within TFS Online website.)
  2. Open up Terminal and navigate to the directory you want to clone the repository to.
  3. Run the Git clone command with the URL of the repository you want to clone to (from step 1 above).
    git clone "https://testproject.visualstudio.com/DefaultCollection/_git/Test"
  4. You’ll be prompted for your username and password – enter the “alternate” ones you just created.
  5. Then you’ll see a screen similar to this… I had no idea what it was at first & I thought I did something wrong, but then I realized it was the friendly Visual Studio logo!
    TFS Git Cloning!

    TFS Git Cloning!

  6. Finally, you can start using local Git within Xamarin Studio as normal. When you need to do the first operation against the remote repository, you’ll be prompted for your username and password – again this is the “alternate credentials” you created. Once entered, Xamarin Studio will cache them, and you’ll be off and running!

That’s all there is to getting a TFS Online Git repository working with Xamarin Studio on the Mac … the secret sauce really is just enabling alternate credentials with your Visual Studio Online account. Once that’s done… off to the races!

July 01, 2015 12:00 GMT

Taking Attendance with Xamarin, Beacons and Microsoft Azure

This post is going to be a little different than my normal Xamarin.Forms posts. I want you all to know that I am more than a pretty interface. I have architectural and distributed systems chops as well.

I currently work for a local university that needs a solution for taking attendance for the first 3 weeks of every semester. You see, the university I work for is not an attendance taking university, but we need to satisfy a government requirement to take a student’s attendance to get financial aid. So I was asked to solve this little problem using mobile.

Here was the challenge

Students will walk into class and have their attendance taken automatically without the teachers involvement. Magically Delicious!


To solve the problem, I combined some very cool technology and one of them, of course, is Xamarin and Xamarin.Forms, but it’s not the star of this blog post. The star is iBeacons, specifically Estimote Beacons.

If you don’t know what an iBeacon is, don’t worry. Think of them as tiny radio stations that transmit their signal over Bluetooth. The Bluetooth signal can range from a few feet to over 200 feet for each station.

The beacons broadcast a small amount of data every few seconds to receivers that are tuned to its specific address. Each classroom at the university will get its own beacon and it will broadcast the building and the room number of the classroom.

When a phone comes in contact with the beacons signal, it will then wake the Xamarin app up and give it 10 seconds to do its work. This works even if your app is not running. Neat!

Beacon Phone Home

Ok, now that the phone has come into range of our classroom radio station, what do we do now? For this application, the app transmits the beacon data and the student’s identity to the cloud. We call this message a beacon ping. To the cloud!


The university’s student mobile application is backed by an Node.js Azure Mobile Service. I know, I use C# on the phone and JavaScript on the server, the irony!

cir-cloudAs you can imagine, we will have a lot of pings coming into the Azure front ends. Today most of that data will be used for attendance but we have no idea where the school will place beacons in the future. Maybe they’ll put them in front of the food venues to figure out which is the most popular. Or put them on the light posts outside to see what walkways are the busiest. We just don’t know what the genie will do once it’s let out of the bottle.

Beacon PubSub

With all the unknowns for our system, flexibility was something we had to build into the system from the beginning. I decided to use the Azure Message Bus in a PubSub configuration to handle today’s and tomorrow’s requirements. This configuration is very powerful and it’s so simple to setup it borders on criminal.


Our day 1 configuration for the Beacon PubSub was for the Azure Mobile Service to take in pings from the handset and push them onto the “BeaconPing” topic inside of the Azure Message Bus. Two subscriptions are added to the topic, one for taking attendance and one for auditing.

Taking Attendance

cir-todo-listTaking attendance is pretty simple. For every ping, we look up a student’s schedule based on the StudentId inside the ping and see if the beacon’s location matches the classroom on their schedule. If we have a match, then we mark them as attended. If not, we throw the ping away and move on. Students can easily come into contact with beacons from other classrooms so we just handle that case by ignoring the ping. The attendance module is idempotent so duplicates are not a problem.


The audit subscription will subscribe to every ping and put the pings into Hadoop for future analysis. I have no doubt our computer science students will have some fun with that data in the years to come.

The Future

cir-pacmanOne of the benefits to using PubSub like this is flexibility. With each ping, identifying the student and a location on campus, the opportunities are endless. One scenario we like to talk about is placing a beacon on our school mascot and running reports to see what part of the student body came in contact with our furry friend. I don’t know why we would want to do that, but we could. Beacons don’t have to be stationary either.

The Endless Possibilities

cir-rotate-clockwiseThe one reason why I like this system and setup is flexibility and the fact that we don’t have to change the code on the mobile app when we add a new type of beacon or beacon processor. We just put more beacons on campus and another processor in the cloud and we’re done. See, like I said in the beginning of this post, I’m not just a pretty interface!

One thing to note here is that some students might not have a phone or wish to be tracked in this manner. Our students using the app have a choice to enable or disable this feature and we still have to have a manual way to taking attendance at the school. Because some student may have a Windows or Blackberry phone! 😉

The post Taking Attendance with Xamarin, Beacons and Microsoft Azure appeared first on Syntax is my UI.

July 01, 2015 3:18 GMT

Build Time Code Generation in MSBuild

Build-time code generation is a really powerful way to automate repetitive parts of your code. It can save time, reduce frustration, and eliminate a source of copy/paste bugs.

This is something I'm familiar with due to my past work on MonoDevelop's tooling for ASP.NET, T4 and Moonlight, and designing and/or implementing similar systems for Xamarin.iOS and Xamarin.Android. However, I haven't seen any good documentation on it, so I decided to write an article to outline the basics.

This isn't just something for custom project types, it's also something that you can include in NuGets, since they can include MSBuild logic.


The basic idea is to generate C# code from other files in the project, and include it in the build. This can be to generate helpers, for example CodeBehind for views (ASPX, XAML), or to process simple DSLs (T4), or any other purpose you can imagine.

MSBuild makes this pretty easy. You can simply hook a custom target before the Compile target, and have it emit a Compile item based on whatever input items you want. For the purposes of this guide I'm going to assume you're comfortable with enough MSBuild to understand that - if you're not, the MSDN docs are pretty good for the basics.

The challenge is to include the generated C# in code completion, and update it automatically.

An IDE plugin can do this fairly easily - see for example the Generator mechanism used by T4, and the *.designer.cs file generated by the old Windows Forms and ASP.NET designers. However, doing it this way has several downsides, for example you have to check their output into source control, and they won't update if you edit files outside the IDE. Build-time generation, as used for XAML, is a better option in most cases.

This article describes how to implement the same model used by WPF/Silverlight/Xamarin.Forms XAML.

Generating the Code

First, you need a build target that updates the generated files, emits them into the intermediate output directory, and injects them to the Compile ItemGroup. For the purposes of this article I'll call it UpdateGeneratedFiles and assume that it's processing ResourceFile items and emitting a file called GeneratedCode.g.cs. In a real implementation, you should use unique names won't conflict with other targets, items and files.

For example:

<Target Name="UpdateGeneratedFiles"
  Condition=="'@(ResourceFile)' != ''"
    <Compile Include="$(IntermediateOutputDir)GeneratedFile.g.cs" />
    <FileWrites Include="$(IntermediateOutputDir)GeneratedFile.g.cs" />
<Target Name="_UpdateGeneratedFiles"

A quick breakdown:

The UpdateGeneratedFiles target runs if you have any ResourceFile items. It injects the generated file into the build as a Compile item, and also injects a FileWrites item so the file is recorded for incremental clean. It depends on the 'real' generation target, _UpdateGeneratedFiles, so that the file is generated before the UpdateGeneratedFiles target runs.

The _UpdateGeneratedFiles target has Inputs and Outputs set, so that it is incremental. The target will be skipped if the output file exists is newer than all of the input files - the project file and the resource files.

The project file is included in the inputs list because its write time will change if the list of resource files changes.

The _UpdateGeneratedFiles target simply runs a tasks that generates the output file from the input files.

Note that the generated file has the suffix .g.cs. This is the convention for built-time generated files. The .designer.cs suffix is used for user-visible files generated at design-time by the designer.

Hooking into the Build

The UpdateGeneratedFiles target is added to the dependencies of the CoreCompile target by prepending it to the CoreCompileDependsOn property.


This means that whenever the the project is compiled, the generated file is generated or updated if necessary, and the injected Compile item is injected before the compiler is called, so is passed to the compiler - though it never exists in the project file itself.

Live Update on Project Change

So how do the types from the generated file show up in code completion before the project has been compiled? This takes advantage of the way that Visual Studio initializes its in-process compiler that's used for code completion.

When the project is loaded in Visual Studio, or when the project file is changed, Visual Studio runs the CoreCompile target. It intercepts the call to the compiler via a host hook in the the MSBuild Csc task and uses the file list and arguments to initialize the in-process compiler.

Because UpdateGeneratedFiles is a dependency of CoreCompile, this means that the generated file is updated before the code completion system is initialized, and the injected file is passed to the code completion system.

Note that the UpdateGeneratedFiles target has to be fast, or it will add latency to code completion availability when first loading the project or after cleaning it.

Live Update on File Change

So, the generated code is updated whenever the project changes. But what happens when the contents of the ResourceFile files that it depends on change?

This is handled via Generator metadata on each of the ResourceFile files:

  <ResourceFile Include="Foo.png">

This takes advantage of another Visual Studio feature. Whenever the file is saved, VS runs the UpdateGeneratedFiles target. The code completion system detects the change to the generated file and reparses it.

This metadata has to be applied to the items by the IDE (or the user). It may be possible for the build targets to apply it automatically using an ItemDefinitionGroup but I haven't tested whether VS respects this for Generator metadata.

Xamarin Studio/MonoDevelop

But we have another problem. What about Xamarin Studio/MonoDevelop?

Although Xamarin Studio respects Generator metadata, it doesn't have an in-process compiler. It doesn't run CoreCompile, nor does it intercept the Csc file list, so its code completion system won't see the generated file at all.

The solution - for now - is to add explicit support in a Xamarin Studio addin to run the UpdateGeneratedFiles target on project load and when the resource files change, parse the generated file and inject it into the type system directly.


Migrating automatically from a designer-generation system to a build-generation system has a few implications.

You either have to force migration of the project to the new system via an IDE, or handle the old system and make the migration optional - e.g. toggled by the presence of the old files. You have to update the project templates and samples, and you have to build a migration system that removes the designer files from the project and adds Generator metadata to existing files.

June 30, 2015 9:39 GMT

Love and Free Apps

This. 100 times this.

This is the age of writing iOS apps for love.

Well, that’s not true for everybody. Well-established and awesome companies such as Omni, Panic, Flexibits, AgileBits, Tapbots, and The Iconfactory have a business writing iOS apps. (They do it for love, but not just for love.) Companies like Black Pixel make money by writing apps for other companies that have money.

And big companies and funded companies don’t actually have to make money from their iOS apps. They have other goals. (I don’t pretend to understand the economics of funded companies.)

You the indie developer could become the next Flexibits. Could. But almost certainly not. Okay — not.

What’s more likely is that you’ll find yourself working on a Mobile Experience for a Big National Brand(tm) and doing the apps you want to write in your spare time.

If there’s a way out of despair, it’s in changing our expectations.

Write the apps you want to write in your free time and out of love for the platform and for those specific apps. Take risks. Make those apps interesting and different. Don’t play it safe. If you’re not expecting money, you have nothing to lose.

Could the do-it-for-love era — with the creative freedom that that brings — bring us back to the days when we downloaded apps that weren’t from Facebook and Starbucks and Funded Company X, and we told our friends about our exciting finds?

I hope. I have hope.

Niche is the only other area I can see. Find something where you - or someone close to you - have an itch. Scratch it with an App. See if other people have the same itch. eg:

  • Trip Wallet. We needed something to keep track of travel spending on a long trip
  • Nearest Bus. I was catching the bus a lot in London
  • mobileAgent. I was using FreeAgent a lot, and wanted to do it from my phone.
  • On the roll (unreleased). Leonie needed to keep track of what film was in her various cameras.
  • Tides (unreleased). I could only swim in a +/- 2 hour window of high tide. So I wrote an app which reminded me of that.

Find an itch. Scratch it. Do it for love.

June 30, 2015 8:51 GMT

Refining the Economics of Your App for the Right Market

Url: https://visualstudiomagazine.com/articles/2015/06/30/app-to-market-part-2-right-app.aspx

In part 1, we looked at researching whether your brilliant idea was worth pursuing as a business venture and it all starts with seeing if the need exists. Now that you've validated that there is a need for the product, only then is it time to start building things. Let's take the next step, which is to work through the basics of the economics of your idea.

June 30, 2015 7:13 GMT

TechDays 2015

Den 20 oktober börjar TechDays med förkonferens, jag och Johan Karlsson kommer att dela med oss av våra kunskapar gällande cross-platformutveckling.

Att bygga cross-platformlösningar är alltid en stor utmaning då det i grunden är olika operativsystem, programmeringsspråk och utvecklingsmiljöer.
Xamarin löser en stor del av cross platform problematiken genom att man kan utveckla appar för iOS, OSX och Android med C#. iOS och Android kan även byggas i Visual Studio. Under dagen kommer vi gå genom hur man bygger arkitektur och gränssnitt för en optimal native upplevelse på varje plattform, det vill säga iOS, OSX, Android och Windows. Vi kommer också att visa hur man kan testa mobila applikationer på ett effektivt sätt med hjälp av Xamarin TestCloud.

Läse mer här, http://tdswe.kistamassan.se/Program-2015/Sessioner/Pre-Conf-Cross-Platform-pa-ratt-satt

June 30, 2015 5:59 GMT

Summer Fun with Xamarin Events in July

It’s July already! The year is already half over, so there won’t be a better time to get out and meet fellow Xamarin developers in your area to learn about crafting beautiful, cross-platform native mobile apps in C# at one of the local conferences, workshops, or user group events happening around the world!



Here are a few events happening this month:

Geek-a-Palooza! ad

  • Sant Julià de Lòria, Andorra: July 4th
  • Hands on Lab: Xamarin & Push Notifications

Mobile & Cloud Hack Day br

  • Hauer, Boqueirão Curitiba, Brazil: July 4th
  • A FREE event on how to create cross-platform apps for Android, iOS, and Windows using C#, Xamarin, and Visual Studio

Seattle Mobile .NET Developers us

  • Seattle, WA: July 7th
  • Introduction to Xamarin.Forms: iOS, Android, and Windows in C# & XAML with Xamarin Evangelist James Montemagno

Montreal Mobile Developers ca

  • Montreal, Canada: July 8th
  • Azure Mobile Services & Mobile Apps with Xamarin

XLSOFT Japan Japan

  • Tokyo, Japan: July 8th
  • Windows Phone / iOS / Android Cross-Platform App Development Using Xamarin.Forms

Birmingham Xamarin Mobile Cross-Platform User Group Flag of the UK

  • Birmingham, UK: July 8th
  • Developing for iBeacons with Xamarin

Introductory Training Session to Xamarin Germany

  • Hanover, Germany: July 13th
  • Xamarin Workshops by H&D International

DC Mobile .NET Developers Group in

  • Washington, DC: July 14th
  • NEW GROUP! Getting Started with Xamarin.Forms by Xamarin MVP, Ed Snider

Sydney Mobile .NET Developers au

New York Mobile .NET Developers us

  • New York, NY: July 28th
  • Building Native Cross-Platform Apps in C# with Xamarin by Xamarin MVP, Greg Shackles


Even more Xamarin events, meetups, and presentations are happening this month! Check out the Xamarin Events Forum to find an event near you if you don’t see an event in your area in the list above.

Interested in getting a developer group started? We’re here to help! Here’s a tips and tricks guide on staring a developer group, an introduction to Xamarin slide deck, and of course our community sponsorship program to get you started. Also, we love to hear from you, so feel free to send us an email or tweet @XamarinEvents to help spread the word and continue to grow the Xamarin community.

The post Summer Fun with Xamarin Events in July appeared first on Xamarin Blog.

June 30, 2015 4:47 GMT

XAML for Xamarin

My newest Pluralsight course, XAML for Xamarin.Forms is now available.  In this course you learn everything you need to know to achieve expertise in XAML to get the most out of Xamarin.Forms.  The major topics include

Rock Climbers

  • Getting Started
  • Introduction to XAML
  • Navigation and Events
  • Data Binding
  • Events
  • Lists
  • Tabbed Pages
  • XAML and MVVM
  • XAML Styles
  • Triggers
  • Messaging

This course is targeted at those who want to write in Xamarin.Forms but have little or no experience with XAML.  That said, experienced XAML programmers may well find the last two modules valuable.

June 30, 2015 8:19 GMT

iOS range slider for Xamarin and Xamarin.Forms

In this post I will show you how to build a range slider for Xamarin.iOS and how to write a custom renderer if you want to use it with Xamarin.Forms. If you want to use the range slider control you can write the code yourself or use the flipper forms control library, https://github.com/johankson/flipper, that can be installed from NuGet, https://www.nuget.org/packages/Flipper.Forms/. On GitHub you will also find a sample app that using the control.

iOS Range Slider

The control will be built up of six UIViews, one for the slider background, two for the indicators, two transparent views to increase the touch area for the indicators and one for the range between the indicators. The first step is to create a new class that inherits from UIView. In the constructor of the new class we are creating the views and adding them to the view. On the both indicators we’re adding a UIPanGestureRecognizer so we can detect when the users dragging the indicator.

public class RangeSlider : UIView
    private UIView _background, _leftIndicator, _rightIndicator, _range, _leftTouchArea, _rightTouchArena;
        private UIPanGestureRecognizer _leftIndicatorGesture, _rightIndicatorGesture;
     public RangeSlider()
            _background = new UIView();
            _background.BackgroundColor = UIColor.LightGray;
            _range = new UIView();
            _range.BackgroundColor = UIColor.Blue;
            _leftIndicator = CreateIndicator();
            _leftIndicatorGesture = new UIPanGestureRecognizer(OnPan);
            _rightIndicator = CreateIndicator();
            _rightIndicatorGesture = new UIPanGestureRecognizer(OnPan);
            _leftTouchArea = new UIView();
            _leftTouchArea.BackgroundColor = UIColor.Clear;
            _rightTouchArena = new UIView();
            _rightTouchArena.BackgroundColor = UIColor.Clear;
     private UIView CreateIndicator()
            var indicator = new UIView()
                   BackgroundColor = UIColor.Gray
            indicator.Layer.CornerRadius = 10;
            indicator.Layer.MasksToBounds = true;
            return indicator;

Then we need to layout our views, we will do that in an override of the LayoutSubviews method. We also need to check if the views already is layouted so the layout not will be restored to the start layout if the method runs again.

private bool _layouted;
public override void LayoutSubviews()
      if (!_layouted)
            _background.Frame = new RectangleF(0, 19, (float)Frame.Width-20, 2);
            _range.Frame = new RectangleF(0, 19, (float)Frame.Width-20, 2);
            _leftIndicator.Frame = new RectangleF(0, 10, 20, 20);
            _rightIndicator.Frame = new RectangleF((float)Frame.Width - 40, 10, 20, 20);
            _leftTouchArea.Frame = new RectangleF(0, 0, 40, 40);
            _rightTouchArena.Frame = new RectangleF((float)Frame.Width - 60, 0, 40, 40);
            _layouted = true;

In the OnPan method we want to update the position of the indicators if state of the gesture recognizer is began or changed. For this range slider we want the indicator to move in steps. To do this we need to move the indicator to next step if we have started to slide from the previous step. For that we need to know the step length in pixels and the cumulative manipulation and the delta manipulation. To calculate cumulative manipulation we need to save the position of the indicator when we starting the manipulation.

While you moving the indicator to next step when it has passed the previous you will have to check if the cumulative manipulation has passed the current step before you moving the indicator to next step.

 private void OnPan(UIPanGestureRecognizer recognizer)
            if (recognizer.State == UIGestureRecognizerState.Began || recognizer.State == UIGestureRecognizerState.Changed)
                var stepLength = _background.Frame.Width / ((MaxValue - MinValue) / Step);
                var touchPoint = recognizer.LocationInView(this);
                UIView indicator = null;
                UIView touchArea = null;
                //Is this a slide to left or right?
                if (recognizer == _leftIndicatorGesture)
                    indicator = _leftIndicator;
                    touchArea = _leftTouchArea;
                else if (recognizer == _rightIndicatorGesture)
                    indicator = _rightIndicator;
                    touchArea = _rightTouchArena;
                //save the start position for use when calculating cumulative manipulation
                if (recognizer.State == UIGestureRecognizerState.Began)
                    _startX = (float)indicator.Center.X;
                var cumulativeManipulation = touchPoint.X - _startX;
                var deltaManipulation = touchPoint.X - indicator.Center.X;
                //Check if the cumulative manipulation is has passed the last step
                if (deltaManipulation > 0 && cumulativeManipulation / stepLength > _lastStep ||
                    deltaManipulation < 0 && cumulativeManipulation / stepLength < _lastStep)
                    if (deltaManipulation > 0)
                    //Calculate the new position of the indicator
                    var numberOfSteps = Math.Ceiling(deltaManipulation / stepLength);
                    var newPosition = new CGPoint(indicator.Center.X + stepLength * numberOfSteps, indicator.Center.Y);
                    var pixelStep = (MaxValue - MinValue) / Frame.Width;
                    if (touchPoint.X >= 0 && touchPoint.X <= _background.Frame.Width-10)
                        if (recognizer == _leftIndicatorGesture)
                            var newLeftValue = Round(MinValue + (pixelStep * newPosition.X));
                            if (newLeftValue >= RightValue)
                        else if (recognizer == _rightIndicatorGesture)
                            var newRightValue = Round(MinValue + (pixelStep * newPosition.X));
                            if (newRightValue <= LeftValue)
                        if (recognizer == _leftIndicatorGesture)
                            indicator.Center = newPosition;
                            touchArea.Center = newPosition;
                            var width = _rightIndicator.Center.X - _leftIndicator.Center.X;
                            _range.Frame = new CoreGraphics.CGRect(newPosition.X, _range.Frame.Y, width, _range.Frame.Height);
                        else if (recognizer == _rightIndicatorGesture)
                            indicator.Center = newPosition;
                            touchArea.Center = newPosition;
                            var width = _rightIndicator.Center.X - _leftIndicator.Center.X;
                            _range.Frame = new CoreGraphics.CGRect(_range.Frame.X, _range.Frame.Y, width, _range.Frame.Height);
                        LeftValue = Round(MinValue + (pixelStep * _leftIndicator.Center.X));
                        RightValue = Round(MinValue + (pixelStep * _rightIndicator.Center.X));
                        if (ValueChanging != null)
                            ValueChanging(this, new EventArgs());
            else if (recognizer.State == UIGestureRecognizerState.Ended)
                if (ValueChanged != null)
                    ValueChanged(this, new EventArgs());
                _lastStep = 0;

I have added to events to the slider, ValueChanging and ValueChanged. ValueChanging occurs during the manipulation of the range slider and ValueChanged when the manipulation is finished. This because you maybe want to update labels with the values of the range slider during manipulation and update data based on the range slider when the manipulation is completed.

If you want to use the control with Xamarin.Forms you need to create a Xamarin.Forms control and a custom renderer. The Xamarin.Forms control will inherit from View and it will contains all the properties of the range slider, no logic at all.

 public class RangeSliderRenderer : ViewRenderer<Flipper.Controls.RangeSlider, iOS.Controls.RangeSlider>
        protected override void OnElementChanged(ElementChangedEventArgs<RangeSlider> e)
            if (e.NewElement != null)
                var slider = new Controls.RangeSlider();
                slider.Frame = new CGRect((float)Frame.X, (float)Frame.Y, (float)Frame.Width, 200);
                slider.ValueChanging += slider_ValueChanging;
                slider.ValueChanged += slider_ValueChanged;              
        void slider_ValueChanged(object sender, EventArgs e)
           if(Element.Command != null && Element.Command.CanExecute(null))
        void slider_ValueChanging(object sender, EventArgs e)
            Element.LeftValue = (float)Control.LeftValue;
            Element.RightValue = (float)Control.RightValue;

The complete code can be found at GitHub, https://github.com/johankson/flipper

June 29, 2015 7:15 GMT

Guide to Add Windows Phone to Xamarin.Forms 1.3+ Projects

I am a huge fan of Xamarin Studio and live inside of it around 50% of my development time. When I need to do library or Windows development though I head over to my good friend Visual Studio. Luckily the same exact project and solutions open in either IDE so it makes syncing with GitHub extremely easy. When I start up a Xamarin.Forms project I usually do it from Visual Studio so it spins up an iOS, Android, and Windows Phone Project. However, there are times that I am in XS, which doesn’t create the Windows Phone project so I need to add it after. Rob Gibbens wrote a great guide on adding Windows Phone projects to Xamarin.Forms in this case, but it is for the older Xamarin.Forms model pre 1.3. It is still a great guide and my guide follows this closely but updated with the new Application class requirements. Additionally, since Rob’s post we did release support for Windows Phone/Store RT apps and that process was documented as well, however Silverlight was left out, so let’s do it!

Going into this you will need at least Windows 8 and the Windows Phone SDK for Windows Phone 8.0 Silverlight.

Add Windows Phone Project

This is probably the easiest part of the process as all you need to do is right click on your Solution node and select Add -> New Project… From there you will need to find the Blank App (Windows Phone Silverlight) option under Installed -> Visual C# -> Store Apps -> Windows Phone Apps -> Blank App (Windows Phone Silverlight).

I personally name it: ProjectName.WinPhone and I turn OFF App Insights. You will then be prompted to select which version of Windows Phone to use. Simply select Windows Phone 8.0.

Restore NuGet Packages

You can always manually search for Xamarin.Forms in the NuGet Package manager, however it is easiest to actually right click on the SOLUTION node and select Manage NuGet Packages for Solution… This will allow you to see ALL NuGet packages installed in your projects and add them into your Windows Phone project. Simply Find Xamarin.Forms in the list, select Manage, and check ProjectName.WinPhone.

You may have additional NuGets installed so be sure to add those to your Windows Phone Project as well.

Fix Toolkit.Content

Xamarin.Forms uses the all powerful WPToolkit for some of its controls. When we added the Xamarin.Forms NuGet it also installed the WPToolkit NuGet and some new images were added under Toolkit.Content. We must select all of the files in this folder and mark the Build Action as Content and the Copy to Output directory to Copy always.

Add Portable Class Library or Shared Project Reference

Of course now we need to add in our shared code. Simply right click on the Windows Phone project’s references and find your “ProjectName” portable class library or Shared Project.

Modify MainPage.xaml

Xamarin.Forms 1.3 changed the normal flow of Xamarin.Forms applications include the Windows Phone’s main page, which is now inherits from FormsApplicationPage. We will now add in a custom xmlns of forms and then inherit from FormsApplicationPage:

Ensure you change “ProjectName” with your actual project name.

Modify MainPage.xaml.cs

Of course there is a bit of code behind to modify in the MainPage.xaml.cs to reference this new FormsApplicationPage and also call the LoadApplication of Xamarin.Forms. Simply replace the entire class with the following:

Ensure you change “ProjectName” with your actual project name.

You should be all set at this point with your Windows Phone project ready to go! 

June 29, 2015 7:10 GMT

What’s New in Google Play services

There are a plethora of amazing APIs built right into the core operating system to take advantage of when developing for Android, and Google Play services (GPS) allows for the addition of even more unique experiences.

What is Google Play services?

GPS LogoGPS is a continuously updated library from Google that enables adding new features to Android apps without waiting for a new operating system release. One of the most well known feature of GPS is Google Maps, which allows developers to add rich, interactive maps to their apps. Since GPS is a separate library that’s updated regularly, there are always new APIs to explore. The most recent release, 7.5, has tons of great new features.

Getting Started with Google Play services

In previous releases of GPS, everything was bundled into one huge NuGet and Component Library to be added to an app. However, this has now changed and each API has been broken into its own unique NuGet package, so you can pick and choose which features to add to an app without increasing app size or worrying about linking. To get started with GPS, simply open the NuGet Package Manager and search for “Xamarin Google Play services”. A list of new packages available for Android apps will be displayed, and you can choose to install the “All” package or select only the ones you want.


To learn more about the changes to the GPS packages and APIs, Xamarin Software Engineer Jon Dick’s blog post on the topic is a great place to start.

Once you have GPS installed, you can take advantage of tons of new APIs for your Android app, including some that I’m particularly excited about, outlined below.

Google Fit

fitness_64dpDevelopers of fitness apps will be excited to see that Google Fit has been updated with a brand new Recording and History API that enables gathering estimated distance traveled and calories burned in a simple API. This is in addition to the other APIs already available to discover sensors, collect activity data, and track a user’s fitness.

Android Wear Maps

Maps Android WearUntil now, there wasn’t a good way to show users their current location on a map on their Android Wear devices. The latest release, however, brings the entire Maps API to Android Wear, including support for interactive maps and non-interactive maps in Lite mode.

Google Cloud Messaging Updates

One of my favorite features of GPS has to be Google Cloud Messaging (GCM) for sending push notifications to Android devices, and there have been several updates to GCM in Google Play services 7.5. The new Instance ID tokens enable a single identity for your app across its entire lifetime instead of having a unique registration ID for each device. This simplifies the process of sending push notifications to all of the devices on which an app is installed.

So Much More

These aren’t the only additions to GPS with this release. Several new APIs have been added, including App Invites, Smart Lock for Passwords, and updates to Google Cast. The full list can be found in in the Google Play services documentation.

The post What’s New in Google Play services appeared first on Xamarin Blog.

June 29, 2015 12:00 GMT

Xamarin.Forms Android ActionBar Style Nugget

AndroidActionBarStyling the Action bar of the Android version of my Xamarin.Forms application took way to0 long. I, myself, will be referencing this post in the future.

I don’t know what it is about Android but my brain just doesn’t work the same way that Android developer’s brains work. I think something must be wrong with me. Too many Apples, maybe?

BarTextColor and BarBackgroundColor

The easiest way to style up your Android Action bar in Xamarin.Forms is to use the built in BarTextColor and BarBackgroundColor of a Navigation Page. You can see how well this works in the graphics on the right. Look at the pretty colors!

One thing you have to remember is to set both for each Navigation page of your application.

One page that you’ll have some problems with is MasterDetailPage. I don’t see how you can set the BarBackgoundColor or the BarTextColor for the MasterDetail unless you set every Navigation Page inside it. For MasterDetailPage and all the other pages in your application, you can use a custom Android theme instead.

Android Theme

I wouldn’t call this a theme. It’s more like a simple style tweak to an existing theme. My tweak is based on the Android Holo Light theme and all we do is set the Action Bar Text Color and the Action Bar Background Color.

To make this style tweak just add a styles.xml into your Droid/Resource/Values folder and add this XML snippet.

<?xml version="1.0" encoding="UTF-8"?>
	<color name="actionBarBackgroundColor">#185082</color>
	<color name="actionBarTextColor">#FFFFFF</color>

	<style name="MyTheme" parent="@android:style/Theme.Holo.Light">
		<item name="android:actionBarStyle">@style/MyTheme.ActionBarStyle</item>
	<style name="MyTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
		<item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
		<item name="android:background">@color/actionBarBackgroundColor</item>
	<style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
		<item name="android:textColor">@color/actionBarTextColor</item>

Once you have that done, we’ll have to apply the style to the whole app. In your AndroidManifest add a link to your Style like so. Pay close attention to the “android:theme=”@style/MyTheme”.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.syntaxismyui.kit">
	<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21" />
	<application android:label="MasterDetailKit" android:theme="@style/MyTheme" > 

You can name your theme whatever you like, just make sure that the AndroidManifest and the style names match. Now you can go about adding pages and a MasterDetailPage without setting the BarBackgroundColor or the BarTextColor of each page.

With Android out of the way, iOS is next.

The post Xamarin.Forms Android ActionBar Style Nugget appeared first on Syntax is my UI.

June 27, 2015 5:55 GMT

Reader Q&A – PDFs in iOS

I got a question from a reader last night who was looking at some code from one of my Xamarin seminars.

Ryan asked about how to extract the content from a pdf file, draw on it, and email it in iOS.

One way to do this is using Core Graphics, as shown in the following snippet:

If you have a question feel free to contact me through my blog. I get lots of questions like this, but I do my best to respond to them all.

June 26, 2015 3:16 GMT

Build and Debug C++ Libraries in Xamarin.Android Apps with Visual Studio 2015

Today, the Microsoft Hyperlapse team shared the story of how they developed their app with C++ and Xamarin. Microsoft Hyperlapse Mobile turns any long video into a short, optimized version that you can easily share with everyone. It can transform a bumpy bike ride video into a smooth and steady time-lapse, like this one from Nat Friedman that was shot using GoPro and processed with Microsoft Hyperlapse Pro.

The core algorithmic portions of Hyperlapse are written in Visual C++ Cross-Platform Mobile and the majority of the app business logic was retained in a .NET portable class library. Using Xamarin, the Hyperlapse team was able to leverage the core C++ code and app logic, while providing C#-based native UIs so users of the app feel at home on each platform. Leveraging C++ code in your Xamarin app is easy, as outlined in the below explanation on implementing C++ in your Xamarin.Android apps.

Using Native Libraries

Xamarin already supports the use of pre-compiled native libraries via the standard PInvoke mechanism. To deploy a native library with a Xamarin.Android project, add the binary to the project and set its Build Action to AndroidNativeLibrary. You can read Using Native Libraries for more details. This approach is best if you have pre-compiled native libraries that support either or all architectures (armeabi, armeabi-v7a, and x86). The Mono San Angeles sample port explains how the ibsanangeles.so dynamic lib and its native methods are accessed in Xamarin.Android.

In this approach, dynamic libraries are typically developed in another IDE, and that code is not accessible for debugging. This imposes difficulty on developers, as it becomes necessary to context switch between code bases for debugging and fixing issues. With Visual Studio 2015, this is no longer the case. Through our collaboration with the Visual C++ Cross-Platform Mobile team at Microsoft, Xamarin developers in Visual Studio now have the power to write, compile, debug, and reference C/C++ projects in Xamarin.Android from within their favorite IDE.

Using Visual C++ Cross-Platform Mobile

As stated above, Visual Studio 2015 supports the development of C/C++ projects that can be targeted to Android, iOS, and Windows platforms. Be sure to select Xamarin and Visual C++ for Cross-Platform Mobile Development during installation.

Visual C++ for Cross Platform Mobile Development

For this post, we’re using the same San Angeles port sample referenced earlier in the Using Native Libraries section. However, its original C++ code is ported to a Dynamic Shared Library (Android) project in Visual Studio. When creating a new project, the Dynamic Shared Library template can be found under Visual C++ → Cross-Platform.

Mono San Angeles Demo

San Angeles is an OpenGL ES port of a small, self-running demonstration called “San Angeles Observation.” This demo features a scenic run-through of a futuristic city with different buildings and items. The original version was made for desktop with OpenGL, and the current version is one of Google’s NDK samples optimized for Android. The source code is available here, ported to Visual Studio.

Now that the Dynamic Shared Library that contains the source code has been directly referenced from the Xamarin.Android project, it works as smoothly as any other supported project reference.

Visual Studio 2015 VC++ Cross-Platform Mobile

To interop with native libraries in your Xamarin.Android project, all you need to do is create a DllImport function declaration for the existing code to invoke, and the runtime will handle the rest. Set the EntryPoint to specify the exact function to be called in the native code.

[DllImport ("sanangeles", EntryPoint = "Java_com_example_SanAngeles_DemoGLSurfaceView_nativePause")]
static extern void nativePause (IntPtr jnienv);

Now, to call the native function, simply call the defined method.

public override bool OnTouchEvent (MotionEvent evt)
	if (evt.Action == MotionEventActions.Down)
	nativePause (IntPtr.Zero);
	return true;

Refer to Interop with Native Libraries to learn more about interoperating with native methods.

One More Thing…

Now that you have access to the native source code, it’s possible to debug the C/C++ code inside Visual Studio. To debug your C/C++ files, choose to use the Microsoft debugger engine under the Android Options of Project properties.

VC++ Native Debugging options

Enable a breakpoint inside your C++ project, hit F5, and watch the magic happen!

Learn More

Refer to the VC++ team’s blog post at MSDN for a step-by-step guide to building native Android apps in Visual Studio 2015. The source code for the Mono San Angeles port explained in this post is available for download in our samples.

Discuss this post in the Xamarin Forums.

The post Build and Debug C++ Libraries in Xamarin.Android Apps with Visual Studio 2015 appeared first on Xamarin Blog.

June 26, 2015 3:04 GMT

8 Weeks of Travel: Dev Days, Conferences, Podcasts, & More!

It has been a few busy months! For the last two months I have been in the air and on the road talking all about cross-platform mobile development with Xamarin, and it has been a blast! Our first leg of Xamarin Dev Days is just about to wrap up and it has been an absolutely amazing experience meeting so many incredible developers. I can’t wait to do it all again very very soon :)

Then comes the list of conferences! //Build, Ignite, Chicago Coder Conference, DevIntersection, Twilio Signal, VS Live Austin, and NDC Oslo! I feel as though my goal of being everywhere is mission accomplished! If you weren’t able to attend these events don’t worry as there were several recordings from NDC Oslo now available!

Xamarin.Forms: Native iOS, Android, & Windows apps in C# & XAML

In this session I give a brief overview of Xamarin.Forms and walk through File->New App!

CocosSharp-2D Games in C# that run everywhere

In the past I used to make awesome video games for the Xbox 360 and I am back at it with 2D games in C# with CocosSharp for iOS and Android!

C# and Twilio-powered iOS & Android Experiences!

Check out this session that I delivered at Twilio Signal on integrating amazing Twilio functionality into your mobile apps.


No time to watch a full video? I gotcha covered with some awesome podcasts that I have been on recently:
Xamarin Podcast: Covering Android M and Google I/O 2015

MS Dev Show: An amazing amazing show covering nearly every single aspect of Xamarin!


I have been doing a lot more than just talking as I have also been releasing some updates to apps and some new ones as well. Coffee Filter, my open source coffee finding application is now available on iOS thanks to the work of some Amazing Xamarins (Oleg, Colby, & Aaron). Additionally, I have updated the Android version to add in the amazing new Google App Invites feature! Check that out.
June 26, 2015 2:34 GMT

Weekly Xamarin Newsletter Issue #46

Android M Preview Now Available
Miguel de Icaza, from Xamarin Inc., announces the Xamarin preview of Google’s latest OS.

Xamarin.Forms Carousel View Recipe
Chris Riesgo has made his Carousel View, yes view, not a Page and it’s available to the Xamarin.Forms community.

Xamarin.Forms and Accessibility
I (Adam) talk about how well Xamarin.Forms did on the accessibility tests.

Live Webinar: Why Mobile Quality Matters
Steven Yi, from Xamarin Inc., opens up registration for a new webinar about Mobile Quality and Test Cloud.

Extending Xamarin.Forms Controls with Custom Renderers
Pierce Boggan, from Xamarin Inc., shows off some stylish custom renderers for Xamarin.Forms.

The Road to Xamarin Certification (Getting Started)
Chris Swain is writing about his Xamarin University experience in this blog series.

Web Service Resilience
Jonathan Yates makes his web service calls more robust and fault tolerant.

Xamarin: Apple Watch Talking to Parent App
Jesse Liberty, from Falafel Software, shows off the important relationships in an Apple Watch app.

Xamarin.Forms Kickstarter has been updated with more Xamarin.Forms goodness.


Don't miss out! Subscribe Today

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

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

June 25, 2015 2:13 GMT

Navigation with Xamarin.Forms


Xamarin Forms was released a bit more than a year ago. Since then, the product has grown, gone through rounds of features and bug fixes, and feels very much like it's ready for use in applications. And since then, mobile apps are no longer relegated to one screen. Mobile apps should work on multiple screens of functionality. And even then, users must be able to navigate between screens in a standard way. In this column, I'll look at how Xamarin Forms can be used to implement the various approaches to navigating on various devices.

Note: In early-to-mid 2014, this column featured articles on standard navigation in iOS and Android, but this column will show how to implement standard navigation with Xamarin.Forms. Also, graphics are not my specialty -- please excuse the graphics.

June 24, 2015 5:29 GMT

Startups and Technology Article 1 - Getting Your Application to Market


You are a developer.  You are at the top of your game.  You can make bits do magical things over the web.  Your database can run circles around anyone else's. You've got a great job. 

Unfortunately, that job is at a soulless corporation. That company sells widgets that have changed very little in the last 125 years. There is a ceiling for you as a developer at this company. You have users in marketing and production. Some of them you love, some you loathe. You long for something more. 

You hear about people making lots of money by starting product companies, but you aren't quite sure what you have to do. You watch Silicon Valley on HBO. You hear about this thing called Y Combinator. Then, one day it happens, you hit upon a great idea. It's something that you see all kinds of need for. What should you do now?

June 24, 2015 12:00 GMT

Xamarin.Forms and Accessibility

Xamarin.Forms Accessibility

My Xamarin.Forms mobile app just went through an extensive audit with our accessibility expert, Tommy. What he found was interesting.

I’m very lucky. I write cross-platform mobile applications for a local university here in the Phoenix area. We use Xamarin and Xamarin.Forms to create these applications for the traditional ground students of the university. Not all of the students who attend the university have perfect vision.

The accessibility of our mobile applications is a big concern for the university and myself, especially when it comes to the tools and frameworks we use. Our applications not only need to work and look good, they also have to be usable by the blind or vision impaired. One of the concerns about working with new tools or frameworks is its track record on accessibility.

Xamarin.Forms Accessibility

If you Google the term “Xamarin.Forms Accessibility” you come up with little or nothing. More like nothing. The most you’ll get today is something about testing with Test.Cloud and the “StyleId” field. This blog post will help.

Let’s dig into each section of the app from navigation, information display and maps. Each of these sections were tested on both Android and iOS devices. Our apps are mainly for young tech savvy teenagers, so no Windows Phone version today. If the university finds it has vision impaired student with Windows Phone, I’m ready to make a Windows Phone version, ASAP.


cir-navigationWe use the hamburger menu as the main navigation in our application. Tommy did say that the swiping controls in Voice Over worked very well once the menu was open. We used a typical MasterDetailPage with a ListView in the master side of the hamburger. One thing Tommy did say was when the menu opened, it did not announce itself, which could be a problem. A blind person might not know if the menu opened without the announcement.

I am currently contemplating whether we should replace the hamburger menu with a spring board menu in the next version. We originally went with the hamburger because we didn’t have enough features in the app to fill a spring board. If we continue to find accessibility issues with the MasterDetail, I’ll replace it.

Tommy Verdict:

Accessibility Score: 75

Information Display

cir-hierarchyInformation is displayed in the application through a combination of lists and labels. Tommy found no issues with either of those. Voice Over on iOS had no problems and Android’s Talk Back did well also.

Information hierarchy was the big thing that helped in this category. Most of the app is laid out much like a good webpage with headers and blocks of information. This is where a simpler interface is more usable than something with a lot of nested view. It might look basic to us, but for a visually impaired user, it’s usable.

Tommy Verdict:

Accessibility Score: 90


cir-locationOne of the surprising features that did well was the Xamarin.Forms maps. We used maps in our Xamarin.Forms application for finding locations on campus as well as getting student’s to class. The students schedule comes with date and time as well as a map with the location of where on campus they can find the classroom building.

Watching Tommy using Voice Over in the application was an educational experience. Seeing how you swipe from right to left to have the street spoken to you was amazing. I can only imaging how a visually impaired user would navigate the real world with the map. Tommy told me the community loves maps on mobile phones.

Tommy Verdict:

Accessibility Score: 85


Our accessibility expert is just that, an expert, who has been testing web apps for accessibility for years but there is one issue. He’s not visually impaired and that’s a problem. We can simulate the use of the application but we will never know until a visually impaired user picks up our app and starts using it.

Is Xamarin.Forms accessible? Yes, I think it is. Or should I say it doesn’t do anything to impede the use of Voice Over on iOS and Talk Back on Android. This is the first of many audits this app will be put through. Every change in the app will be put through the same audit as we evolve the app.

The post Xamarin.Forms and Accessibility appeared first on Syntax is my UI.

June 23, 2015 9:00 GMT

Android M Preview Now Available

Today, we’re excited to announce the preview release of Xamarin.Android featuring support for Android M’s developer preview. Android M is an exciting release, that introduces several new features for Android developers including new app Permissions, Fingerprint Authorization, enhanced Notifications, Voice Interactions, and Direct Sharing.

Android M

Installing the Android M Preview

  • Starting with Android Lollipop, Java JDK 1.7 is required to properly compile apps. You can download one for your system from Oracle’s website.
  • Update your Android SDK Tools to 24.3.3 from the Android SDK Manager
  • Install the latest Android SDK Platform and Platform and Build-tools


  • Download the Android M (API 22, MNC preview) SDKs
  • mnc-preview-packages

Getting Started

With this preview installed, you should have the new APIs available to use in your Xamarin.Android apps. Check out our release notes, download links, and more details on our Introduction to Android M documentation to guide you through setup and the new APIs.

The post Android M Preview Now Available appeared first on Xamarin Blog.

June 23, 2015 6:03 GMT

Live Webinar: Why Mobile Quality Matters

This live webinar will cover how to create a successful and sustainable mobile development strategy that enables quick delivery of great apps that work on across today’s diverse device landscape. Key to this process is a mobile quality solution like Xamarin Test Cloud that identifies bugs, visually compares results from hundreds of devices at once, increases delivery agility and velocity by eliminating manual testing, and integrates with your Continuous Integration (CI) systems.

The webinar will cover the different approaches and advantages to mobile testing, from manual testing, device remoting, and simulators to fully automated testing with real devices and how to create quality consumer-grade mobile apps.

Wednesday, July 08
8:30 AM – 9:30 AM PT


All of the registrants for the webinar will receive a copy of the recording, so please feel free to register even if you won’t be able attend the day of the event.

The post Live Webinar: Why Mobile Quality Matters appeared first on Xamarin Blog.

June 22, 2015 4:24 GMT

Extending Xamarin.Forms Controls with Custom Renderers

Xamarin.Forms allows you to build native UIs from a single, shared codebase with over 40 pages, layouts, and mix-and-match controls. One of the most powerful aspects of Xamarin.Forms is that you not only have access to the controls that we surface, but you have 100% access to all of the native APIs on each platform as well.

Moments Sign Up Page

Accessing Native APIs in Shared Code

Accessing native APIs using Xamarin.Forms is done in one of three ways: the dependency service, custom renderers or through plugins for Xamarin. The dependency service in Xamarin.Forms allows shared code to easily resolve interfaces to platform-specific implementations, so you can easily access platform-specific features like text-to-speech, geo-location, and battery information from your PCL or Shared Project.

User interfaces built with Xamarin.Forms look and feel native because they are native — they’re rendered using the native controls for each platform. For example, if you use an Entry control in Xamarin.Forms, on iOS this will be rendered as a UITextField, on Android as an EditText, and on Windows Phone as a TextBox. Developers can easily tap into these native renderings of Xamarin.Forms controls by using custom renderers, which can be used to do everything from small tweaks of the existing control or building entire pages.

Implementing a Custom Renderer

In Moments, a Snapchat clone built with Xamarin.Forms and Microsoft Azure, I made extensive use of the built-in Xamarin.Forms controls. However, there were a few places I wanted a finer level of customization. Let’s look at how easy it is to tweak the Entry control’s placeholder font and color using custom renderers in the sign up page featured above. Each custom renderer has two main parts: a subclass of the control being extended and platform-specific implementations that are used to customize a control’s appearance.

Subclassing Existing Controls

In the Shared Project or PCL where your Xamarin.Forms user interface logic resides, create a subclass of the control that you wish to extend, as seen below:

public class MomentsEntry : Entry
    public MomentsEntry ()
        TextColor = Color.White;

Platform-Specific Implementation
To customize the control’s appearance, we must create custom renderers on each platform for which we wish to customize the given control. Each Xamarin.Forms control has a renderer class that can be subclassed on each platform, such as EntryRenderer.

public class MomentsEntryRenderer : EntryRenderer

Next, override the OnElementChanged method. This method is where all the customization for the control takes place. All customization is done using the Control property, which is just an instance of the native mapping for the particular renderer subclassed. For example, on iOS, this would be a UITextField and on Android an EditText. Altering the placeholder color and font was as easy as altering a few properties, as seen below in both the iOS and Android implementations:


public class MomentsEntryRenderer : EntryRenderer
    protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
        base.OnElementChanged (e);
        if (Control != null)
            Control.BackgroundColor = UIColor.FromRGB (119, 171, 233);
            Control.BorderStyle = UITextBorderStyle.None;
            Control.Font = UIFont.FromName ("HelveticaNeue-Thin", 20);
            Control.SetValueForKeyPath (UIColor.White, new NSString ("_placeholderLabel.textColor"));
            Control.Layer.SublayerTransform = CATransform3D.MakeTranslation (10, 0, 0);


public class MomentsEntry : EntryRenderer
    protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
	    base.OnElementChanged (e);
	    if (Control != null)
	        Control.SetHintTextColor (ColorStateList.ValueOf  (global::Android.Graphics.Color.White));
	        Control.SetBackgroundDrawable (null);

Finally, to enable Xamarin.Forms to properly find and render your custom control, you must add the [assembly] attribute above the class. The first parameter references the Xamarin.Forms control you wish to alter the renderer for, while the second parameter references the platform-specific renderer for the custom control:

[assembly: ExportRenderer (typeof (Moments.MomentsEntry), typeof (Moments.iOS.MomentsEntryRenderer))]

The Results

Before and after custom renderer

Wrapping It All Up

Custom renderers in Xamarin.Forms make it easy to extend existing Xamarin.Forms controls, create your own controls, or even build entire pages using native APIs. To get started, be sure to check out the docs or watch this video from Xamarin’s Mark Smith, and you’ll be up and running with custom renderers in no time!

The post Extending Xamarin.Forms Controls with Custom Renderers appeared first on Xamarin Blog.

June 20, 2015 7:59 GMT

Xamarin.Forms Carousel View Recipe

I often see people on the Xamarin.Forms forums asking for a carousel-style control. We have the CarouselPage built in, but you can't resize the viewport or easily indicate which page you are viewing. I believe the official documentation even mentions that this control is mainly intended for Windows Mobile.

Thankfully, the power of Xamarin.Forms allows us to build our own.

Thanks to my friends at Firefly Logic and to Michael Watson for inspiring techniques that helped me create this custom control recipe.

The control is similar in functionality to the Xamarin.Forms CarouselPage - except the "pages" can be any type of content.

I have examples that show the CarouselView used as:

  • A full-page control with no page indicators (like CarouselPage)
  • A gallery-style control with dots as page indicators
  • A full-page control with tabs as page indicators

Carousel View

Let's take a look at the different components.


Probably the most important piece is the custom Xamarin.Forms control. There's a lot to look at, but I'll try to talk about the important bits.

The control itself inherits from ScrollView. We set the orientation to Horizontal and set the Content to a horizontal StackLayout. This should immediately tell you that the content will display horizontally allowing you to scroll to the parts not on screen.

We manage "pages" of data by creating a bindable IList property as our ItemsSource. Anytime we update the ItemsSource, we add our page items as children of the StackLayout.

We're close!

We should be able to load pages of data and scroll through the pages. What's lacking is that snap into place that we expect when swiping through pages of content. For that, we'll add a Renderer for each of our platforms.

Renderers: Snap Into Place

Our Xamarin.Forms control derives from the ScrollView which means that the native views at work are the Android.Widget.HorizontalScrollView and UIKit.UIScrollView. Each of these controls provide native methods for programatically scrolling to a given position.

The secret sauce in having our custom control pages snap into place is by doing a little math, then telling our native ScrollView controls to scroll to a position based on that math.

There are some other things at work, but I'll skip to the interesting parts:



Pretty neat, right? We'll finish by pulling this together with page indicators.

Page Indicators

This is the interesting part, and the part missing from some other controls. The page indicators are just a horizontal StackLayout grouping of child elements -- one child element per page. My example shows a few different options:

  • None: No page indicators. This behaves like the CarouselPage control.
  • Dots: The page indicators appear as tiny dots. It is common to see this style of page indicators on gallery-style carousel layouts.
  • Tabs: The page indicators appear as a tab bar with icons (and for iOS, text).

The dots are simply Buttons. As the ItemsSource changes, so does the number of dots.

The tabs are a bit more involved. As the ItemsSource changes, we clear all of the existing tabs, and make sure to draw new ones. Each tab is itself a StackLayout. If on iOS, you will get the icon and tab text. If on Android, you will only see the icon. These are typical patterns, but the code is customizable and can be configured in whichever way makes most sense for your application. Also, my example has hardcoded icon and text values, but these are easily configurable.

Putting It Together On Screen

This example has some conditional logic to handle the different page indicator styles, but generally I'm laying out the screen using a RelativeLayout.

You can make this as simple or complex as you need. If you look at the layout for Dots, I overlay the dots page indicator onto the carousel view content. This is a common pattern with gallery-style carousels.

This post is already TL;DR, and a lot of the details were left out. Hopefully, if nothing else, this recipe introduced some new and interesting ways to approach laying out your content.

To see the entire project with multiple examples, visit the GitHub repo.

June 19, 2015 5:45 GMT

Newest Content from our Community

When Xamarin developers aren’t building amazing iOS and Android apps in C#, they’re helping out fellow Xamarin developers with engaging blog posts and articles, creating open-source projects, and building cross-platform plugins or components. The links below will take you to some of our favorite content from our community over the past few weeks.


Prism for Xamarin.Forms

Prism for Xamarin.Forms with Brian Lagunas

Great Community Posts

Jesse Liberty: Lists in Xamarin Watch

Lists on the Apple Watch

Azure Offline Editing and Syncing

Azure Offline Editing and Syncing

Tools and Frameworks


Thanks to these developers for sharing their Xamarin knowledge with the rest of the developer community. If you have an article or blog post related to Xamarin development that you would like to share, please let us know by tweeting @XamarinHQ, and it may be featured in an upcoming community content roundup.

The post Newest Content from our Community appeared first on Xamarin Blog.

June 19, 2015 1:07 GMT

Weekly Xamarin Newsletter Issue #45

Want to try Xamarin University? Now you can!
Bryan Costanich, from Xamarin Inc., announced the new Xamarin University trial offer.

UI Design with Xamarin.Forms Lecture
I (Adam) was invited to give a lecture at Xamarin University. It’s going to be on Xamarin.Forms and design. Big surprise right!

Who Turned Off the Lights? Azure Offline Editing and Syncing
Matthew Soucoup, from Code Mill Technologies, goes deep into Azure and syncing.

Xamarin.Forms Layouts: StackLayout
Paulo Ortins, after a bit of a break, is back. This time with a post on StackLayout.

Expand Your App’s Reach with Google’s App Invites
James Montemagno, from Xamarin Inc., is at it again. This time with App invites.

Xamarin.Forms in Anger – Findr
I (Adam) show off my love of sandwiches with Maps and Xamarin.Forms.

Automated UI Testing and Monitoring for Your Mobile Apps
Greg Shackles puts up his slides from the NYC Mobile .NET Developers Group.

Gone Mobile 26: Prism for Xamarin.Forms with Brian Lagunas
Greg Shackles and Jon Dick have Brian Lagunas on the podcast to talk about Prism.

Forums Updates: Badges and More!
Jayme Singleton, from Xamarin Inc., announces some additions and improvements in the forums.

Xamarin.Forms InputTransparent Nugget
I (Adam) get all touchy feely about Xamarin.Forms.

Linker experiences with Xamarin.iOS
Sergio Escalada solves a big headache with the help of the linker.

Xamarin.Forms Image Caching in XAML
James Montemagno, from Xamarin Inc., shows off some Xaml for image caching.

Xamarin Podcast: WWDC and Google I/O 2015
Pierce Boggan, from Xamarin Inc., fires off another Xamarin podcast.

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

June 18, 2015 2:02 GMT

Want to try Xamarin University? Now you can!

Try Xamarin University for Free

Xamarin University has grown rapidly since its introduction in 2014 and today, we’re excited to announce a brand new way for you to experience Xamarin University for free.

With our new trial offer, you’ll see why over 2,500 students have enrolled in Xamarin University. Take advantage of Lightning Lectures, Guest Lectures, and two full classes from our Certification track, which you’ll be able to attend live as well as access on-demand:

    Xamarin University Orientation: Get help configuring your development environment, as well as how to get the most out of Xamarin University, and how to become a Xamarin Certified Developer.
    Intro to Xamarin.Forms: Build a first app using Xamarin.Forms. This class is designed to get you up and running on Xamarin with a 100% shared code native application that runs natively on iOS, Android, and Windows.

With almost 60 classes offered across 8 learning tracks, we have something to offer to developers across the spectrum. From those getting started in C# or making the switch to mobile, all the way to experienced developers ready to add Xamarin Certification to their resumes, Xamarin University offers everything you need to stay up-to-date in today’s constantly evolving mobile landscape.

Xamarin Certified Mobile Developer status can only be attained through Xamarin University, and after your trial, your completion of Xamarin University Orientation and Intro to Xamarin.Forms can be counted towards the full Xamarin Certification track.

Your 30-day free trial is ready — get started today!

Start Your Trial

The post Want to try Xamarin University? Now you can! appeared first on Xamarin Blog.

June 18, 2015 12:00 GMT

UI Design with Xamarin.Forms Lecture

The good folks over at Xamarin University have asked me to give a guest lecture to the students of Xamarin University. My topic, of course, will deal with Xamarin.Forms and design. No surprises there. Don’t worry, this talk is for developers by a developer. Black turtlenecks and tattoos are optional.

The Abstract

“Learn how to design and develop beautiful and modern cross-platform mobile user interfaces with Xamarin.Forms and a graphics editor.”

This lecture will be on October 6th at 8AM PST.  The talk will last for about an hour and we will have a question and answer section at the end. If you’re a Xamarin University member, I hope you’ll be there. If you are not a member, what are you waiting for? Xamarin University is worth it. Where do you think I learned about Xamarin.Forms?

I’ll let you know when you can register for the event. I hope to see you there. Adam

The post UI Design with Xamarin.Forms Lecture appeared first on Syntax is my UI.

June 17, 2015 9:55 GMT

Expand Your App’s Reach with Google’s App Invites

There were some major announcements at Google I/O 2015, but there were also several exciting enhancements to Google Play Services announced that focus on increasing your app’s reach in the market. app-invites-logoOne of my favorite new features in Google Play Services has to be App Invites, which gives developers a simple way of allowing their users to share their app with friends through e-mail or SMS. App Invites also provides a way for developers to add deep link content in these invitations, enabling a unique way of bubbling up information, such as discount codes or exclusive content, to new users when your app is installed.

How App Invites Work

Traditional app discovery is usually done by browsing a large list of apps or searching for a specific keyword, but App Invites enables apps to be shared user-to-user. When people share an app invite from a mobile app, it kicks off the App Invite flow. Google Play Services handles what happens if an app is installed or not, and provides a deep link for adding additional context. Here’s what a normal flow looks like:


App Invites are currently in beta on both iOS and Android from Google.

Getting Started

For this blog post, I’ll focus on Android development (Xamarin.iOS support is coming soon). App Invites are packaged as part of Google Play Services 7.5, which are currently available as a pre-release NuGet Package. Simply search for “AppInvite” in the NuGet Package Manager in either Visual Studio or Xamarin Studio with the pre-release packages flag enabled.


The next step is to enable Google Services for your Android app. Google has a nice wizard to help you create or choose an existing app to enable services for on the Google Developer Console.

Enter your app name and Android package name:


Check App Invites and then add your Android Signing Certificate SHA-1 information. To find your SHA-1 Fingerprint, simply follow our documentation. If you’ve used Google Maps in the past, this is the same process.

Enable App Invites

After this step in the process, you may be prompted to download and copy a configuration file, however, this is not necessary for Xamarin.Android apps at this time.

Sending App Invites

I’ve decided to integrate App Invites into my app Coffee Filter, which enables you to find coffee shops based on your geolocation. Coffee Filter has a master-detail view setup, and I chose to allow users to send app invites from the coffee shops detail page, which enables me to deep link to the coffee shop in this example.

When you want to trigger the App Invite, you will need to start by creating a new Intent using the AppInviteInvitation.IntentBuilder class. The only required field is the title that is displayed to the user on the invite, but you may want to also provide a message to display and a deep link URL that you can use when receiving the app invite.

int RequestInvite = 0;
void SendInvite()
  var intent = new AppInviteInvitation.IntentBuilder("Invite Friends to Coffee")
	           .SetMessage("Join me for coffee with Coffee Filter")
	           .SetDeepLink(Android.Net.Uri.Parse("http://motzcod.es/" + viewModel.Place.PlaceId))
  StartActivityForResult(intent, RequestInvite);
//Get information back from the App Invites request
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
  base.OnActivityResult (requestCode, resultCode, data);
  if (requestCode == RequestInvite)
    if (resultCode == Result.Ok)
      //Check how many invitations were sent. You could optionally track this data as
      //the Ids will be consistent when you receive them
      var ids = AppInviteInvitation.GetInvitationIds((int)resultCode, data);
      ShowMessage("You just sent " + ids.Length + " invites!");
      // Sending failed or it was canceled, show failure message to the user
      ShowMessage("No coffee invites were sent.");

As you can see, I’m deep linking to a specific coffee shop ID that I can use later when receiving the deep link. For your app, you should determine what type of deep link information you want, if any. With just this code, your users will now have the ability to send app invites out:

Nexus 4 (Lollipop) Screentshot 1

This will send out an e-mail with your app on a card view, enabling a one-click install of your app:
App Card

Receiving App Invites

When a user receives and accepts an app invite, the app may or may not be installed. This means you will need to handle each instance separately. If the app is already installed, you can simply handle and process the app invite in your Main Activities OnCreate method, with just a few lines of code:

protected override void OnCreate(Bundle bundle)
  // No savedInstanceState, so it is the first launch of this activity
  if (bundle == null && AppInviteReferral.HasReferral(Intent))
    // In this case the referral data is in the intent launching the MainActivity,
    // which means this user already had the app installed.
// Process the deep link information, however if you don't have any deep links
// this may be a good time to welcome them to the application
public void LaunchDeepLinkActivity(Intent intent)
  var newIntent = new Intent (intent);
  newIntent.SetClass (this, typeof(DetailsActivity));

If the user doesn’t have the app installed, they will install it and then the Google Play Store will send a broadcast out notifying your app to process the deep link. You will need to create a ReferrerReceiver that will handle this broadcast:

[BroadcastReceiver(Exported = true)]
[IntentFilter(new []{"com.android.vending.INSTALL_REFERRER"})]
public class ReferrerReceiver : BroadcastReceiver
  public override void OnReceive (Context context, Intent intent)
    // Create deep link intent with correct action and add play store referral information
    var actionIntent = new Intent(context.GetString(Resource.String.action_deep_link))
    var deepLinkIntent = AppInviteReferral.AddPlayStoreReferrerToIntent(intent, actionIntent);
    // Let any listeners know about the change

Inside of your MainActivity, you will need to register a new local broadcast receiver that will receive this broadcast and launch the deep link activity.

class InviteBroadcastReceiver : BroadcastReceiver
  readonly MainActivity activity;
  public InviteBroadcastReceiver(MainActivity activity)
    this.activity = activity;
  public override void OnReceive (Context context, Intent intent)
    if (!AppInviteReferral.HasReferral (intent))
    activity.LaunchDeepLinkActivity (intent);

You should register and unregister this broadcast receiver in the OnStart and OnStop methods of your activity.

InviteBroadcastReceiver deepLinkReceiver;
void RegisterDeepLinkReceiver()
  // Create local Broadcast receiver that starts
  //DeepLinkActivity when a deep link is found
  deepLinkReceiver = new InviteBroadcastReceiver(this);
  var intentFilter = new IntentFilter(GetString(Resource.String.action_deep_link));
  LocalBroadcastManager.GetInstance(this).RegisterReceiver(deepLinkReceiver, intentFilter);
void UnregisterDeepLinkReceiver()
  if (deepLinkReceiver == null)
protected override void OnStart ()
  base.OnStart ();
  RegisterDeepLinkReceiver ();
protected override void OnStop ()
  base.OnStop ();
  UnregisterDeepLinkReceiver ();

Finally, when your deep link activity starts, you’ll want to process the incoming intent to see if you need to handle the deep link action. In my app, I parse out the place ID that we sent earlier and refresh the data.

protected override void OnStart ()
  base.OnStart ();
  ProcessReferralIntent (Intent);
void ProcessReferralIntent(Intent intent)
  if (!AppInviteReferral.HasReferral (intent))
  var invitationId = AppInviteReferral.GetInvitationId (intent);
  var deepLink = AppInviteReferral.GetDeepLink (intent);
  var info = deepLink.Replace ("http://motzcod.es/", string.Empty);
  viewModel.Place.PlaceId = info;
  RefreshData ();

Now, when the app is launched it will go directly to the deep linked coffee shop:

Nexus 4 (Lollipop) Screentshot 3

Learn More

To learn more about App Invites, including tracking invitations, be sure to see the Google App Invites documentation. Additionally, you can find the entire source code for Coffee Filter with App Invites on my GitHub.

Discuss this post in the Xamarin Forums

The post Expand Your App’s Reach with Google’s App Invites appeared first on Xamarin Blog.

June 17, 2015 12:00 GMT

Xamarin.Forms in Anger – Findr

My favorite food in the whole world is a sandwich. No I’m not talking about a PB&J with the crusts cut off. I’m talking about a hero; yea, you know a submarine, a grinder, a hogie, or po’boy if you live in the bayou. They call them by many names; I call them delicious. For this Xamarin.Forms in Anger post I decided to dedicate it to finding my favorite food and if that wasn’t enough, I thought that circle maps are sexy.

Xamarin.Forms Findr

This UI sample uses the same image technique I used in “Hot Sauce,” except this time I used a perfectly round cutout in the overlay image. The cutout is really just a section of the image with an opacity of 0, making it see through.


To be honest, I think circle maps are sexy but not exactly user friendly. I like to use my whole screen and the clipped corners could be an issue on smaller device sizes.

The Blueprint

In the blueprint, you can see it’s just a RelativeLayout with layers for the overlay image and the map for the top and some StackLayouts for the bottom. The one tricky bit is setting the overlay images InputTransparent setting to true. That way touches on the clear overlay image will be registered on the map below. Tricky, I know!


The Code

The code is pretty simple. One thing to notice is how I calculated the width and the height of the circle and the map. They both have to be the same size or your going to have some issues with the map sticking out the sides of you’re overlay image. For this UI, I used the width of the device for the width and the height of the map and the overlay image. The UI looks pretty good, even on different size devices.

public FindrMapPage ()
	Title = "Find a Shop";
	BackgroundColor = Color.White;

	var lense = new Image () {
		Source = new FileImageSource () { File = "maplense.png" },
		Aspect = Aspect.AspectFit,
		IsOpaque = true,
		InputTransparent = true

	var map = new Map(
			new Position(33.509242, -112.035860), Distance.FromMiles(0.3))) {
		IsShowingUser = true,

	var pin = new Pin {
		Type = PinType.Place,
		Position = new Position(33.509242, -112.035860),
		Label = "Potbelly Sandwitch Shop",
		Address = "2131 E. Camelback Rd.  Phoenix, AZ"

	var stack = new StackLayout () {
		Padding = new Thickness(10),
		Children = {
			new Label () {
				FontAttributes = FontAttributes.Bold,
				Text = "Delivery Zone:",
				TextColor = Color.FromHex("852F29"),
			new Label () {
				Text = "North to E Lincoln Dr, South to E Osborn Rd, East to 40th Street, West to Central Ave ",
				FontSize = 14,

			new Label () {
				FontAttributes = FontAttributes.Bold,
				Text = "Delivery Available:",
				TextColor = Color.FromHex("852F29"),
			new Label () {
				Text = "Mon. - Fri. 11:00 AM to 2:00 PM",
				FontSize = 14

	var orderonline = new StackLayout () {
		BackgroundColor = Color.FromHex("E6A93D"),
		Children = {
			new Label() { 
				Text = "Order Online",
				FontSize = 22,
				FontAttributes = FontAttributes.Bold,
				TextColor = Color.White,
				HorizontalOptions = LayoutOptions.Center,
				VerticalOptions = LayoutOptions.CenterAndExpand

	RelativeLayout relativeLayout = new RelativeLayout () {
		HeightRequest = 100,

	relativeLayout.Children.Add (
		Constraint.Constant (0),
		Constraint.Constant (0),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;

	relativeLayout.Children.Add (
		Constraint.Constant (0),
		Constraint.Constant (0),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;

	relativeLayout.Children.Add (
		Constraint.Constant (0),
		Constraint.RelativeToParent ((parent) => {
			return parent.Width - 10;
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		Constraint.RelativeToParent ((parent) => {
			return parent.Height - (parent.Width + 50);

	relativeLayout.Children.Add (
		Constraint.Constant (0),
		Constraint.RelativeToParent ((parent) => {
			return parent.Height - 50;
		Constraint.RelativeToParent ((parent) => {
			return parent.Width;
		Constraint.RelativeToParent ((parent) => {
			return 50;

	this.Content = relativeLayout;

You can find the code for this sample in the Xamarin.Forms in Anger GitHub repo. Why don’t you download the code and try it out for yourself. For this sample, I just added the code for iPhone since adding the Android maps stuff is just a pain.

Xamarin.Forms in Anger Series

Can Xamarin.Forms produce good looking cross-platform UI from a single codebase? Each “In Anger” blog post will tackle a single page of a beautifully designed iOS or Android application. My job will be to reproduce the design in Xamarin.Forms as faithfully as possible. InAnger-Strip-7

The post Xamarin.Forms in Anger – Findr appeared first on Syntax is my UI.

June 17, 2015 1:50 GMT

Automated UI Testing and Monitoring for Your Mobile Apps

I gave a talk tonight at the NYC Mobile .NET Developers Group on automated UI testing and monitoring for apps. For anyone interested, here are my slides:

I don't have any specific sample code available from this talk since all of my demos were entirely live coded, but if you're looking to get started then Xamarin's documentation is a great place to start, or I'm happy to try and answer any specific questions anyone might have as well.

June 16, 2015 1:30 GMT

Episode 26: Prism for Xamarin.Forms with Brian Lagunas

Prism has been around for awhile, and now you can take advantage of it in your Xamarin.Forms apps! In this episode we dig into what Prism is, why you’d want to use it in your mobile apps, and how it fits into Xamarin.Forms apps.

Hosts: Greg Shackles, Jon Dick

Guest: Brian Lagunas


Thanks to our Sponsors!


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

June 16, 2015 10:39 GMT

Who Turned Off the Lights? Azure Offline Editing and Syncing

We spent the last post cloud gazing and exploring the Azure Mobile Services API as it relates to creating and retrieving data from a Xamarin mobile app. But we were limited to accessing our data only when connected to the internet.

What happens when the skies turn dark, a storm rolls in and we lose internet connectivity? Or, in our case with the Cheesed app we are developing, our users are deep in a cheese cave sampling a rare 20 year cheddar and their mobile device cannot reach the internet?

Do we just display an error message saying, “stop eating cheese … no internet, try again later”? And not let them enter a rating or any notes on the complexities of the cheese?

That’s not acceptable! How can we expect somebody to use an app, but only when they are online? Lucky for us, Azure Mobile Services provides offline capabilities! So let’s dig in and see what it’s all about.

Benefits of Working Offline

Being able to edit data anytime is only one benefit that the offline capabilities that Azure Mobile Services gives us.

Other benefits include:

  • Resiliency against network outages (we’ll have a data cache that will always be there).
  • Improves the (perceived) performance of the app – if we design it right, we can have the data already downloaded and onboard the device before the user needs it.
  • Detect conflicts when the same record modified on more than one device and then sync’d/pushed to the cloud.

We’ll talk about how to handle conflicts in the next post – but for now let’s dig into how to make our app offline capable using the Azure Mobile Services library.

Basic Setup


Just about everything we need to implement offline capability is included in the same NuGet package we used in the last post, WindowsAzure.MobileServices.

Install-Package WindowsAzure.MobileServices

BUT… the one thing that isn’t included in that package is the offline repository or database itself. The package above contains everything we need to do push and pull from the cloud, but does not contain an implementation of how to store the data on the device in between.

Luckily, we don’t have to roll our own repository as Microsoft has provided one for us, and it’s based on SQLite (man – that SQLite just keeps popping up every where on mobile devices, doesn’t it?).

It’s named

and it gives us a way to store and edit data locally before we push it to the cloud.

To install, run the following NuGet command.

Install-Package WindowsAzure.MobileServices.SQLiteStore

Of course, if we wanted to implement our own local storage we could, but for the purposes of this post, we’re going with Microsoft’s.

Modeling Data

Modeling data to be included in offline editing is no different than discussed in the previous post on modeling data for Azure. We just use POCO classes, matching the class and property names to the table and column names in Azure.

Or we can use the

to map class and property names to table and column names respectively. See the last post for an in-depth discussion.

How It Works

The basics of offline data editing with Azure are as follows:

  • All data CRUD operations takes place against a local SQLite database.
  • Data only sent to the cloud when “pushed”.
  • Data for a specific table retrieved from the cloud when “pulled”. A pull will always automatically initiate a “push” first.

The Push Process

Push Process

Pushing data to Azure means taking local changes and applying them to Azure. Regardless if we’re online or not, all of the edits to the data occur against a local SQLite database. When we’re ready to “push” to the cloud, only the data that has changed gets pushed. It should be noted that data across all tables will be pushed to Azure (for data consistency), not just data from a single table.

The Pull Process

When we talk about “pulling” data, we mean grabbing data from Azure and bringing it local to the device. The first thing that must happen before we can grab the data from Azure is that we must push any changes we have locally up to the cloud. That means any pull operation automatically invokes a push. This is to keep data in Azure consistent. After data is pushed, then the data we’re requesting is pulled. Note that it’s only data for a single table (and most likely filtered at that) – not all the data in all the tables in Azure.

Pull Process

Working With Offline Data

Basic Initialization

There is some basic boilerplate code that we’ll have to invoke once in an application in order make it work with Azure Mobile Services and also to get the Mobile Services’ SQLite Store to work:

Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init ();

SQLitePCL.CurrentPlatform.Init ();

This only needs to be called once in each of your platform specific projects. AppDelegate.cs and MainActivity.cs seem like a good spot to me.

Define Local Storage

Let’s now talk about how we setup Azure Mobile Services to use a local datastore. It’s actually pretty straightforward.

First we create a new

object and pass it the filename of our database. Then we invoke the
function. This is very much akin to the
function in SQLite.Net that we talked about in a previous post. Finally, we register our offline data store with the
. The code will look like the following:

var store = new MobileServiceSQLiteStore ("cheeses.db3");

// Do this for every table we want to keep track of locally                 
store.DefineTable<Cheese> ();
store.DefineTable<Dairy> ();

await mobileClient.SyncContext.InitializeAsync (store);

Note that we must call the

function before invoking the
function. It’s that function which actually creates the tables in the SQLite database, so we need to have them defined first.
can accept a second parameter … and this second will help us handle conflicts – which we’ll talk about in the next post.

Setting Up the Sync Tables

Just like in the previous post on working with Azure directly, we still need to have the

create the table objects that we’re going to work with in order to both persist data locally, and to push and pull it from the cloud.

Instead of invoking

as before, we’ll use
, as the example below illustrates, building from declaring the local store through creating the sync tables:

// Define the local data store
var store = new MobileServiceSQLiteStore ("cheeses.db3");
store.DefineTable<Cheese> ();
store.DefineTable<Dairy> ();

await mobileClient.SyncContext.InitializeAsync (store);

// Creating the sync tables
var cheeseTable = mobileClient.GetSyncTable<Cheese> ();
var dairyTable = mobileClient.GetSyncTable<Dairy> ();

All of the CRUD operations now will happen against these sync tables – which implement the

interface. We can pull (and implicitly push) data from these tables as well. And we can also use the
to push data as well.

Writing Data

Again, the most important thing to realize is that all writes happen against the local SQLite database. Nothing goes to Azure until we specifically tell it to. That’s the whole point of having offline editing capabilities, right? To allow our users to make any changes they want, whenever they want, no matter their connection status.

are all defined on the
interface. This means that working with the sync tables defined above is the same, and as easy, as before. Nothing special is going on, we’re just modifying the local data store.

As mentioned before, the

has a
function on it. This function will take all of the pending changes in the local data store and push them up to Azure.

To add on to the example from above – this time writing data and pushing to Azure:

var store = new MobileServiceSQLiteStore ("cheeses.db3");
store.DefineTable<Cheese> ();
store.DefineTable<Dairy> ();

await mobileClient.SyncContext.InitializeAsync (store);

var cheeseTable = mobileClient.GetSyncTable<Cheese> ();
var dairyTable = mobileClient.GetSyncTable<Dairy> ();

var hooksDairy = new Dairy { 
    DairyName = "Hooks"

var cheddarCheese = new Cheese {
    CheeseName = "20 Year Cheddar",
    CheeseType = "Cheddar",
    Dairy = "Hooks",
    Rating = 5,
    ReviewDate = DateTime.Now
// Writing data locally
await dairyTable.InsertAsync(hooksDairy);
await cheeseTable.InsertAsync (cheddarCheese);

// Push both data changes
await mobileClient.SyncContext.PushAsync();

The sync tables also have a

function. First this does the exact same thing as the PushAsync function of the MobileServiceClient.SyncContext. Then it issues a query to pull back data related to the table. So it pushes all the data that has been modified since the last push across all the tables, but only pulls back data from a single table.

A couple of notes about pulling data …

If soft deletes have been enabled on the server, then pulling data will delete any records locally which have been marked as a soft delete on the server. If soft deletes are not enabled, the deleted records will stay in local storage, even if they have been deleted from the server, so a call to the sync table’s

function will be necessary from time to time to clean everything up. And of course,
will first push any local modifications before it actually does the purge on the table.

Finally – if a record has multiple transactions against it locally – it was inserted, then updated multiple times – only the final state of the record will be transmitted to Azure on a push. It will not be pushed multiple times. This happens automatically and is nice to save our users some bandwidth.

Reading Data

Obviously when pulling down data from Azure, we do not want to pull all the data from the table. Azure Mobile Services give us some pretty nice functionality to make sure we don’t pull down a ton of data each time, blowing away our users data cap.

Within the

function, there is a string parameter named “queryId” … by supplying a value for this, the Mobile Service client will keep track of the last time that queryId was issued and then only pull down data changed in Azure since then. It uses the
metadata column that Azure automatically puts onto every table.

Mobile Services also lets us pass in either a string query, or a

object to further refine the results of the data coming back. For example, to only get the finest cheeses we’ve sampled, the following can be invoked:

await cheeseTable.PullAsync ("deliciousCheese", cheeseTable.Where (ct => ct.Rating > 4));

Again, every time this statement is issued, it will first push all the modified data across every table, but then only bring back cheeses rated “5 wedges” and up since the last time we pulled.

If we just want to query data locally, and not pull it down from Azure, we would do so against the IMobileServiceSyncTable itself, without invoking PullAsync first. The following example illustrates grabbing the best cheeses stored locally:

var justGreatCheese = await cheeseTable.Where(ct => ct.Rating > 4).ToListAsync();

Design Considerations

When designing and developing a mobile app for offline data access, one of the most important things to do is figure out when it makes sense to push data to Azure. Ideally we’d like to bundle logical transactions as best we can – for example, if we have a screen in our app where we create both a cheese and numerous tasting notes for that cheese – and those are stored in different tables – it only makes sense to send all the changes at once.

We want to be sure we keep the data in Azure as logically consistent and complete as we possibly can. Not send bits and pieces up which would impact other users if they issue a pull before all of our logical data is in place.


In this post we took a look at the benefits of offline data editing and how to implement it using Microsoft Azure Mobile Service’s SQLite Data Store. We learned that modeling data is as simple as POCO objects, that pushing data moves all modified data to the cloud, and pulling data first pushes modifies data to the cloud before it retrieves it. Finally we went through and built up and example of creating the data store, initializing the synchronization context with the mobile service client, and then pushing and pulling data with it.

Next time we’ll look at what happens with conflicts and maybe… just maybe… unveil a functioning Cheesed app!

Featured Image: “100 Wisconsin Avenue, night, Madison, WI” by John Benson from Madison WI – 100 Wisconsin AvenueUploaded by xnatedawgx. Licensed under CC BY 2.0 via Wikimedia Commons –

June 15, 2015 9:55 GMT

The best of WWDC*

Disclaimer: I didn't go to WWDC, so chances are, this isn't the best of WWDC. That would be the people you - person who went to WWDC - met in the hallways, at the parties/cafe's/bars/backstreets/local Blue Bottle Coffee. But I can comment on the content and the external view. So I'm going to.

First of all, either grab a nice auto-download script, or get the fantastic WWDC iPad/iPhone app. Personally, I got the app, as I've been watching the videos on my horrible1 commute. Aside from one feature request (skip 30 seconds), it works great.

On to the sessions. This isn't an exhaustive list, just some of the ones I enjoyed2 enough of to make it worth mentioning. There is a full list here - I'm not sure if you need a dev account (which is free now!) or not.


However, the two real winning presentations for me where Mysteries of Autolayout part 1 and part 2. So much useful stuff in there.


So far, I've only watched What's new in Swift, which has some good insights into the language design. But on my "still to watch" list is:

I think that Apple have finally got Swift to 1.0 with the 2.0 release. It's definitely time to learn it, and it appears it might be stable enough to use in production.

I still think Swift is a Frankenstien's monster of different language ideas mashed together, compared to something like C#, Java or even Objective-C, but it's where Apple is going, so time to jump onboard.

Oh and Objective-C got generics. Awesome. I guess.


For me at the moment, this is the single most interesting thing Apple is doing right now. iCloud before it was a mess, as no one at Apple was using it. However, CloudKit is being used in a LOT of mainstream Apple products (mail, dialer, contacts, notes, photos amongst others), so it's going to get a lot of love internally. And I even have a project to use it on, which is a nice change for me.

  • What's new in CloudKit have a good overview
  • CloudKit JS and Web Services covers a lot of the new REST-based stuff. The only aspect I wanted to know, that they didn't cover, is if their JS library works out of the browser, eg in a NodeJS app. They did cover the fact that once the user had authenticated, you can pass the session token back to the server to do more processing, but not if (or not) you have to write the REST wrappers yourself. I'm hoping not. The API - mostly promise based - looks sweet too.

Security and Privacy

  • Security and your Apps covers the new security stuff off, including App Transport Security.
  • Privacy and your Apps covers the privacy side, including a huge middle finger to Twitter using url schemes to scrape what apps are installed on your device.

There is plenty of other good sessions, if you are into games, or animation, of web stuff, or... pretty much anything Apple. Finding the time to watch them all is the hard part. Thanks, Apple, for putting them all up so damn quickly (next morning, usually, if not that night). Made it feel a little like I was there, even if I was on the other side of the world.

  1. Really, not horrible.

  2. I don't care about Safari changes or OSX changes, only, pretty much, iOS. I don't care much about watchOS either, tho it's going to be HUGE. So it's skewed that way. Also, game stuff doesn't interest me much.

June 15, 2015 12:00 GMT

Xamarin.Forms InputTransparent Nugget

In my recent post Xamarin.Forms in Anger – Mall Dash, I made a dashboard or springboard for my main navigation. Each one of the widgets in the board is made up of a RelativeLayout, 2 Images and a Label. When trying to get the sample to actually work, I ran into a wee bit of a snag. Which of the components should respond to the tap gesture? Should I add Tapped Gestures to all the components of the widget?

Widget Assembly


Each of the Images and the Label could be tapped on by the user and I didn’t want to add tapped gestures to each object. But the user could tap on anything in the widget. If I just added the tap gesture to only one of the components, taps that missed the component would do nothing. No doubt, frustrating the user.

Xamarin.Forms InputTransparent

InputTransparent is a boolean property on the VisualElement class. The property allows visual elements like Labels and Images to participate in the user interaction cycle or just pass the events up the visual tree. Neat!

Now that we can optionally participate in the interaction cycle, let’s look at the effects of turning it off. Starting with each element having InputTransparent set to true. True is the default.

Turning it OffXamarin.Forms InputTransparent

  1. All widget components have their InputTransparent property set to True.
  2. Icon image is now set to False touches will be passed up the chain to its parent the RelativeLayout.
  3. Both the icon Image and the Label will not react to tapped events but the background Image will.
  4. The Label and the 2 Images will not react to the touch events. Only the RelativeLayout will respond to touch gestures.

After setting all the components to InputTransparent to False, any touches on the widget will result in the RelativeLayout receiving all touch events. Adding a single tapped event gesture to the RelativeLayout was all that I needed. So much cleaner.

InputTransparent is important when making layered user interfaces that interact with the user. Allowing us to turn off each element makes things much simpler. I would hate to have to added tapped gestures to each component in the widget UI. With InputTransparent = False we don’t have to.

The post Xamarin.Forms InputTransparent Nugget appeared first on Syntax is my UI.

June 14, 2015 12:14 GMT

June meetup - Design & Develop

“Read. Read. Read. Just don't read one type of book. Read different books by various authors so that you develop different style.” ― R.L. Stine

It's June and we, the XHackers are back with a new meetup. We always believe in technical diversity and our meetups also reflect the same. We pick different themes to make you feel as if you are reading a different book every time you join us for a meetup.

To prove our point,In this meetup, we will be talking about technologies and tools which will help a mobile developer in developing cross platform mobile apps using Xamarin and IBM MobileFirst platform. Also we will be touching upon Android design concepts through material design and Android M preview updates.
Material Design

Let's jump into the schedule

9:30 AM to 10AM - Registration

10 AM to 10:30 AM - IBM keynote by Rajesh K Jeyapaul, Solution Architect-Ecosystem Development

10:30 AM to 11:20 AM - Getting started with Xamarin and Xamarin.Forms by Senthil Kumar, Microsoft MVP

11:20 AM to 11:30 AM - Break

11:30 AM to 12:20 PM - Integrating IBM MobileFirst Platform to your Xamarin Apps by Ajay Chebbi, Software Architect/Sr. Engineer - IBM MobileFirst Platform.

12:20 PM to 1:10 PM - Material Design & Android M Updates by Vidyasagar Machupalli, Microsoft MVP

1:10 PM and to 1:30 PM - Q&A/ Networking with Xamarin Experts Nish Anil and Anubhav Ranjan

To be part of this exciting learning,


See you there!

Xhackers Core Team

June 13, 2015 3:39 GMT

Xamarin.Forms Image Caching in XAML

A lot of mobile applications have to deal with Images. There are a lot of awesome libraries for iOS and Android that will automatically download, optimize, and cache your images for you from a single line or two of code. Xamarin.Forms actually handles all of this for you automatically when you give the Image’s Source property an Image URL. You can read through the awesome documentation on the Xamarin developer portal. If you browse through this documentation you will see a section that says “Image Caching” and that is interesting. Xamarin.Forms actually handles image caching for you automatically for 1 day. You can enable or disable or extend this time easily in C#:

However, something that isn’t documentated just yet, although I will ping Craig about this, is how to do it in XAML. It is actually extremely simple as you can access all the properties of the Source including the ability to extend image caching. Here is what my image looks like with extending the image cache to 14 days:

Are you using Circle Images? Well you can still do it!

You can always adjust the CacheValidity=“14” as it just creates a new timespan in days for you.

June 13, 2015 12:11 GMT

WWDC2015 – The BIG takeaways


Ah, WWDC 2015 what a wild ride, 5 days of content packed sessions.  While I’m still trying to comprehend everything I’ve learned over the past 5 days there’s some big takeaways that I’ve got from WWDC this year.

Native apps still dominate!

Why? Did you know that on iOS 86% of time is spent in apps?

One thing that’s really apparent is that Apple is obsessed with user engagement, experience and performance, and they believe apps are key to this. To get an understanding let’s take a look at some of the new features which Native Apps/APIs can help you engage with your users like never before, some updated in iOS 9 and some brand new in iOS 9.

Apple Watch - Apple is betting big on the Watch, putting the watchOS 2 on level pair with OSX and iOS. WatchOS 2 comes with a set of API allowing developers to build even better Native Apps and they also added to this is the ability to be on a users Watch face. For my details see my blog post on watchOS 2.

Screen Shot 2015-06-12 at 3.20.20 pm

Notifications - Apple Watch now supports long form notifications and actionable notifications.

Screen Shot 2015-06-12 at 3.12.00 pm

Search APIs - Apps are now allowed to interface with search in iOS 9, with the ability to deep link into the app. If you want to know more you can view my blog on Search APIs.

Below is an example in which a person has booked a holiday to Maui, from AirBnB and Kayak.


App Extensions  - While not new in iOS9, still a very powerful engagement feature, apps can display widgets in the Today view of Notification Center, providing quick updates or enabling brief tasks — for example, posting updates on package deliveries, the latest surf reports, or breaking news stories.

Screen Shot 2015-06-12 at 4.26.32 pm

Apple will continue pushing people to apps

Apple have shown they will keep pushing users into apps, this is clear with Universal links and Apps now appearing in iOS Search and Safari search.

Apple will continue pushing people to upgrade iOS

Apple has promised developers that they will continue pushing users to upgrade their OS version, specifically users now will only need 1.3 GB of free space to upgrade to iOS9. Apple have also enabled notifications that will prompt users to upgrade their iOS version. Their recommendation is that developers will only need to target the two most recent OS versions.

Swift all the things

During the 5 days of the conference I didn’t see a line of objective-c (thankfully). There was an enormous amount of content on swift and some the sessions on swift were outstanding. Apple is betting big on Swift and with Apple behind Swift it’s going to be a language that’s around for the next 20 years.

watchOS is serious

As mentioned before, with 10+ session on watchOS Apple is betting big on the watch.

Stop thinking about Orientation

With iOS9 Multitasking we need to stop thinking about designs in orientation, we need to be thinking about Size. If you want to read more about multi-tasking you can this blog on iOS9 Multitasking.

Xamarin.Forms is still awesome

After full week living in the Apple future I’m still very confident in Xamarin.Forms and it’s future, the flexibility of Xamarin and Xamarin.Forms allows me (us) to still take advantage of all these new Native APIs but in a cross-platform way. In the next day I’m going to be blogging a Xamarin.Forms app that supports the Multitasking features in iOS9.


WWDC has been mind blowing, on par with TechEd Europe which I attended a few years back. I’ve learnt alot, made some good friends and I recommend all mobile developers attend at least once.



The post WWDC2015 – The BIG takeaways appeared first on Michael Ridland.

June 12, 2015 6:51 GMT

Load a Collada File in Scene Kit

My friend @lobrien (whose blog you should read if you don’t already) was asking about loading Collada files in Scene Kit, so I whipped up a quick example:

In the Xamarin Studio solution pad, the folder containing the Collada file has a .scnassets suffix, and the model has a build action of SceneKitAsset:

solution pad

Given this, the model is rendered as shown below:


There’s also a Collada build action as well. I’ve never used that option though. If someone wants to elaborate on what that does (perhaps supporting animations embedded in Collada files? just a guess) please add a comment here.

June 12, 2015 1:15 GMT

Weekly Xamarin Newsletter Issue #44

Keep Users from Leaving Your App with Chrome Custom Tabs
Jon Dick, from Xamarin Inc., tells us about delivering a branded experience and the power of Chrome.

Lambda Expressions, Weak Subscriptions, and MvvmCross…Oh My!
Greg Shackles digs deep into the mysteries of data-binding in MVVMCross.

Xamarin.Forms Nuggets – A Sweet and Sour Blog Series
I (Adam) kick off another blog series of bite size Xamarin.Forms goodness.

Introduction to iOS9 Multitasking and Xamarin.Forms first-thoughts
Michael Ridland gives you his thoughts straight from the WWDC conference.

Crafting 5 Star iOS Experiences with Transitions
Mike James, from Xamarin Inc., add some sizzle to his iOS with transitions.

Xamarin.Forms Button Nugget
I (Adam) realize just how much I don’t know about Xamarin.Forms.

Better Apps & Faster Release Cycles

Karl Krukow, from Xamarin Inc., helps you deliver better quality apps faster.

Paket Support in Xamarin Studio
Matt Ward introduces Xamarin Studios support for Packet.

What’s New in Prism for Xamarin.Forms 5.7.0-Pre1 Release
Brian Lagunas gives us an update to the Prism project.

An Exercise for the Reader
I (Adam) finish off the Xamarin.Forms springboard and ease some frustrations.

Building the Swiper control – Part 2 (Android)
Johan Karlsson gives you part 2 of his swiper control for Xamarin.Forms.

Put Some Cyanogen in Your Xamarin Apps
Jon Dick, from Xamarin Inc., talks about the enhanced Android distribution.

Lists in Xamarin Watch
Jesse Liberty gets some lists running on the new Apple Watch.

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

June 11, 2015 12:00 GMT

An Exercise for the Reader

Mall DashIn my latest Xamarin.Forms in Anger post, I made a dashboard or springboard for my main navigation of a future shopping mall app. The dashboard page uses a Grid with widgets in each cell. Each widget is a ContentView with a RelativeLayout, two Images and a Label describing the shopping category. Tapping on the widget should navigate you to a page where you can look through a list of shops in the selected category.


What I didn’t do for the sample code was hook everything up. I kind of left that as an exercise for the reader. Well, that might not have been the best idea! One reader was getting a little frustrated trying to tie together the tapped event on the widget back to the dashboard page so that he could, you know, navigate around the app. So to avoid anymore frustration it was time to put fingers to keyboard and finish it.


I am happy to tell you that I have finished off the dashboard navigation in the sample. When the dashboard adds each widget to its Grid, it also registers for the custom Tapped event on each widget. When the widget is tapped, an event is fired that sends a WidgetTappedEventArgs back to the subscribers. The dashboard page then navigates to the requested page.

Take a look at the Xamarin.Forms in Anger GitHub repo and try out the Mall Dash sample for yourself. I’m happy with the way it turned out; but remember, it’s not the only way you can do it.

The post An Exercise for the Reader appeared first on Syntax is my UI.

June 11, 2015 1:42 GMT

Lambda Expressions, Weak Subscriptions, and MvvmCross...Oh My!

Earlier this week we found ourselves looking into a strange databinding problem, where things were working as expected on devices but not in the simulator. Differences between simulators and devices is certainly not uncommon, but I'm not sure I can recall a time where it was on the device that things were binding correctly, and the simulator that was showing problems. The usual suspect of being a linker issue was off the table, so we had to dig a little deeper.

My suspicions then turned to differences in build configurations between the two - the garbage collector, debugging symbols, profiling support, etc - but no amount of option toggling smoked anything out there either. The strangest part? If we built in Visual Studio and deployed to the simulator, things worked. If we built with Xamarin Studio...no dice. Harumph.

At this point I was pretty confident it would end up being a garbage collection issue of some sort, and found that the binding was set up like this in a view model:

public void Init()  
    // ...other stuff...

        () => option.Quantifiable.Quantity, 
        (sender, args) => RaisePropertyChanged(() => Caption)));

If you've used MvvmCross before, you're probably familiar with the WeakSubscribe() method, which can be great for subscribing to property changes on a model without creating strong references to it. In fact, if you've used this method before there's a good chance you already see the problem (or this post's title gave it away...it's ok, I'll give you the benefit of the doubt). The second argument to WeakSubscribe is the event handler to use for the subscription, which in this case was a lambda expression that goes out of scope after Init() finishes running.

Let's take a look at how weak subscriptions work in MvvmCross to see why this is important. When you call WeakSubscribe you're given a MvxWeakEventSubscription in return. When this subscription object is created, it creates its own event handler using OnSourceEvent which will get called each time the source property is updated.

The implementation of this method is the key here:

    protected void OnSourceEvent(object sender, TEventArgs e)
        var target = _targetReference.Target;
        if (target != null)
            _eventHandlerMethodInfo.Invoke(target, new[] {sender, e});

If the target is null, which is the event handler we supplied for this subscription, it removes the event handler and moves on. This is what was happening in our code...the lambda was going out of scope, and the next time the binding tried to update it would notice that and drop the handler, resulting in the property changes not bubbling up to our UI. The solution in this case was simple - use an actual method as the event callback:

public void Init()  
    // ...other stuff...

        () => option.Quantifiable.Quantity, 

private OnQuantityChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)  
    RaisePropertyChanged(() => Caption);

Once that was updated things worked as expected. It's also worth noting that it's worth holding on to the subscription you get back from calls to WeakSubscribe so that you can manage and dispose of them as appropriate for your applications. That was left out of this example for the sake of brevity.

This isn't rocket science, but I wanted to post it as a reminder that it's important to think about what's going on under the hood with this sort of thing and not get caught up the simplicity of a nice API. Lambda expressions are awesome and make code much more readable, but do come with a cost at times.

June 11, 2015 1:26 GMT

iOS 9 Search API – A killer way to engage with users

Note: I’m currently at WWDC watching the live sessions, I haven’t been able to include all session details and only the public information, as more information becomes public I will post more details.

Did you know that in iOS 86% of time is spent in apps?

Apps are now allowed to integrate with the search in iOS9, this is a bit of a killer feature for iOS 9, not only for app developers but also for users.

Imagine the scenario where you’ve booked a hotel room from an app, you want to find some details about the hotel room at a later time, with search API you can put in a query directly in the iOS search bar and details of that booking can appear and deep link you into your app.

Below is an example in which a person has booked a holiday to Maui, from AirBnB and Kayak.


As developers we can choose exactly what to index with a lightweight API. As a added bonus the results also appear in the safari search, still including the deep linking into the apps which is awesome. You can also tag content as public, meaning very popular public content will also appear in the search result.

There’s three API for supporting iOS 9 search:
NSUserActivity – Which is previously viewed app content
CoreSpotlight – Which you can add any app content
Web Markup – App content which is also supported on the web


Was introduced in iOS 8 but is now indexed and searchable, it works with iOS Search and Safari search and this allows the user to revisit that activity.

In a NSUserActivity you can select many options via the metadata, like if it’s eligible for handoff, if it’s eligible for search and public indexing.

Some of the fields you can handle on this include title, userInfo, keywords, contentAttributeSet, expirationDate, webpageURL, eligibleForSearch, becomeCurrent and thumbnailData.

In order to support returning to your app you need to support the method continueUserActivity.

If you want the Activity to work on the web then you can set – eligibleForPublicIndexing, but this data remains anonymous (via a hash) until the activity is popular enough too appear in the results.

This is also how you can support SIRI smart reminders and Handoff e.g.. ‘remind me about this”


CoreSpotlight allows you to index any part of your application, you can take a list of data from your backend and index all the items in the list using the CSSearchableIndex and CSSearchableItem. You can add a bunch of attribute data using CSSearchableItemAttributeSet like title, description, thumbnail and data.

In order to handle this deep linking you only need to handle Appdelegate.continueUserActivity.

It’s up to you/your app to manage the indexed content you have you can update a Item by using the same ID and calling indexSearchableItem and if you want to delete you can use deleteSearchableItem.

This is a basic overview but generally it is this simple.


This is a App Deeplink, so it will be a simple URL (a real URL, like www.apple.com/product/iphone) that goes to a website when on OS X but on IOS will Deep Link into your app.

There’s a few requirements for WebMarkup:

  • The website must contain the Markup for Deeplinks
  • It should match the support URL and marketing URL
  • Ensure your website has smart app banners

Universal Links are better then customURL schemes, as their Unique, Secure and Flexible.

Apple are also going to be supporting Twitter Cards and Facebook App Links. I’m sure more details on this will come soon, but overall it’s very cool.

Best Practices

Make sure you give the items that same ID, you don’t want to be duplicating any items.

Apple have put in a lot of work to protect relevance, spammers are downlinked and engagement ratios are tracked.

Some tips for indexing:

  • Use a description
  • Use a thumbnail
  • Provide the key information
  • Use keywords
  • Proactivityely index items

iOS search is flexible and limitless, it’s going to be very awesome for both User and Developers, I’m really looking forward to it.

If you have any questions please contact me on my website, I’m happy to answer any questions.




The post iOS 9 Search API – A killer way to engage with users appeared first on Michael Ridland.

June 10, 2015 10:27 GMT

Introduction to iOS9 Multitasking and Xamarin.Forms first-thoughts

Note: I’m currently at WWDC watching the live sessions, I haven’t been able to include all session details and only the public information, as more information becomes public I will post more details.

Split screens on iPad, ah scary, now we have even more things to worry about.

Just in case you haven’t heard about what multitasking is on the iOS9, it’s basically being able to run two apps side by side on an iPad. There’s three different modes, Slideover, SplitView and Picture-in-Picture.







One of the first things you need to understand about multitasking in general, the User is in control of the apps and the sizes of the apps. You can never set the size of a window.

We all now need to adopt a multitasking mindset, which means two things 1) avoid using device idiom or interface orientation and instead adapt to the window size 2) we need to ensure our apps are ‘good citizens’ and not leaking memory, growing in an unbounded fashion, or blocking the main thread

In regards to handling different sizes and layout, Adaptivity is the solution, if you’ve been using the features like AutoLayout and Size classes then supporting multitasking in your app should be easy. Apple aren’t afraid to say I told you so, ‘participating in iOS 9 multitasking is straightforward when you’ve adopted Apple’s best-practice recommendations for iOS 8.’

If you’re developing with Xamarin.iOS and you’ve been doing it with best practices then this should be a simple transition.

The basic steps to support multi-tasking in your app are:

1) Build your app with iOS 9 SDK
2) Support all orientations
3) Use launch storyboards

If you want to opt-out of multitasking then you can add the key ‘UIRequiresFullScreen’ in your plist, this is not recommended as user will expect that your apps support multitasking and their not going to be happy if they can’t use multitasking. Apple recommends Most apps should adopt Slide Over and Split View.

The simulator in xcode 7 will allow you to simulate the functionality so testing your app them should be fairly easy. Currently only the iPad Air 2 support the full SplitView, I would guess this is due to performance.

The biggest change is about resource management. Every iOS app—even one that opts out of using multitasking features—needs to operate as a good citizen in iOS 9. Now, even full-screen apps don’t have exclusive use of screen real estate, the CPU, memory, or other resources.

It’s important to note that we shouldn’t be using rotation events in iOS9, the events we should be using are similar to this (more details TBA).



Multitasking with Xamarin.Forms first thoughts

If you’re using Xamarin.Forms then there’s no direct support for autolayout or size classes but if you design your layouts to look good at all sizes then you should be ok. I’m feeling that in general multitasking won’t be an issue in Xamarin.Forms, even ‘as-is’ Xamarin.Forms we can use the current system to have adaptable screen sizes using the various Xamarin.Forms layouts like StackLayout, Grid and RelativeLayout. Additionally this is just a thought but possibly, the Xamarin.Forms team could add a Device.Size property which could help us make a decision on how to layout the main areas of the screen, possibly add even a event.

Here’s some initial thoughts on handling the new feature.

  • Avoid making layout decisions on Idoim(Tablet/Phone), use the window size
  • Avoid making layout decisions on device orientation
  • Avoid absolute layout
  • Use RelativeLayout, StackLayout and Grid to help with adaptable screen sizes
  • MasterDetail should already function correctly
  • It would be possible to add (polyfil) an event into Xamarin.Forms to notify when a Screen Size changes, allowing us to change the primary navigation style

One other thing to note is Xamarin.Forms has no concept of ‘readable content guide’, so if you want text content to be a good reading experience in your Xamarin.Forms applications then you’ll need to come up with a alternative solution.

If you have any questions about iOS9 multitasking or Xamarin.Forms feel free to get in touch as I’m always keen to help.






The post Introduction to iOS9 Multitasking and Xamarin.Forms first-thoughts appeared first on Michael Ridland.

June 09, 2015 8:22 GMT

Introducing WatchKit and watchOS 2

Watch development now has three new frameworks, WatchKit, ClockKit and Watch Connectivity.


As I mentioned before the WatchKit extension now runs on the watch but apart from the architectural changes the extension primarily stays the same. There’s a few implications on how you develop your WatchKit extension.

You must implement your extension using the watchOS SDK instead of the iOS SDK. If a API isn’t available in the watchOS then you’ll need to rely on your iPhone app to perform the task. It’s very surprising but the API available on the watch is very large, ClockKit, Contacts, CoreData, HomeKit, CoreGraphics, CoreLocation, CoreMotion, EventKit, HealthKit, Watch Connectivity.

Your extension now stores files and data on the Apple Watch, but any data that’s not a part of your Watch app or WatchKit extension bundle must be fetched from the network or companion iOS app running on the iPhone. You cannot rely on a shared group container to exchange files with your iOS app.

WatchKit now has support for Networking via the NSURLSession object, with full access to the NSURLSession capabilities include the ability to download files in the background. While I think this is very cool it also scares me how much this can be abused by app developers and dramatically reduce the battery life on the watch.

One more thing to note is that WatchKit extensions not longer have direct access to iCloud technologies.

ClockKit and Complications

A complication is a small UI element that displays custom information on the clock face of Apple Watch. Like your app’s glance, complications are a way to display your app’s most important information to the user quickly. Your complications can be displayed alongside system complications for displaying the current date, moon phases, sunrise times, user activity, and many other types of information.

There’s a few different methods to update complications in your apps, if you’re complication data is known from now and into the future then you can send all the data for the timelines up to the complication, this also allows your complication to support the Time Travel feature. Other options to update data include scheduled updates and certain types of push notifications.

All apps the support a complication must have a class that implements the CLKComplicationDataSource and all methods must be implemented, to register this in your app add the key CLKComplicationsPrincipalClass into your Info.plist.

ClockKit manages the life cycle of your complication, launching your extension at appropriate times, creating your data source object, and asking it for data. Complications run on an update cycle, which your able to configure via getNextRequestedUpdateDateWithHandler. You provide the ClockKit with data from the past, present and future data. It’s recommended to provide enough data for hours and not minutes, then if your data changes you can invalidate the data using CLKComplicationServer.

To display the UI for your complication you use a placeholder template, ClockKit only ask for your placeholder templates once after your app is installed on the device. It caches the data your provide and does not refresh unless your app is reinstalled or updated. Templates seem to support Images and Text must support the different shapes, ring, small and large.


The WatchConnectivity framework provide a two way communication between an iOS app and Watch app and basically we can use it to pass data back and forth between the phone and watch, live communication is possible when both apps are active otherwise data is sent in the background.

The new framework consists of just a few classes, WCSession, WCSessionFile, WCSessionFileTransfer, WCSessionUserInfoTransfer and finally the WCSessionDelegate.

The WCSession (and it’s delegate) is the primary facilitator of communication between the Watch and Phone. The WatchKit extension and the iOS app must configure their own session objects, activating the session opens a channel that allows each app to communicate with its counterpart.

When both apps are active you can send data directly using sendMessage otherwise you can send messages in the background using transferUserInfo or transferFile. All messages are delivered in the same order that they are sent.

The transferCurrentComplicationUserInfo on the WCSession allows iOS Apps to directly send data to the WatchApps and update the complication.

Custom Interfaces for Notifications

Yippee, Watch apps now have support for Actionable notifications introduced in iOS 8, which is a way to add buttons to your notification interface. This is something I’ve been waiting for as currently I find Notifications on the Watch aren’t amazingly useful. Apple Watch automatically adds the button to the notification, as developers we just need to handle the action the user selects.

Notifications have a short look that cannot be customised and the long look which can be customised. The long look also contains any action buttons that you support.


Apple has really thought about how developers can build awesome user experiences with the Apple Watch and they’ve opened up a lot more than I would have expected. Well it looks like us app developers have our work cut out, there’s a lot to learn about Watch development, and Apple is betting big on the Watch.

Current none of these APIs are supported by Xamarin and I’m sure it wouldn’t too far away, except they do have a bit of work cut out for them.


The post Introducing WatchKit and watchOS 2 appeared first on Michael Ridland.

June 09, 2015 6:00 GMT

Paket Support in Xamarin Studio

Xamarin Studio and MonoDevelop now have support for Paket with an alpha release of the Paket Addin.

Paket is a dependency manager for .NET. The dependencies it supports are NuGet packages, files from GitHub, Gists or files from any HTTP source. Paket can be used to maintain project dependencies completely from the command line.

So let us take a look at the support for Paket in Xamarin Studio and MonoDevelop.


  • View dependencies and referenced NuGet packages in the Solution window.
  • Add, remove, update NuGet packages from the Solution window.
  • Install, restore, simplify NuGet packages from the Solution window.
  • Check for updated NuGet packages from the Solution window.
  • Syntax highlighting for all paket files.
  • Code completion whilst editing the paket.dependencies file.
  • Integrates with Xamarin Studio’s unified search.
  • paket.dependencies and paket.template file templates.

Installing the addin

The addin is currently available from MonoDevelop’s Add-in Repository in the alpha channel. In Xamarin Studio open the Add-in Manager and select the Gallery tab. Click the repository drop down and if Xamarin Studio Add-in Repository (Alpha Channel) is not displayed then click Manage Repositories…. In the window that opens tick the check box next to Xamarin Studio Add-in Repository (Alpha Channel) and then click the Close button.

Enabling alpha channel addins

Back in the Add-in Manager dialog click the Refresh button to update the list of addins. Use the search text box in the top right hand corner of the dialog to search for the addin by typing in Paket.

Paket addin selected in Addin Manager dialog

Select the Paket addin and then click the Install… button.

Now let us take a look at adding a NuGet package to your project with Paket. This is a simple way to get started with Paket in Xamarin Studio without having to manually create any paket files.

Adding a NuGet Package

To add a NuGet package using Paket, right click the project in the Solution window, and select Add – Add NuGet Packages using Paket.

Add NuGet Package using Paket Solution window context menu

The Add NuGet Packages using Paket menu is also available from the main Project menu.

This opens the Add NuGet Packages dialog. Search for the NuGet package you want to use and click the Add Package button.

Add NuGet Packages dialog

The Status Bar will update as the NuGet package is installed.

Json.NET added status bar message

More detailed information about the installation can be found in the Paket Console window. This can be opened by clicking the Status Bar or from the View – Pads menu.

Json.NET added Paket Console messages

After the NuGet package has been installed successfully you will see two new items in the Solution window. A Paket Dependencies folder and a Paket References folder.

Paket folders in Solution window

These folders show the NuGet packages that are in the paket.dependencies and paket.references files.

Paket Dependencies Folder

The Paket Dependencies folder is shown in the Solution window if Xamarin Studio finds a paket.dependencies file in the same directory as the solution. The NuGet packages that are in the paket.dependencies file are shown under this folder.

Paket Dependencies folder in Solution window

Double clicking the folder will open the paket.dependencies file into the text editor. The Paket Dependencies folder also has a context menu where you can run Paket commands.

Paket Dependencies folder context menu

From the context menu you can Add a NuGet Package as a dependency, install, restore, update, and simplify your dependencies, or check for updates. When you select Check for Updates the updated NuGet package information will be shown in the Paket Console and in the Solution window.

Paket Dependencies folder NuGet package update information

To update a single NuGet package you can right click it and select Update. To remove the NuGet package as a dependency you can right click it and select Remove or press delete.

Paket Dependencies folder NuGet package context menu

Paket References Folder

The Paket References folder is shown in the Solution window if Xamarin Studio finds a paket.references file in the same directory as the project. The NuGet packages that are in the paket.references file are shown under this folder. Double clicking the folder will open the paket.references file into the text editor.

Paket References folder in Solution window

Right clicking the Paket References folder allows you to add a NuGet package to the project.

Paket References folder context menu

A NuGet package can be removed by right clicking it and selecting Remove or by pressing Delete.

Paket References folder NuGet package context menu

Code Completion

When editing the paket.dependencies file you will get code completion as you type. You can also bring up the code completion list by pressing Ctrl+Enter.

paket.dependencies file keyword completion

Keywords that have an associated value will also show code completion after a space is pressed or the first character is typed in.

paket.dependencies file keyword value completion

After the source keyword you will see a list of NuGet package sources that are defined in your NuGet.Config file.

paket.dependencies file NuGet source completion

After the nuget keyword you will see a list of NuGet packages.

paket.dependencies file NuGet package completion

This list of NuGet packages is currently taken from your local machine’s NuGet cache. Currently there is no support for asynchronously searching an online NuGet package source to get the list of NuGet packages.

Running Paket commands

Paket commands can be run from the Unified search. If you type in paket you will see some of the Paket commands.

Paket commands in unified search

The syntax for each command is the similar to what the paket.exe console application supports but the commands do not support all the parameters.

As you type more of the command the list of commands will be filtered. To run a command select it and then press the enter key. These commands directly run paket.exe and update the paket files and project files. The status of the current command is shown in the Status Bar and the output from paket.exe is shown in the Paket Console window.

Paket dependencies installed status bar message

Paket dependencies installed console message

The Paket Console window will automatically be displayed if there was an error running a command and an error message will be displayed in the Status Bar.

Paket error message in Status Bar

Paket console error message

Otherwise you can open the Paket Console by clicking the Status Bar.

Syntax highlighting

Syntax highlighting is available for all paket files – paket.dependencies, paket.references, paket.lock and paket.template.

paket.dependencies file syntax highlighting

paket.lock file syntax highlighting

This brings us to the end of the introduction to Paket support in Xamarin Studio.

June 09, 2015 8:44 GMT

Getting rid of "No -tsa or -tsacert is provided" when signing APKs

Since JDK 1.7u51 Oracle introduced some extra strictness to the jarsigner, which is fine. Although, a lot of you might have seen some warnings when Xamarin.Android signs your APK, something in the lines of:

No -tsa or -tsacert is provided and this jar is not time stamped. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (2xxx-xx-xx) or after any future revocation date.
I am using a property group like this in my csproj file, which defines where my keystore is and which passwords it has, for convenience:

I could not find any options to add parameters to the jarsigner command, but I did notice, that the alias always came in the end of the jarsigner command in the output window. So my small workaround is to simply prepend the alias with -tsa http://timestamp.digicert.com, which removes the warning (yay!)
So now the property group looks like:

Although, I have recently put up APK files on the Play Store without this hack to remove the warnings and they were accepted just fine. So I guess... do whatever you want ;)
June 09, 2015 2:04 GMT

WWDC n+1 – The Keynote + Platforms State of the Union

Considering WWDC is a developers conference the keynote seemed more like a advertisement for Apple Music than anything else. We got 30 minutes of Apple Music, 2 minutes of swift and no code.  The Platforms presentation was much more interesting and finally included some code.

Below I list my highlights as a Xamarin developer, I’m going to keep these blogs focused on the interesting parts for Xamarin developers.

Multitasking in iOS 9  

More specifically designed for iPad Multitasking allows you to view two apps in a Slide Over, Split View, and Picture in Picture. The most interesting part of this is the layout, if you’ve been using auto layout it’s possible that your app might work with this already but if you haven’t then you might have a bit of work on your hands. If you’re using Xamarin.Forms this might be even more of a problem, but we will see once we’ve spent some more time with the new feature, this seems like a good item for some R&D and a blog post.

Search APIs in iOS 9

Apps are now allowed to interface with search in iOS 9, with the ability to deep link into the app. The API is called CoreSpotlight and is not supported by Xamarin yet. If your building website, there’s also the ability to include webmarkup that will appear in users search results. More info in a future blog post.

New game development APIs

Advancements in SceneKit, SpriteKit, and Metal. New APIs including GameplayKit makes it simple to build better quality games that involve complex rules, states, and behaviors. Model I/O gives you powerful control over the rendering of physical object models with materials and realistic lighting. ReplayKit lets users easily record and share great game content.

App Thinning

With iOS 9, the App Store allows users to download apps that are specifically optimized for their device. This means apps will download, install and launch faster while taking up less storage space than before. Build support for slicing, on-demand resources, and bitcode, and give your users smaller, more convenient updates to your apps. At the moment I’m not sure how this will work but stay tuned and you’ll find out soon.

Swift 2.0 and Open Source

The next version of swift has been announced with advanced error-handling, availability checking, and lots of enhancements to syntax. In even bigger news Apple is planning to make swift open source sometime this year, I’m not sure exactly how this relates to Xamarin but it’s still good news for developers.

WatchKit for watchOS 2

Apple announced a updated watch operating named watch OS 2, giving developers a bunch of new APIs and functionality, such as programmatic access to the Digital Crown and animation APIs for more dynamic user interfaces. New APIs for playing audio, video and microphone. Access to the Taptic engine, you can add haptic feedback in your Apple Watch apps. Extensions now run Native on the watch and don’t require a round trip to the phone resulting in a faster and responsive watchapp, developers can also create iPhone not present apps and full networking with NSSession and can work when iPhone is out of range. WatchApps now have a larger API a little similar to the iOS API, but with the extras like Digital Crown, Tapic Engine etc.

watchOS 2 also includes many enhancements to other existing frameworks such as HealthKit, enabling access to the health sensors that access heart rate and health information in real-time. CoreMotion enhancements include the ability to use the accelerometer to create engaging experiences on Apple Watch. Notifications on the watch can now have custom buttons and actions directly from the notification.

ClockKit, Time Travel and Complications

Well we all wanted it but weren’t sure if we would get it, but WE DID. Apps can now have their own data/information on the watch clock face, this information can be live updated via few different methods. And with the new Time Travel feature in watchOS 2, users can turn the Digital Crown to go backward and forward in time to display information in Complications from that time. Users can even enable multiple versions of your app’s Complications on the same clock face to display a variety of information.

Free App Development + $99 for all platforms

It’s now Free for developers to develop apps for all platform and now it’s only $99 if you want a developer account. The developer account is required to distribute and has a range of other features like access to early versions.

OS Upgrade Improvements 

Apple noted the problem of ‘free-space’ that many faced when attempting to update to iOS 8, so now iOS 9 will only require 1.4 GB of freespace to update. Apple are committed to pushing users to upgrade their OS.

iOS 9 Improved Battery Life & Low Power Mode

iOS 9 has an extra hour of battery life over iOS 8. iOS 9 now comes with a low power mode which can increase battery life by 3 hours..

Universal Links

App developers are now able to have a single link that opens in safari on the desktop but deep link into a app on the iPhone.


It’s been a long day but I’m very excited about learning more about these new features. I’ve got many more blog posts to come so stay tuned.




The post WWDC n+1 – The Keynote + Platforms State of the Union appeared first on Michael Ridland.

June 08, 2015 7:59 GMT

Building the Swiper control - Part 2 (Android)

This is part two in a three-part series about the Swiper control. The first part can be read here, if you are new to custom control/renderers in Xamarin I suggest you read it first since I'll skip the parts that the renderers have in common.

Why didn't I just use the native controls?

I've been getting some comments about the iOS and Android implementation for this, stating that I could have done this a lot simpler by using the native controls (the ViewPager and the UICollectionView). This is perfectly true, but it wasn't the purpose why I created the control.

The reasons I choose to do it the way I did was

  • I originally planned to add custom graphic effects
  • I wanted to see if I could make it perfectly fluid on my own
Having that said, I might convert the control to use the ViewPager and the UICollectionView and create another experimental Swiper as separate control. I got lazy for the WP implementation of the renderer and used a Panorama. So I'm kind of in between the two ways to do this.

So what's the theory behind the Droid renderer?

I went even more back to basic this time. I decided to juggle pure bitmaps and override the Draw(...) method of the renderer. This means we are doing pure rendering on demand of the entire control. 

If we start from the top, you'll see that this time, the renderer inherits from ViewRenderer where View is the thin wrapper for an Android View which is the most basic building block for an Android GUI thingy. View itself inherits from java.lang.Object so it's pretty much bare metal from here on.

   public class SwiperRenderer : ViewRenderer<Swiper, View>

As with the iOS version we need to override a few methods to get going
  • OnElementChanged
  • OnElementPropertyChanged
  • Draw
  • OnTouchEvent


The first one being OnElementChanged which is called by Xamarin Forms when it's time to create a platform specific object. (I don't like to use the word Native since it implies that Xamarin isn't native). Anyhow, the method looks like this. It's way shorter than the iOS counter-part.

  protected override void OnElementChanged(ElementChangedEventArgs<Swiper> e)

       _rootView = new View(Context);

The first thing we do is call UpdateSizes that simple copies size data into local variables for easier lookup later on.

  private void UpdateSizes()
        if (this.Element == null)

        if (this.Width > 0 && this.Height > 0)
            _width = this.Width;
            _halfWidth = _width / 2;

            _height = this.Height;
            _halfHeight = _height / 2;

Then we create the platform specific control and set it as the "Native" control. Since this is Android we need to pass the context to every corner of our code. I'm pretty sure the Android team use that as the solution to everything in life, as long as we have a context... We're fine!

At this point we have a control that will do the rendering for us.


This method is a lookalike to the iOS counterpart and I should really look into sharing some more code here by abstracting the events that go on in the renderers. All renderers have an InitializeImages method for example. I could define an interface for all common stuff and create a platform agnostic controller... Well, I didn't so we're stuck with code duplication for the time being. I didn't include the whole method in the sample below, simply the first two as an example of what it looks like.

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == Swiper.SourceProperty.PropertyName)

            if (e.PropertyName == Swiper.WidthProperty.PropertyName || e.PropertyName == Swiper.HeightProperty.PropertyName)

            if (e.PropertyName == Swiper.SelectedIndexProperty.PropertyName)
                // TODO Check for index overrun
                if (this.Element.SelectedIndex > 0 &&
                    _currentImageUrl != this.Element.Source[this.Element.SelectedIndex])
                    _currentImageUrl = this.Element.Source[this.Element.SelectedIndex];

            // Code omitted (there's more in this method)

As with the iOS version, we listen for changes in properties and call the appropriate methods to handle this change. For example, if we change the source we need to reinitialize the images. If we change the width or height we need to update sizes. Those sizes are needed to render later on.

Async image downloading

I played around with a couple of different approaches to async image downloading. I ended up with the basic WebClient since it would be cool to have download progress if the images are large. Looking at the code now, I realize that it's not fully implemented yet. I registered an issue (#13) for this and hopefully I'll get something done. The downloading works but the showing the progress is not completed yet. We just draw a loading text.

We directly convert the downloaded bits into a Android Bitmap object.

      private async Task LoadWithProgress()
                var webClient = new WebClient();
                webClient.DownloadProgressChanged += webClient_DownloadProgressChanged;

                var bytes = await webClient.DownloadDataTaskAsync(new Uri(_url));
                _bitmap = await BitmapFactory.DecodeByteArrayAsync(bytes, 0, bytes.Length);

                if (Completed != null && _bitmap != null)
            catch (Exception ex)
                Log.Debug("SwipeRenderer", "Exception loading image '{0}' using WebClient", _url);

        void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            int i = 42;


The caching in the Android version is just as basic. We simply store a dictionary of string and AsyncImageLoader for now. It's the same with all three platforms and a common caching strategy is required here.

Tracking your fingers

Handling touch events is easy. Simply override the OnTouchEvent method and check what type of event is being raised. We can break down this method in three parts categorized by the action type.

  1. The user starts a touch and we get a MotionEventActions.Down. We store the start location of the X-axis of the touch position to keep for later reference.
  2. If the action is Move we calculate the offset value of the current finger position on the X-axis. Then we call Invalidate() to force a redraw of the control.
  3. When the user lets go of the image we need to check if the image has moved far enough to count as a image switch motion and in that case, what direction. If it's not a switch we still need to animate the images back into the original place.

 public override bool OnTouchEvent(MotionEvent e)
                case MotionEventActions.Down:
                    _swipeStartX = e.GetX();
                    return true;

                case MotionEventActions.Move:
                    _swipeCurrectXOffset = e.GetX() - _swipeStartX;
                    return true;

                case MotionEventActions.Up:
                    var index = this.Element.Source.IndexOf(_currentImageUrl);
                    if(Math.Abs(_swipeCurrectXOffset)>30) // TODO Add a variable for the trigger offset?
                        if(_swipeCurrectXOffset > 0 && index > 0)
                            // Left swipe
                        else if (_swipeCurrectXOffset < 0 && index < this.Element.Source.Count() -1)
                            // Right swipe
                    return true;


            return base.OnTouchEvent(e);

Animation of images

Each platform offers different kind of animation APIs. In this sample I've chosen to use the static ValueAnimator to animate a float value. We can take the AnimateLeft(...) method as an example. It's dead simple to use. Simply state the initial value and the end value in the ValueAnimator.OfFloat(...). Hook up events for Update (that fires every frame) and for AnimationEnd(that fires when the end result has been achieved).

For this specific function we continue to animate the current x-offset to the left and when we hit the end we set a new _currentImageUrl (that represents the center image) and reinitialize all images so the new images are displayed.

       private void AnimateLeft(int index)
            var animator = ValueAnimator.OfFloat(_swipeCurrectXOffset, this.Width);

            animator.Update += (object sender, ValueAnimator.AnimatorUpdateEventArgs args) =>
                _swipeCurrectXOffset = (float)args.Animation.AnimatedValue;
            animator.AnimationEnd += (object sender, EventArgs args) =>
                _swipeCurrectXOffset = 0f;
                _currentImageUrl = this.Element.Source[index - 1];


The method signature of Draw(...) looks like this.

    public override void Draw(Android.Graphics.Canvas canvas)

It passes in a single argument in the form of a Canvas object. This Canvas represents the drawable surface that we have access to. The Draw(...) method is called everytime Invalidate() is called else where in the code or when the operating system wants you to update.

The method is quite repetitive so I'll just take a sample out of it.

     // Clear the canvas
            canvas.DrawARGB(255, 255, 255, 255);

            if(_centerBitmap != null && _centerBitmap.Bitmap != null)
                var dest = CalculateCentrationRect(_centerBitmap.Bitmap);
                 canvas.DrawBitmap(_centerBitmap.Bitmap, dest.Left + _swipeCurrectXOffset, dest.Top, null);
            else if (_centerBitmap != null)
                DrawLoadingText(canvas, 0);

This is pretty much what's going on, but times three. One for each image. First we need to clear the frame from the previous stuff drawn onto it. We do that with the canvas.DrawARBG(...) call. This could easily be extended to take a background color or image instead.

Then for each image we either draw the image or draw a loading text if the image isn't downloaded yet.


You could have made this a lot simpler and perhaps I'll revisit this control and redo it. But as a learning experience it was quite fun. Feel free to steal any code! My code is your code!
June 08, 2015 7:00 GMT

My First App Published: ¡Buenos días!

Dedicado a Elisa, que siempre me ha empujado para que siguiera con ello, y no lo dejara. Gracias, mi amor. ¡Te quiero!

¡Buenos días! is the spanish translation for Good morning! What does this have in common with mobile apps or Xamarin?

Álvaro Reinoso (Aro) is a freelance artist who takes a picture of the reality around him every day (from monday to friday), and draws up to transform it into something very valuable. He shares it on Twitter every morning, accompanied by the hashtag #buenosdias, translated into multiple languages. I met Aro when I was going to work at workINcompany (a coworking space in Seville), and since then I have always had the idea of making an app that takes his work to each mobile device.

Why saying good morning is a good idea? (Only available in spanish, sorry; but drawings are self-explanatory)

I had some meetings with Aro, sketching what we both would like the app to do. Everything said, it was much more further what the app does actually. However, as I learned do not remember where about MVPs (not Microsoft/Xamarin ones hehe, but Minimum Viable Products), it is important to focus on that functionality which holds the reason why the app should exist. I liked reading on Coffee Filter, from James Montemagno and Frank Krueger, because I feel in the roots the same concerning bringing ideas to apps.

The app ¡Buenos días! just does that: shows the last image, created that same morning. I have tried to display it with the same affection with which Aro creates it, and also make it super simple to share. I really enjoyed working on it. I guess it comes from the times when I was a child, and was everyday with LEGO blocks, dreaming with inventing new stuff.

Xamarin is for me with 30 years old what LEGO was with 10. I have made it using my beloved Xamarin.Forms, with a little bit of XAML, querying Aro’s Twitter account through LINQ to Twitter. Some plugins have made my life easier too. Initially, the idea was to share the source code on my GitHub account, and write a post here, but I did not feel comfortable with that: this app should be available to anyone, with ease:

Buenos días

Finally, I would like to thank my parents, neighborhood friends and workmates at Plain Concepts, which have played around with it those days, specially: Javier Fernández, thank you guy for sharing that crash trace; David Ávila, he made me think about the animations which happen on the app, thank you dude. Both sent me even some features which would be cool to have. Written down.

June 08, 2015 4:00 GMT

CyanogenMod for your Xamarin apps

CyanogenMod is an aftermarket Android firmware which keeps growing in popularity. With the first release of their platform SDK, it’s now possible to harness the power of the Quick Settings pulldown menu in your own apps running on CyanogenMod.

Quick Settings Custom Tiles are a great way to add an easy, global way for your users to do things like toggle a feature of your app on and off.

Adding a Quick Settings Custom Tile to your Xamarin.Android app is easy now with the new CyanogenMod SDK Component on the Xamarin Component Store.

After you’ve added the component to your project, you can use the CustomTile.Builder to build your tile:

var customTile = new CustomTile.Builder (this)
              .SetOnClickIntent (pendingIntent)
              .SetContentDescription ("Monkey Toggler")
              .SetLabel ("Monkeys " + States.Off)
              .SetIcon (Resource.Drawable.ic_launcher)
              .Build ();

Once you’ve created your custom tile, you can publish it with the CMStatusBarManager:

CMStatusBarManager.GetInstance (this).PublishTile (CustomTileId, customTile);

The CustomTileId is a unique ID associated with your tile. When you publish a new tile with the same ID, it will update the existing tile under that identifier. This makes it possible to change the appearance based on the current state of your app.

Don’t worry if your app isn’t running on CyanogenMod, in that case the SDK gracefully fails. You won’t see any exceptions, but rather, no Custom Tiles will be published on platforms which do not support it. You can feel safe in adding this feature to your app!

This is the first and only feature that CyanogenMod has released in its Platform SDK. I’m excited to see what new features they add in the near future! Go grab the component today and give your CyanogenMod users a greater user experience!

June 07, 2015 9:00 GMT

NuGet Support in Xamarin Studio 5.9.2


  • NuGet 2.8.5 support
  • NuGet warning and error messages in Status Bar

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

NuGet 2.8.5 support

Xamarin Studio now supports NuGet 2.8.5.

NuGet 2.8.5 adds support for three new .NET target frameworks: DNX, DNXCore and Core.

With NuGet 2.8.5 supported you can now install the latest pre-release version of xUnit.

NuGet warning and error messages in Status Bar.

Xamarin Studio 5.9 has a new native Status Bar on the Mac. This new Status Bar has a smaller width so the NuGet warning and error messages could be too long to be displayed. The screenshots below show a NuGet warning and error message in Xamarin Studio 5.9 that do not fit in the Status Bar.

NuGet warning message truncated in status bar

NuGet error message truncated in status bar

In Xamarin Studio 5.9.2 the NuGet Status Bar messages have been shortened so they can be displayed in the new Status Bar without being truncated. The screenshots below show the new format of the NuGet warning and error messages shown in the Status Bar.

Shortened NuGet warning message in status bar

Shortened NuGet error message in status bar

June 05, 2015 8:48 GMT

Lists in Xamarin Watch


There is documentation and a sample on Xamarin.com to show how to add lists to a Watch application, but it can be a bit confusing, so I created a very simple example that we can walk through line by line.

To get started, reate a new single page iOS application; let’s call it WatchRowsDemo

Fill in the program name, etc. And when the app is created, click on solution and choose Add New Project. In the New Project window click on Extension and WatchKit App.

Click your way through and once done you will have three projects:

  • WatchRowsDemo
  • WatchRowsDemoWatchKitApp  
  • WatchRowsDemoWatchKitExtension.  

It is important to keep these three straight:  WatchRowsDemo is the parent or main application.  WatchRowsDemoWatchKitApp is the UI for your watch application, while WatchRowsDemoWatchKitExtension is where the logic for you watch application resides.

A key concept to remember is

  • your UI (storyboards) go in …WatchKitApp 
  • your logic (controllers) go in …WatchKitExtension.

Your application is born with Interface.storyboard and InterfaceController.

Continued here

June 03, 2015 6:14 GMT

Introducing the iCircuit Gallery


TLDR; I wrote a website to share circuits made with my app iCircuit and I hope you’ll check it out.

Finally, a place to share

iCircuit users create amazing things. For the past 5 years of reading support emails, I have been privy to just a fraction of these wonders. Circuits far bigger than I ever thought iCircuit could handle - circuits that were clever and required me going back to my college texts to understand - and circuits that just made me laugh. I learned something from each of them.

It was a shame that all these wonders were hidden in my inbox. Well, no more.

Introducing, the iCircuit Gallery - a community driven web site full of circuits.

Now iCircuit users have a place to upload their and share circuits with the world. Each circuit is lovingly rendered in SVG and can contain rich textual descriptions of the circuit. Even if you’re not an iCircuit user, you can still learn a lot from the gallery.

I have seeded the site with the standard example circuits and Windows Phone users have (believe it or not) been able to upload circuits for years - so the site has some initial work in it already. But,

I am asking iCircuit users to share their designs - big or small - novel or standard - brilliant or otherwise. Share them with the world! There is great satisfaction to be had in sharing your work with others. I hope also to see educational examples pop up that take full advantage of the ability to document the circuit.

Simply click the Upload button, create an account (email optional), and pick the files off your device. Right now, that means Mac and Windows users have the easiest time with the gallery. I am working on iOS and Android updates to make uploading a snap there too.

I am very excited to see your designs!

Future Improvements

I have lots of ideas on how to improve upon this initial release but hope to get some feedback from the community before pursuing any of them. For example, I hope to add Tags to help organize things and Comments if contributors desire.

Also, I will be integrating the gallery into the app to make browsing and uploading easier. Keep your eye out for updates!


Oh my, I wrote a website! With servers and all that. Part of the reason it took me 5 years to write this thing is that I am scared to death of running servers. My ability to manage a server only gives it a life span of a few months before some hacker is using it as a spam bot.

So what’s changed? App hosting is what’s changed. I adored Google App Engine for it remedied the whole server problem - host apps instead of servers - genius! They provided a great database and a great toolset.

But it wasn’t .NET and I always wanted to run the iCircuit engine on the server.

And then Azure came along. Azure has a million enterprisy “solutions” and one awesome service called Mobile Services. But they their Cloud Service was the most confusing thing ever. It acted like an app host but also acted like a server. Which was it? So very confusing.

Well, Azure fixed that with a Web Apps service. Finally, after that little marketing spin and an assurance that I’m not managing a server, I became a customer.

Building the site was a snap with ASP.NET MVC. My only possible mistake is that I’m using Azure’s Table Storage - not sure how that decision will pan out. I foresee a future of migrating to SQL…

I am also scared to death about cloud pricing. Every page on the site has an HTTP and memory cache of 5 minutes. It’s ridiculously high. Almost as ridiculously high as my fear of cloud service pricing.

But there’s only one way to find out…

June 03, 2015 5:10 GMT

Living with the Apple Watch

The Watch In Detail

My buddy Seth thought it would be valuable to extend my series on the watch, with a more critical eye.  Essentially, what is good, what is bad, and what sucks.

I won’t try to convince you to  buy the Apple Watch; nothing it offers is so fantastic as to necessarily justify the price.  That said, if I lost mine I’d buy another the next day.

Clock Faces

The watch face is beautiful, with the clarity you’d expect from a Retina display.  The information you want can be customized as can colors, etc.

On the other hand,  independent programmers cannot (yet?) write custom clock faces.


Apple watch apps should, ideally, be extensions of existing apps, rather than stand alone.  A prime example of this is the weather app: want to know the temperature? Glance.  Want to know more details? Lightly tap to get the day’s forecast. Want all the details? A harder press will open the app on your iPhone.

I’ve had a hard time finding third-party apps that I care about.  Most don’t give enough information or they force you too quickly to open your phone,

On the other hand, the built-in apps work beautifully, and having Sound-Hound that, uh,  handy, is actually surprisingly useful.

Killer App?

While I can’t identify a universally agreed upon killer-app, I can tell you that the clock face I use has my next appointment displayed.  Touch it and I get the entire day, and then more touches let me see the month, etc.

This is phenomenally useful.

I also love that I can see what an alarm is for, and silence it from my wrist.

Surprisingly, the ability to answer phone calls and then hand off to the phone once you dig it out of your pocket, is terrific as well.


Siri is better and more convenient than ever.  Turn your wrist and say “Hey Siri” then ask your question.  Often you’ll get the answer, but annoyingly much of the time the answer is on your phone (which kind of defeats the purpose).

There is handoff to make that transition easier, but you still have to dig your phone out of your pocket.


Speaking of which, Handoff is much improved. To handoff from the watch to your phone is a snap.  Whatever app you are in appears as a small icon on the lock screen.  Flip that up and now you are on your phone

Looking at the time

Apple has done an almost magical job of allowing you to look at the watch and have the screen spring to life.. Unless you are lying down.  That said you can always touch the crown to bring up the face if all else fails.

There is no need to flick your wrist, just turn it to see the time and hey! Presto! It is there as it should be.

Flip Up, Down and Sideways

Notifications are easily found by pulling down from the top.  Apps are found by pulling up from the bottom.  Details by sliding right or left.  It takes some getting used to but it works well

If you are on the app screen (which also works surprisingly well) you can overcome the fat-finger problem by approximately centering the app you want and then turning the crown, which opens the app


Coming soon… Apple Watch vs. Pebble


June 03, 2015 11:44 GMT

Developing Your First Apple Watch App

Apple's new wearable is finally making it out to users, which means now is the time to start building apps for it! First, let's take a look at the different pieces that make up a watch app.

  • Watch App: While you might think that this is where most of your app logic will live, watch apps actually offload all real work to their parent apps. The watch app itself effectively contains just the user interface and not any of the code behind it.
  • Parent App: This is the normal iOS app you're already familiar with, and what users will download from the app store. Even if your app is meant to only target the Apple Watch you still need a parent app that lives on the user's iOS device.
  • Watch Extension: Similar to other extensions on iOS, a watch extension is used to connect the watch app with its parent app, and also contains the code that drives the watch app's user interface.

When defining your watch app's interface there are three interactions you can take advantage of:

  • Normal: the main UI that users can interact with when the app is active
  • Glances: a non-interactive view of the app that can give users important information quickly. Tapping on a glance will result in launching the full app
  • Notifications: Watch apps leverage the normal iOS notification system by default, but apps can choose to provide a custom interface to use for displaying notifications

Only the normal interaction mode is required for a watch app, but you can choose to add customized glances and notifications to help enhance your user experience as appropriate. In this article I'll focus on just the normal mode.

Read the full article over on Visual Studio Magazine.

June 03, 2015 4:08 GMT

Sharing War Stories: The Best Way To Swap Between Xamarin Studio & Visual Studio

Some of the best ways to become a better software developer, in general, is to listen to other people’s experiences and learn from them.  As a consultant, I’ve had the privilege of working with some of the brightest and talented software developers I have ever met.  I enjoy working with people who are smarter than me for two reason.  First, I learn how to approach problems in different ways I would have never have though of.  Second, I can take other peoples experience and retrospectives and add them to my tool belt of knowledge.

So I’ve decided to start a series on this blog, and this is the first post in that series.  I’m calling it “Sharing War Stories” and its intention is to take my experiences and share them with the rest of the community.  These stories are going to be things that can’t necessarily be found in official documentation.  It’s about solving certain issues or problems based on hands-on, real-world experience.  In short, the theme for this series is about how things are done in the field that you can’t find anywhere else.

So without further adieu, here is the first article in this series.

The Problem

In building Xamarin.iOS projects, the main problem is developing the user interfaces.  My preferred IDE (most of the time) for developing mobile apps is Visual Studio.  However, building user interfaces with Visual Studio has some limitations.  Here were my main problems.

First, the Storyboard Designer in Visual Studio, though powerful, still has some limitations (compared to XCode).  Bust most importantly, I don’t like to use Storyboards. :) That is another discussion/debate that deserves it’s own blog post.  But for the time being, let’s just say that Storyboards are not very cross-platform friendly.  And since I’m in the mobile cross-platform business, I’m going to stay away from Storyboards.  Instead, I still build user interfaces that are XIB based.

Second, the Xamarin Visual Studio plug-in does not support editing XIB files.  Visual Studio will create XIB files, but in a sense if irony, you can’t edit those files using the built-in designer.  Xamarin Studio on the Mac doesn’t support XIB files either, but Xamarin Studio will open XCode if you want to modify XIB files and automatically sync the changes back up with Xamarin Studio.

Third, I found it a real pain to copy source code from a Windows machine to a Mac, modify the files, and then copy the files back.  And to top it off, nearly all of my clients use Microsoft Team Foundation Server for their source control system.  This is the defacto standard for most enterprise environments, or at least the ones I’ve work with.  Unfortunately, there is not a nice solution to connect to TFS from a Mac.  Xamarin Studio does not support TFS natively on a Mac.  One can use the TFS Eclipse Plug-in, which works sometimes.  But most of the time, it crashes and is pretty painful to work with.  In short, it sucks.

My Requirements For a Better Solution

So in my search for a better solution, I came up with the following requirements:

  1. MUST natively support TFS for source control and work item tracking.
  2. MUST have the ability to create and edit XIB files for Xamarin.iOS projects.
  3. MUST have Resharper like capabilities for developer productivity.

Given those three major requirements, neither Xamarin Studio nor Visual Studio can meet all 3 of those requirements.  So the solution I came up with was to use both.  But swapping between the two can be painful, especially if your Mac Host and Windows Machine are two different physical machines.

The Solution

My solution was to use a Mac as my main development machine, and then run a Windows virtual machine (VM) so that I can run Visual Studio.  So here is my setup:

  • Physical Machine:  Macbook Pro w/ 16GB of RAM and Solid State Drive
  • Virtual Machine Software: VMWare Fusion
  • Windows VM: Windows 8.1 with Visual Studio 2013 installed

The Details

I first started typing this up and soon realized that I was about to write a lot of content.  It would have made for a long blog post, and felt like I would probably lose your attention.  So I decided to try something new and created a video tutorial showing you how to setup your Windows VM using VMWare Fusion, and how to properly host your source code from TFS.  So here’s the video:


So in summary, here’s the gist:

  • Install VMWare Fusion.  You can download the 30-day Trial Version.  A new license is only $69.99 USD, but well worth the price.
  • Create a Windows 8 Virtual Machine using the VM Wizard.  It’s really easy.  Install Visual Studio 2013/2015.
  • On your Mac File System (not on your Windows File System), choose a location to host your source code.
  • In your Window VM Settings, Share the folder location with the Windows VM.
  • Open Visual Studio, Create/Map your Workspace to the Shared Folder, and perform a Get Latest Version.
  • Swap between Visual Studio and Xamarin Studio with ease while maintaining source control integration!

So that’s my war story!  If you have any questions feel free to leave a comment below!

June 02, 2015 10:16 GMT

Building the Swiper control (the iOS part)

This is going to be a rather long post about building the Swiper control for iOS. There is also a WP and an Android-renderer available but in this post I'll focus on iOS.

The Swiper control is a image flipping control that displays images in a long line and allows for lazy-loading of new images.

All source code is available at GitHub (https://github.com/johankson/flipper) and the bits can also be downloaded through nuget (http://www.nuget.org/packages/Flipper.Forms/).

What's the purpose with this blog post?

The purpose is to show you how the swiper control is built from an iOS perspective.


This control is a standard Xamarin Forms control. That means that there are two major parts;
  • The shared code in the PCL
  • One renderer for each platform
In the shared code we declare our control in a platform agnostic way. I've chosen to name it Swiper.cs (upper blue arrow). Each platform then has a corresponding renderer if they do custom rendering that is. In this case the lower blue arror pointing at the file named SwiperRenderer.cs.

We're going to look into details for each of these files in a little while. But first I think we should start by looking at how the control is used and what it looks like in action.

How is it used?

We're going to start at the end where it gets used. In a XAML-page, the example is from the sample app included in the project.

The first thing you need to do is to declare a namespace so that we can reference the control.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

After the namespace is declared, you are free to use the control.

        <flipper:Swiper Source="{Binding Items}" 
                        IsNearEnd="{Binding EndIsNearCommand}" 
                        SelectedIndex="{Binding Index, Mode=TwoWay}"
                        SelectedUrl="{Binding Url, Mode=TwoWay}"
                        NearEndTreshold="4" />

The only mandatory property that you need to set is the Source property that is an ObservableCollection that contains a list of image URLs. The reason for it being observable is that the control needs to react to you adding (or removing) images to the list and update stuff based on that.

To help you with the lazy loading you can specify a command to be executed when the user is closing in to the end of the list. The name of this command is IsNearEnd. You can control the timing of this by setting the NearEndTreshold property to fire the command when the desired number of images are left.

The SelectedUrl and SelectedIndex can be set and read. Please note that the URL must exist in the already supplied list. I was thinking about adding a behavior that simply adds a new URL to the end of the list if the URL isn't in the list.

So what does it look like?

This is 29 amazing seconds of random image flipping...

Ok, show me some code!

Let's start with the platform agnostic part. I've chosen to inherit from the Xamarin Forms View class since it best fits my needs of behavior. I'm not going to show all the code here since it would just take up a lot of space. For the full sample, check out the source at Github.

  public class Swiper : View
        public static readonly BindableProperty SourceProperty =
            BindableProperty.Create<Swiper, ObservableCollection<string>>(
            (p) => p.Source, null);

       public ObservableCollection<string> Source
            get { return (ObservableCollection<string>)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }

The second thing you need to do is to define static BindableProperty objects for each property that you want to bindable and then map these to the actual member property of the class. In a nutshell, this is what my platform agnostic piece of the Swiper control do. It could do more. One example is to move the code that determines if we are getting close to the end of our image list. This code is now in each of the three renderers... Bad practice... Well, no ones perfect.

The renderer

Most of the code is within the renderer class in the iOS project. To allow for the Xamarin Forms framework to be aware of what renderer that goes with what control, you need to register them. In our case it looks like this:

[assembly: ExportRenderer(typeof(Swiper), typeof(SwiperRenderer))]

It declares the fact that if the framework needs to render a control of the type of Swiper, please use the SwiperRenderer. In fact, you can create a renderer for any Xamarin forms control. For example overriding a Label by inheriting form a LabelRenderer and add custom logic to it. This line of code must be outside any namespace declaration.

The SwiperRenderer class inherits from ViewRenderer and here's where the platform specific magic kicks in. Notice the UIView at the end of the generic declaration. This is a "native" (everything is native, but this is more native) iOS UIView that we are going to render our stuff on.

Some image swapping theory first

The way I created this control is not the best way, the first way or the worst way. It's just one way of doing it. I did it to learn more about custom renderers.

What I did is that I took three UIImageView object called them left, middle and right. If we just look at the control, the middle image is the one you see. I then listen to touch events and track drag along the x axis, repositioning the images as the user moves his/hers finger. If the delta value of the drag is above a certain threshold when the user ends the draw the images are animated either left or right. As soon as the images are animated the position of the UIImageView objects are reset and the current index is updated and images are reset. You never see the "jump". 

The normal flow

Right after the renderer is created, the OnElementChanged(...) method is called. This is called once in the renderers lifetime (normally) and lets you create the native control and pass it back to Xamarin forms. It looks like this:
      protected async override void OnElementChanged(ElementChangedEventArgs<Swiper> e)

            if (this.Element == null)

            _leftImageView = CreateImageView();
            _rightImageView = CreateImageView();

            _centerImageView = CreateImageView();
            _centerImageView.UserInteractionEnabled = true;
            _centerImageView.AddGestureRecognizer(new UIPanGestureRecognizer(OnPan));


            _rootView = new UIView();
            _rootView.ContentMode = UIViewContentMode.ScaleAspectFit;


            if (this.Element.Width > 0 && this.Element.Height > 0)
                await InitializeImagesAsync();

The important parts here are:
  • We add a gesture recognizer to the center image. That's the only one that needs one.
  • We update sizes, setting the frame of the image and position them in a fine row.
  • We create a UIView and add three subviews to it.
  • We then call InitializeImagesAsync() that loads the correct images onto the three images displayed.
Then each time a property is updated on the control the framework calls OnElementPropertyChanged(...) and that one looks like this:

 protected async override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == Swiper.SourceProperty.PropertyName)
                await InitializeImagesAsync();
            ... more code omitted - it looks the same

Here you can react to changes in properties. In the example above, if the Source property changes we need to reinitialize our images. In fact, we reinitalize them a lot.

And finally, the OnPan method we wired up to handle any drag events handle the interaction with the user. Check it out in the sample, it's long but self explanatory.

Also, worth noting, there is no draw call since we don't need to override it. iOS is very good at recognizing invalidation of the UI and redraws just fine without us bothering it. The Android version of this control however is mainly manual drawing. Mostly for fun...

What about caching

Well, there is still job to do here. At the moment, I use a simple Dictionary that has no concept of size management and storing to disk. It is destroyed as soon as the user navigates away from the swiper.
        // Primitive cache - no life time management or cleanup - also stores the image in full size.
        // Thinking about abstracting the cache away and inject it instead to make sure it can be
        // replaced during runtime.
        private Dictionary<string, byte[]> _cache = new Dictionary<string, byte[]>();

How does the loading overlay work

Oh you noticed that, nice! When I said that I had three UIImageView objects... I lied, I have three AsyncUIImageView objects that inherit from UIImageView that simply adds an overlay if an image hasn't loaded yet.

Any other special cases

I needed to set the alpha to 0 to make the "-1" picture invisible so you don't see it when scrolling left of the first picture. Clearing the Image source didn't work. Now that I think about it, that should work... I need to investigate that again.


This is just version 1 of the control. If you have suggestions, please add an issue to the Github project directly and feel free to steal any code you fancy.