James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Live, Love, Bike, and Code

Share


Tags


James Montemagno

Why I Choose Xamarin to Build Cross-Platform Apps

It has been a little over 7 years since I left my day job at Canon crafting wonderful printer workflow management software, to dive into the world of mobile development. At the time it was an extremely tough decision because I had been only working on desktop Windows Forms and WPF applications, and this change meant entering a whole new unknown world of platforms that I didn't know much about. This move was not only changing my main day job, but also the city that I lived in with a fresh start in Seattle. At the time I didn't know what I was in for since the change in my career and living situation was so drastic. I was so lucky to have had the option to explore cross-platform technologies which is what led me to find Xamarin. Finding this single piece of technology completely shifted and revolutionized my entire life as a developer. I thought what time is better than now to reflect back on my love for this technology that put me where I am today.

2000px-Xamarin-logo.svg

If you are brand new to Xamarin or just need a refresher, then let me give you the elevator pitch for Xamarin. Xamarin enables developers to craft beautiful cross-platform mobile applications for iOS, Android, and macOS in C# (or F#) with the ability to share code across all .NET platforms, leverage existing libraries, and access to 100% of the native APIs.

CodeShare

To me, Xamarin is much more than this. I thought what better way to reflect on my 7 year anniversary as a mobile developer then to talk about why I chose Xamarin 7 years ago and why I still continue to choose Xamarin today to build all of my mobile apps.

Fully Native

It is true, Xamarin apps look and feel native, because they are native. This has always been touted as the top selling feature of the Xamarin platform. You get full access to the native APIs of iOS and Android from C#, can craft and use every available native user interface control, and get great native performance when running your application. That said there are trade-offs when chosing a cross-platform framework and the team works really hard to optimize each runtime. I could go into all the details of how this works, but our documentation team has already done this, so give it a read. I do love this aspect of developing apps with Xamarin, but there is so much more to choosing Xamarin as the way to build mobile apps and it is worthy of a few thousand words ;)

Productive Development Environment

While being native, native, native is very important what I need the most as a developer is a super optimized development experience for any application I am building. Every day I come into the office and I have to open my project, start coding, debug my application, and commit code for production. This daily developer loop has to be super optimized with the tools I actually want to use, and that are going to make me highly productive. It is not just the tools that I open up every day to code in, it is the entire ecosystem around the specific technology that can really take things to a different level. Here is what I mean and how it applies to Xamarin development.

The Power of C#

At the very core of Xamarin is C# and it's ability to take advantage of all of the latest features that are being bundled into this awesome programming language. After working in C++ and Java for many years in university, I ran into a professor, Phil Miller, that would change my development career. He had a strong passion for object oriented development and had latched on to C# early in its development. He used it as a base for his classes and I was lucky enough to have signed up for one. From the very first class and interface I created to the wonderful .NET base class library that backed it, I was completely sold.

From there C# would go on to create some truly ground breaking technologies such as Linq and the TPL (Task Parallel Library) aka async/await. As the language evolved, it continued to advance and more recently introduced a plethora of great new features that really boost developer productivity such as pattern matching, expression-bodied members and methods, async Main, and tons of other features that I have blogged about in the past. With C# 8 on the way the best programming language is only getting better and the investment from Microsoft has never been greater.

I mean look at this crazy awesome code I recently wrote that will go and grab any Xamarin.Forms Color field and put it into a Dictionary<string, Color>:

var colorDictionary = typeof(Color)
                .GetFields()
                .Where(f => f.FieldType == typeof(Color) && f.IsStatic && f.IsPublic)
                .ToDictionary(f => f.Name, f => (Color)f.GetValue(null));

While I do love all of the core features of C# that I get to take advantage of when developing with Xamarin, what sets it apart is how the Xamarin SDK C#ifies iOS and Android APIs. While it is true that Swift and Kotlin are advancing iOS and Android development with fancy new features, I have been enjoying them for over 7 years with Xamarin! When developing with Xamarin and you need to access native APIs you do it in C# and those APIs get automatically upgraded to take advantage of things such as async/await, auto-properties, and a bunch more. Here is a super simple example of how you would geocode a coordinate in iOS versus C#:

Swift original code from cocoacasts, new code from Steve in comments

let geocoder = CLGeocoder()
let location = CLLocation(latitude: 47.640320, longitude: -122.134400)

geocoder.reverseGeocodeLocation(location) { (addressList, error) in
    if let error = error {
        print("Unable to Reverse Geocode Location (\(error))")
    } else {
        print(addressList?.first?.compactAddress ?? "No Matching Addresses Found")
    }
}

extension CLPlacemark {
    var compactAddress: String {
        return "\(thoroughfare ?? ""), \(locality ?? ""), \(country ?? "")"
    }
}

C# with Xamarin

try
{   
    var geocoder = new CLGeocoder();
    var location = new CLLocation(47.640320, -122.134400);
    var addressList = await geocoder.ReverseGeocodeLocationAsync(location);
    Debug.WriteLine(addressList?.FirstOrDefault()?.CompactAddress() ?? "No Matching Addresses Found");
}
catch (Exception ex)
{
    Debug.WriteLine($"Geocode failed with error: {ex.Message}");
}

static string CompactAddress(this CLPlacemark placemark) =>
    $"{placemark.Thoroughfare}, {placemark.Locality}, {placemark.Country}";

What I like here is that not only does the Xamarin SDK simplify ReverseGeocodeLocationAsync to a single line of code, but the codes look beautiful with modern C# features such as extension methods, async/await, Linq, pattern matching, and null coalescing. Sometimes it is the small things such as adding a ? to check for null or getting and setting properties instead of calling a method that greatly enhances my day to day and makes me continue loving this language and platform.

The World's Best IDE

The moment I was introduced to Visual Studio I knew that I never wanted to touch another IDE ever again. Gone were the days trying to debug an app in Eclipse or trying to figure out what version of NetBeans was compatible with what version of Java. Visual Studio was the one IDE to rule them all and it was always packed full of amazing productivity features including some of the best IntelliSense out there. When I walk up to my desk and boot up Visual Studio I know that I am going to be delighted. After using Visual Studio throughout college and at my first job at Canon I knew that I didn't want to move away from it. I knew where everything was, all the keyboard shortcuts, easy source management, tons of refactoring and IntelliSense goodies, and awesome add-ins that I used to boost my efficiency when editing code. I could go on and on about all the great features built in, but Kendra recently made this crazy awesome video breaking down productivity features in Visual Studio in 5 minutes:

So, when I learned that Xamarin had full Visual Studio support for Android development built right in to Visual Studio where I could craft my applications with a full designer I was in! I didn't have to learn a new IDE or a new language at all and I could jump right in.

Android-Setup

As time passed the Xamarin team brought full iOS development to Visual Studio on Windows including a full remoted iOS simulator, designer, asset management, Wi-Fi debugging, automatic provisioning, and tons of other features so I really never need to touch my macOS machine and have everything at my finger tips. Of course if you are on a macOS machine do not worry as there is Visual Studio for Mac that delivers a development experience for .NET developers building mobile and cloud apps. While it is not as fully featured as Visual Studio on Windows the team is hard at work adding new features all the time. Working on the inside I can say there is a large investment here.

iOS-Simulator

On top of all of this, there is an entire marketplace full of extensions to the IDE to add spectacular functionality to the IDE from Microsoft, the community, and other amazing companies. One of those spectacular extensions is IntelliCode, which is AI-assisted development and IntelliSense. That sounds fancy, but what the team did was analyze tons of C# and XAML (and many more) open source projects on GitHub to create machine learning models for predicting what you probably want to code up next. Here is a rad example for Xamarin.Forms XAML:

This is just one of many extensions in the Visual Studio ecosystem that builds on top of a simply amazing IDE.

Maximized Code Sharing

When I was originally choosing a technology for cross-platform mobile development one of my top requirements was to cut down my development time by being able to share as much code across platforms as I could. This was important for me not only because I wanted to cut down my development time, but also because I wanted to test my business logic only once and if a bug popped up then I simply had to fix it in one place. I didn't want to have to write the same logic to make a web request and store it in a database three different times. I wanted to do it once and be done with it, and that is what Xamarin enabled me to do.

.NET Is On Every Platform

The unique part of Xamarin is that the team ported the entire .NET framework and runtime to run natively across iOS, Android, and macOS. This means that the same logic that is able to run on a desktop app or web app can be run directly in your mobile apps with Xamarin and completes the .NET story as a platform to build for anything.

dotnet

This was extremely smart because developers can immediately reuse their existing .NET libraries that they have been building for years and been sharing on NuGet. When I was getting started I was immediately able to re-use my favorite libraries that I had been using since I started C# development such as Json.NET and SQLite-net. This code and library sharing strategy enabled me to share over 70% of code in the first app that I ever built and now with the amount of .NET libraries available I easily share over 90% code in all my apps.

Shared Cross-Platform UI

One of the main reasons that I am able to share as much code and why I am so productive is because of Xamarin.Forms.

banner

Xamarin.Forms gives developers access to a vast application building framework that offers cross-platform native user interface, animations, two-way data binding, extensibility, deep linking, navigation, and a plethora of other features to build mobile applications. Xamarin.Forms sits on top of the core of the Xamarin platform and opens up a whole new world to be able to create a single shared XAML user interface that uses that underlying platform to render native user interfaces.

EvolveApps2

Xamarin.Forms has grown up since it's launch nearly 5 years ago and has added ridiculous amounts of features to take advantage of. The team is currently prepping Xamarin.Forms 4.0 that is set to bring even more developer productivity with the introduction of a simplified app structure with Shell, Navigation Routes, Visual Consistent UI, CollectionView, BindableLayout, CarouselView, and a bunch more.

What I love about Xamarin.Forms is the ecosystem of libraries and controls that have been created by the community and by amazing companies that I have been using for years such as Syncfusion and Telerik.

syncfusion-xamarin-platform

Having this amazing ecosystem means that you are able to create the best applications in no time at all. I am loving each and every moment of it.

Sharing Code Has Never Been Easier

Let's recap really quick. You can write C# code and build .NET libraries that can be shared across just about any operating system out there. With Xamarin.Forms you have a single user interface stack to build mobile applications that are still fully native. Wouldn't it be great if being able to share all of this code was simple? It is with .NET Standard libraries that enable developers to build a single .NET library an have it work seamlessly across any .NET platform that supports it, which is a ton including Unity game development!

dotnetstandard

As a developer that creates a ton of libraries having this core technology at my disposal is absolutely essential and improves my day to day life as a developer.

Cross-Platform Simplified

Sharing core .NET business logic is great, but what about getting access to those lovely platform APIs of iOS and Android from shared code and a single API? Well it is all possible! Through a little engineering, a little evangelism, and a bunch of amazing community members we created a full ecosystem of Plugins for Xamarin that abstracted away platform specific code to a cross-platform API for developers to use.

Then last year I was given the opportunity to work with some members of the Xamarin development team to transform this concept into a core part of the Xamarin platform. After a few months and a lot of late nights of coding we launched Xamarin.Essentials that provides core cross-platform API for iOS, Android, and UWP developers.

Essentials

This means you now have access to core platform features such as sensors, connectivity, geolocation, secure storage, preferences, text-to-speech, and a bunch more from your shared business logic! Learn a single handcrafted API to access any of the underlying platform features. It is a beautiful world when you can check the connectivity of your device with a single line of code:

if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
    // Connection to internet is available
}

This is just the start of the Xamarin mission to maximize code sharing across all .NET platforms.

End-to-End Integrations

So far I have talked a lot about what the Xamarin platform and development experience looks like when you are building apps on a day to day basis, but there is much more to just building an app. You need to connect it to a powerful cloud backend, test it on tons of devices, integrate essential services, and be able to deliver apps faster with DevOps. With Xamarin you have all of this and more with great services that Microsoft provides, but you are free to use any of the great integrations that are available to you.

Cloud & AI Infused

As I start to build out mobile applications I usually soon learn that I need to extend them with some cloud backend services and spice them up with some artificial intelligence. I want these services to work with any application that I am looking to build, not just my mobile applications. I work at Microsoft, so of course I am a bit bias and think that Azure is a perfect option for adding cloud to any app. Azure is constantly evolving with new services and it provides over 54 regions to deploy code into worldwide. More important though is that it provides excellent cross-platform .NET optimized SDKs for just about every service. Anything that I want to do, I can do cross-platform.

Azure

These services are great and all, but everyone is always talking about AI and Machine Learning (at least we do on Merge Conflict). I am not a data scientist, but I would love to be able to add some awesome AI into my apps with very little code. What do you know, Microsoft introduced a service to do that in Azure called Cognitive Services.

cogs

From image classification to face dection to text analytics, it has it all. Each service also has a cross-platform SDK! In my GeoContacts app we introduce facial emotion detection in just a few lines of code:

static class EmotionService
{   
readonly static Lazy<FaceAPI> faceApiClientHolder =
        new Lazy<FaceAPI>(() => new FaceAPI(new ApiKeyServiceClientCredentials(CommonConstants.FaceApiKey)) { AzureRegion = AzureRegions.Westcentralus });
    static FaceAPI FaceApiClient => faceApiClientHolder.Value;

    public static async Task<string> GetEmotionAsync(Stream stream)
    {
        var attributes = new List<FaceAttributeType> { { FaceAttributeType.Emotion } };
        var faceApiResponseList = await FaceApiClient.Face.DetectWithStreamAsync(stream, returnFaceAttributes: attributes);
        var emotion = faceApiResponseList.FirstOrDefault()?.FaceAttributes?.Emotion;


        if(emotion == null)
            return "🐵";

        var scores = new Dictionary<string, double>
        {
            ["😠"] = emotion.Anger,
            ["🙄"] = emotion.Contempt,
            ["🤢"] = emotion.Disgust,
            ["😨"] = emotion.Fear,
            ["😃"] = emotion.Happiness,
            ["😐"] = emotion.Neutral,
            ["😢"] = emotion.Sadness,
            ["😲"] = emotion.Surprise,
        };

        return scores.OrderByDescending(x => x.Value).First().Key;
    }     
}

Seeing AI is proof of how Xamarin combined with Azure and Cognitive Services can truly build astonishing apps that can change the world:

DevOps Simplified

I am a huge fan of DevOps as it really simplifies the daily lives of developers. Simply push code to the server and let your DevOps pipeline build, test, and distribute your application to you, your testers, or even the stores.

DevOps

Azure DevOps & App Center

When it comes to full DevOps nothing does it better than Azure DevOps. It works with every piece of technology, cloud Windows/Linux/macOS agents, full CI/CD with gates, and a plethora of other features. I really like how I can fill out a workflow and see exactly how my app or website is going to be built and deployed. On top of this Azure DevOps can build all of my .NET Libraries and even create a private NuGet feed for me for practically free!

azuredevops

A nice compliment to Azure DevOps is App Center that provides really simple CI/CD for mobile apps and also essential services such as analytics, crash reporting, and push notifications. Both Azure DevOps and App Center work seemlessly with each other.

Choose Your Own Adventure

While I love our DevOps products here at Microsoft, there is no reason you can't build your Xamarin apps in Bitrise, TeamCity, Jenkins, or just about any other DevOps system out there.

An Open Source Platform

When Microsoft aquired Xamarin not only did they make Xamarin free in the community edition of Visual Studio, but they also open sourced tons of the components. Every SDK and library from the Xamarin team that I have talked about are open source under MIT. This includes Xamarin.Forms, Xamarin.Essentials, all of the core SDKs, and even the runtime!

Fully Commited

It has been over 7 years since I started mobile development with Xamarin and I think it is in the absolute best state that it has ever been. I started as a customer building mobile apps for a small startup. I then had the amazing opportunity to work for Xamarin as a developer evangelist to help share my passion for the platform and help developers around the globe be successful with Xamarin.

xamarin-joins-microsoft

This month marks the 3 year annivesary of the announcement that Microsoft was acquiring Xamarin and I have come along for the full ride. I am now a Program Manager of mobile developer tools working close with our development community and core engineering team to ensure we are building the best possible tools for mobile developers. The commitment from the leadership & development teams here at Microsoft has been very inspiring and has me doubling down on my own commitment to Xamarin. Let's just say that you will be seeing and hearing a lot more about me this year.

Some Things to Think About

Like any cross-platform framework there are some trade-offs that you are going to have to make when it comes to app size, performance, and updating of the platform. I mentioned early on that the team is always optimizing the runtime and performance across the board. When it comes to core Xamarin without Xamarin.Forms you see nearly a 1:1 on this measure and pretty small app sizes. With Xamarin.Forms specifically on Android there is a hit on startup and some performance here and there as it is a more complex UI framework, but it has improved great over time and of course is a trade off for sharing nearly all of your code. One thing to note is that the team recently introduces AOT on Android this can greatly improve performance of an Android app by adding more size to the APK. I tried to look at the overall platform as a .NET developer and what Xamarin has to offer from start to finish of a project, which is a very rich ecosystem and I hope that you will agree.

Get Started Today

You have everything at your fingertips when it comes to mobile application development: an amazing cross-platform framework, amazing IDE, code sharing, great backend cloud services, AI & ML integrations, and a full DevOps solution!

It has never been a better time to get started with Xamarin to build iOS and Android apps in C# with Visual Studio as it is completely FREE with Visual Studio Community Edition! Head over to the Visual Studio tools for Xamarin page to get started. After that browse through all of the amazing Xamarin documentation that has everything you need. There are other great resources out there including:

Wrapping Up

This is a blog post that I have wanted to put together for some time now and happy to have the push to make it the first post as part of the #XamarinMonth initiative started by Luis. Checkout his blog for tons of great upcoming posts.

Copyright © James Montemagno 2019 All rights reserved. Privacy Policy

View Comments