Disclaimer: this is an automatic aggregator which pulls feeds and comments from many blogs of contributors that have contributed to the Mono project. The contents of these blog entries do not necessarily reflect Xamarin's position.

August 24

How Olo Powers 150+ Restaurant Ordering Apps with Mobile DevOps

Olo’s customer and employee-facing Xamarin apps help restaurant brands deliver faster, more accurate, and more personalized service to their customers, building customer loyalty and improving restaurant operations. With a portfolio of over 150 brands and 25 million users, mobile DevOps is critical to Olo’s mobile strategy, and Xamarin helps the team deliver the highest quality experiences to their global clients.

Today, we’ve invited Greg Shackles, Principal Engineer at Olo and long-time Xamarin community member, to share his experiences with mobile development and his advice for aspiring app developers.
Which Wich App Screenshot
Tell us a little bit about your company and role. What is Olo and who are your customers?

I’m a Principal Engineer at Olo, which means I’m involved in a bit of everything we do.

Think of Olo as the digital layer between the restaurant and the on-demand world. Whether that’s takeout, delivery, or streamlined phone ordering, we integrate directly with the brands’ existing systems, including Point of Sale and loyalty, to bring digital commerce into their existing operations.

We generally work with large multi-location brands, typically over 40 locations. If you’ve used the Five Guys app, called 1-800-CHIPOTLE, or ordered Wingstop online, you’ve used Olo.

Tell us about your app(s).

We publish fully-branded iOS and Android apps for restaurants, enabling their customers to engage directly with their brand, customizing orders exactly how they want, on whichever platform they want, at their own pace, and be assured the restaurant will get it right.

With the apps, customers are able to easily find their closest locations, redeem loyalty rewards, see menus, view recent or favorite orders, order ahead, allowing them to Skip The Line® when they arrive, or even have their order delivered. Our open framework allows customers’ agencies to utilize our API, which we’ve seen with Sweetgreen.

What role does mobile play in your company’s strategy? Has your mobile offering evolved over time?

From the very beginning, and for the last decade, mobile has been the foundation for Olo.

Tired of waiting in long lines for his coffee every morning, our founder and CEO, Noah Glass, saw mobile’s potential to solve this problem and created Olo. In 2005, we launched our feature-phone based text message ordering; remember, this is still a couple of years before the launch of the original iPhone, and mobile remains a cornerstone of our platform to this day.

While we no longer support text message ordering, our customers engage with and accept orders from their customers on a wide variety of platforms including the web, iOS, Android, over the phone, and even Facebook and Twitter chat-based interfaces.

Why did you choose Xamarin?

Olo’s app platform wasn’t always built on Xamarin. Its was originally built using one of those Other Frameworks™ using JavaScript, which worked well enough for a while, but eventually put us in a tight spot. We found ourselves battling with the abstractions the framework put between us and the platforms, and at times it could take weeks to finish simple features. This was frustrating for our developers, but even more importantly, it meant that we couldn’t deliver the experience we wanted to our customers.

Any engineer knows that rewriting a platform is not a task to be taken lightly, but choosing to rebuild it using Xamarin was an obvious choice. We were already a .NET and C# shop, so being able to bring some of our existing amazing engineers into the mobile world, leveraging their existing skills, was a huge opportunity. With the new platform in place, we are able to deliver a stable, fully-native experience to our users, while still keeping our engineers happy.

What do you think about when you hear “native app”?

For me, it comes down to apps that fully leverage the native underlying UI frameworks, rather than an abstraction, and deliver the kinds of experiences users are accustomed to and expect from an app on that platform. Native apps need to feel native and to perform as such. They need to be able to use the things that make each platform unique and interesting, and not only build to the lowest common denominator across all of them.

Xamarin provides us with the best of both worlds, exposing direct access to all of the native APIs, while also allowing us to dial in our own abstractions the way we want them.
Wingstop App Screenshot
How much code do you typically share across platforms?

There’s an important qualifier that often gets lost in the discussion: how much code is shared across platforms that should be shared? Sharing code is great, but that doesn’t mean you need to avoid unshared platform-specific code, if it makes your app better on that platform. It’s our job as app developers to write code that gives our users the right experience.

We benefit from large amounts of code sharing at multiple different levels. At the base level, a core portable class library contains the real meat of the application: services, database access, network and API calls, application flow, logic behind each screen, etc. We have a large number of unit tests for everything in this layer, with the ability to run those tests on individual platforms to ensure compatibility.

On top of that, we’ve implemented our shared iOS and Android layers as shared code projects, allowing us to define all the platform-specific pieces needed to drive the app on each platform, agnostic to any particular brand.

For a specific brand’s apps, we have a lot of tooling built around our build and scaffolding pipelines that allow us to generate unique projects.

Describe your development process—how are you using mobile DevOps / CI?

With a platform like ours that maintains so many different apps, automation and CI is crucial. Every commit on every branch builds each project, runs unit tests, and builds the brand-specific apps, ensuring that the entire pipeline remains solid.

We can deploy versions of any brand’s app out to any of our environments via HockeyApp with the click of a button. We have automation in place around app store provisioning, packaging and signing, and also use Xamarin.UITest to automate screenshot generation.

How are you testing your apps? Why is mobile quality important?

Much like automation, testing is critical. We pride ourselves on delivering apps that are not only native and performant, but also incredibly stable. Unlike the web where you can quickly ship a fix and users get it on the next refresh, the barrier to releasing app updates is much higher. It’s crucial to smoke out as much as possible before the app makes it into your users’ hands.

We get a huge amount of wins out of unit testing. Since so much of our apps are driven from that layer, we can write tests that run quickly and test a significant portion of app behavior. Without spinning up a UI, we’re able to test everything from making network calls to defining the app’s flow from screen to screen.

We also love using Xamarin.UITest and Xamarin Test Cloud to make sure things are working correctly at that level too. Unit tests are awesome, but ultimately it’s the end user’s experience that matters.

We’ve gone through some big design changes in recent months, and being able to run our apps in Xamarin Test Cloud to see how different devices handled (or didn’t handle) things was simply invaluable. We were able to quickly and easily catch issues in random Android devices we likely would not have gotten otherwise.

How do you use HockeyApp?

We’re using HockeyApp purely for beta distribution, both internally and externally. For analytics, we’re using a mixture of technologies, ranging from things like Google Analytics and Google Tag Manager to custom homegrown instrumentation that we use to monitor how our apps are behaving in the wild.

My session at Xamarin Evolve 2016 dug into what we’re doing to monitor our apps’ performance in the hands of users in real time. One of the fun things about a platform like Olo is that we’re able to see how a wide range of brands and users interact with our apps, which puts us in a great position to learn and keep improving our flows and overall user experience.

What have your customers and their users said about your apps?

We’re always tracking customer feedback and doing user testing. Overall, the feedback has been overwhelmingly positive. Every time someone leaves an app review for one of our apps, both good and bad, it gets sent to the app team’s room in Slack for all to see.

It’s always a lot of fun when a brand launches with us and their customers go nuts. If you want to see what I mean, head over to Twitter and search “Wingstop app.”
 



 
What advice do you have for developers who are just starting out or investigating mobile development? Any best resources?

Between blogs, video services like Pluralsight, and the Xamarin site’s awesome documentation, there’s so much content available. This is great, but it can feel overwhelming for a newcomer.

My main piece of advice for new mobile developers is to start small. Don’t start out putting a bunch of abstractions between you and the platforms, such as big MVVM frameworks that add a lot of value, but also a lot of magic. There’s no escaping the fact that platforms like iOS and Android, while they do have many similarities, are ultimately very distinct. To start, spend some time learning the basics of how each operates, and then start diving into some of the abstraction layers once you understand exactly what they’re abstracting.

Read more about how our customers are transforming customer relationships and driving internal productivity on our Xamarin Customers webpage, and dig into Microsoft’s Mobile DevOps Solution.

The post How Olo Powers 150+ Restaurant Ordering Apps with Mobile DevOps appeared first on Xamarin Blog.

Attaching your project to a bug report

We want your bug reports! With good reports, we can get the info we need to improve the quality of Unity for everybody. When your bug reports include a solid description and an attached project, we have a 3 times larger chance of reproducing the issue and filing a bug that can be fixed! But […]

Newest open source project: managed-commons-collections-squarelist

I've published the source for a tentative 1.0.0-beta for this MIT-Licensed project at GitHub.

What is a SquareList?


Basically a squared (same depth as width) structure formed from a List of LinkedLists, with items kept in ascending order, so that in constant time you can know the minimum and the maximum values, O(1). Also by being almost 'square' you can insert/search/delete values in a worst case time of O(sqrt(n)).

Implementation details


I implemented it as a generics-based collection, in C#, for .NetStandard1.0 .

Loosely based on an article published in the May 2013 issue of Dr Dobb's Journal, by Mark Sams.

This implementation allows for multiple instances of the same value to be inserted, and then deleted one-at-a-time or wholesale.
Thinking in performance, search for counting/existence is done bidirectionally, but removal scans only in the forward direction, to have stable behavior (remove the first found) when duplicates exist.

The trade-off is obviously about using more memory to achieve better performance, as there is no copying of large swaths of memory, or linear scans of the total mass of data, but the downside is lots of pointers from each node in both directions.

August 23

Creating a Serverless Backend for Mobile Apps

Azure Functions Functions_Logoenable developers to create a serverless, event-driven experience for their data and applications. In our first post on Azure Functions, we saw how to have an Azure Function perform an OCR of an image and insert it into an Azure Mobile table. Today, we’re going to take a look at turning Azure Functions into a serverless backend for our mobile apps that can integrate and connect with data from Azure, Office, Salesforce, or even Google Docs.

In this blog post, we’ll create a new mobile app that can query data through a single Azure Function endpoint. The Azure Function we create will take a country as input to a HttpRequest, parse data from a data source, and return a list of monkeys that live in that region.

Monkeys

Creating our Mobile App

To get started, we need to create a new blank Xamarin.Forms application and add a new XAML page for our user interface. The UI will have a few elements on it to select the location we want to query for monkeys from, a button to press to call our backend code, and a list of monkeys.


        
          

Now we’ve got our base page set up and ready to consume data from our Azure Function. Before we create the Azure Function, let’s set up our Model and ViewModel that our View will talk to.

First is the Monkey model, which has a few properties:

public class Monkey
{
    public string Name { get; set; }
    public string Location { get; set; }
    public string Details { get; set; }
    public string Image { get; set; }
}

Then we can create our ViewModel that the user interface will bind to, and we’ll also stub out a Command that will call our Azure Function when the “Find Monkeys” button is pressed.

public class MonkeysViewModel
{
    public MonkeysViewModel()
    {
        Monkeys = new ObservableRangeCollection();
        GetMonkeysCommand = new Command(async () => await GetMonkeysAsync());
    }
    //Monkey List: ObservableRangeCollection from: https://github.com/jamesmontemagno/mvvm-helpers
    public ObservableRangeCollection Monkeys { get; set; }
    //Selected Location index from our picker
    public int Location { get; set; }
    //Mirror list so we can use it later
    public List LocationList => new List
    {
        "Africa",
        "Asia",
        "Central America",
        "South America"
    };
    //Command that will call GetMonkeysAsync to get data
    public Command GetMonkeysCommand { get; }
    public async Task GetMonkeysAsync()
    {
        try
        {
           //Call to Azure Function here
           //Load Monkeys here.
        }
        catch (System.Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }
}

Finally, in the code behind of our MonkeysPage.xaml.cs, we can set the BindingContext.

public MonkeysPage()
{
    InitializeComponent();
    BindingContext = new MonkeysViewModel();
}

Now, it’s time to create our backend with Azure Functions to pull data into our mobile app.

Creating the Function

Creating an Azure Function to respond to a web request is simple, as there’s already a template called “HttpTrigger – C#” that will provide boilerplate code to take in an HTTPRequestMessage and output a HttpResponseMessage with any data we’d like. Name the function and set the authorization level to anonymous, so our mobile app can access the endpoint.

NewFunction

Once created, we’ll see boilerplate code that parses the request for a field called “name” that we can use later on.

public static async Task Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;
    // Get request body
    dynamic data = await req.Content.ReadAsAsync();
    // Set name to query string or body data
    name = name ?? data?.name;
    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name));
}

Note that for extra security we could turn on authentication for our Function with Azure Easy Authentication or a secret key.

Adding Data from Input Bindings

At this point, we could call the function endpoint and it will return a simple message to us. For our app, we want to take in the parameters, talk to a data source, and return data for our mobile app. This is where input bindings for Functions are handy. Tap on the Integrate tab and select New Input. This will enable us to create a connector to several data sources to read data from.

New Input

There are several options, including integrating with Azure Mobile Table Records or existing SaaS solutions, for file and table access:
AddSaas

For this example, we’ll skip this step and hard code in the monkey data that will be returned. We can use the name parameter as the location that is passed in.

This means before we return, we’ll get the list of monkeys and then perform a Linq query to find the monkeys with the specified location:

var monkeys =  GetMonkeys().Where(m => m.Location.ToLower().Contains(name.ToLower()));
return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, monkeys);

You can find the final run.csx file on my GitHub for reference.

Getting Data to our Mobile App

Now it’s time to integrate the Azure Function into our mobile applications. All we need to do is fill in our GetMonkeysAsync method to make a web request and deserialize the data from our Azure Function.

public async Task GetMonkeysAsync()
{
    try
    {
        using (var client = new HttpClient())
        {
            var url = "https://mobile-ocr.azurewebsites.net/api/Monkeys";
            var input = JsonConvert.SerializeObject(new { name = LocationList[Location] });
            var res = await client.PostAsync(url,
                new StringContent(input, Encoding.UTF8,"application/json"));
            var json = await res.Content.ReadAsStringAsync();
            var monkeys = JsonConvert.DeserializeObject<IEnumerable>(json);
            Monkeys.ReplaceRange(monkeys);
        }
    }
    catch (System.Exception ex)
    {
        //Something has gone wrong
        Debug.WriteLine(ex);
    }
}

In Action

In Motion

There you have it! Our mobile app is able to call and pass data to our Azure Function and get the correct list of monkeys back.

Learn More

There are so many more integrations for Azure Functions for mobile applications, especially around Bindings and Triggers to tie to several data sources. Be sure to head to the Azure Functions website for more information and download the full source code for the sample app on my GitHub.

The post Creating a Serverless Backend for Mobile Apps appeared first on Xamarin Blog.

August 22

Podcast: Identity Management in Mobile Apps

Whether you’re building an app that has user-specific data such as notes, or need to ensure access to internal data is restricted, it’s likely your mobile app needs identity management. In this edition of the Xamarin Podcast, Mike James and I discuss identity management in mobile apps. We start by exploring the question, “does my app even need identity?” If it does, we break down the various options available to mobile developers, from local to social to enterprise authentication.

Subscribe or Download Today

Knowing the latest in .NET, C#, and Xamarin is easier than ever with the Xamarin Podcast! The Xamarin Podcast is available from iTunes, Google Play Music, and SoundCloud. Do you have an interesting story, project, or advice for other .NET mobile developers? If so, we’d love to share it with the Xamarin community! Tweet @pierceboggan or @MikeCodesDotNet to share your blog posts, projects, and anything else you think other mobile developers would find interesting. Be sure to download today’s episode on identity management in mobile apps, and don’t forget to subscribe!

The post Podcast: Identity Management in Mobile Apps appeared first on Xamarin Blog.

Unity Ads Platform Update: Integration Tutorials

Hi all!

The Unity Ads team has been hard at work on the next release of our platform, and it’s now and available for use!
Download now in the Unity Asset Store to get started for iOS and Android

You can also download here for iOS and Android.

Why is this a great opportunity?

In addition to game ads, this update* to the Unity Ads platform brings a whole new network of ads to your games. It provides you with brand advertisers competing, and paying top dollar, to advertise in YOUR game – boosting global fill rates, eCPMs, and ARPDAU!

We’re dedicated to helping developers like you succeed, so you can keep doing what you love – making fantastic games! With that in mind, we’d like to make sure this update is as easy and painless as possible. You can find all the information you need — whether you’re a native Unity user, on iOS, or Android. The following help guides will show how simple it is to integrate:

Documentation
Quick start guides
Video tutorials:



The sooner you download this update, the sooner you’ll start earning even more revenue. Get started now to make sure your network is ready and waiting for the peak traffic of the holiday season, which is right around the corner.

IMPORTANT NOTE: If you are using a mediation partner, you must first get the latest version of the mediation SDK from that supplier. You must also make sure that the package supports Unity Ads 2.0.

As always, you can go to our forums and your Unity Ads dashboard to get personalized help every step of the way. If you have any questions, please contact us at unityads-support@unity3d.com

Download now in the Unity Asset Store to get started for iOS and Android

*In this release, there’s a small, lightweight SDK required to download. Soon, this feature will be built into the Unity Editor where it’s as easy as flipping a switch to turn on video ads.

August 21

crestexplorer

At the 3rd Party Dev State of the Union at EVE Fanfest 2016 earlier this year, CCP FoxFour drew my attention to a limitation of the current approach used by crestmatic to generate CREST documentation: it only discovers resources always reachable from the API root from the perspective of the authorised character at generation time. As CREST now includes APIs for transient resources like fleets the entire API isn’t reachable for documentation from a nightly run using the credentials of a character not in a fleet.

There are a couple of ways to fix this. At the API level OPTIONS responses could refer to linked representations that can exist. An alternative is to extend crestexplorerjs with OPTIONS metadata to make it expose live documentation about reachable resources.

At a recent hackathon I took the second approach. crestexplorer now makes OPTIONS requests to each resource it requests and uses crestschema and data urls to generate downloadable JSON schema descriptions for each of the representations available for a resource. It also hyperlinks to the alternative representations so now all representations of all reachable resources are available in crestschema and the human readable descriptions of each field are added to the rendered resource as hovertext.

Now documentation for any valid CREST resource live by specifying the URI for the resource as the crestexplorer hash fragment. Even when the resources are transient documentation is available for resources while they exist.

August 19

Video games: a matter of life and death?

In May of 2006, the then 11-year-old boy, Taylor Carol, was diagnosed with a rare form of leukemia, and the doctors predicted that he had two weeks to live. But Taylor proved them wrong. What’s more, he found a special way to cope with the endless months in isolation, and loss of normal childhood activity. Video games rescued Taylor’s childhood, allowing him to communicate with other kids, and distracting him from the otherwise nearly unbearable period of his cancer treatment.

After a grueling five-year battle with cancer, Taylor fully recovered and went on to found the nonprofit organization, GameChanger, with his father in 2008. GameChanger helps children and families suffering from cancer and other rare diseases by providing the kids with game experiences and other types of entertainment.

UCLA Hospital, Lovely Child... - Copy

A GameChanger visit with some gaming goodies brings a smile to a child’s face at UCLA Children’s Hospital.

I’m pleased to say that Unity has now committed to supporting GameChanger with awareness campaigns and donations. We’ll also be contributing tutorials to an exciting new GameChanger technology platform, which will deliver streaming content and interactive activities exclusively to hospitalized children.  

I can’t think of a more worthy cause to support. GameChanger brings hope to the kids and families who need it most. And it does so in a tangible way that has an immediate and direct impact. Every parent and family’s worst fear is having to face a crisis and challenge like this.  I implore everyone in the community who can afford to get involved, even in a modest way, to do so by making a donation.

Straight to the kids and their families

Unlike traditional fundraising charities, GameChanger repurposes donated items and uses digital technologies to help children directly. This business model requires a low overhead and a small staff, which makes them highly efficient.

Charity Watch considers an organization to be highly efficient when 75% of their donations go to the beneficiary. By comparison, 96% of GameChanger’s donations and money make it to the patients and their families.

In the nine years since they were founded, GameChanger has:

  • Met and helped 10,000 kids dealing with life-threatening illnesses
  • Raised over $200,000 towards finding a cancer cure
  • Donated over 20,000 video games to hospitals, children centers, partner charities and families
  • Awarded 57 character-based college scholarships to cancer survivors and other inspiring young role models who battled through adversity
IMG_4386

GameChanger founder, Jim Carol, with one of the youngest, and bravest, kids the charity organization has ever met.

Can video games actually help children survive life-threatening diseases?

A 2012 study from the University of Utah suggests that not only can video games help patients with cancer and other diseases to cope, they can actually have health-related benefits.

This research is in line with what GameChangers have experienced with so many of the children they’ve helped. For example, when the organization brought a game to toddler, Christian, who was waiting for a heart transplant at Seattle Children’s Hospital, the impact was evident.

According to his mother, up until then, Christian had been listless and barely had had the energy to sit up. The game had an immediate effect.

“He started sitting up for longer and longer each day, and he learned how to use the Xbox controller and play on his own,” Christian’s mother says. “He has more energy because of how his lungs and failing heart work when he’s sitting up. His occupational therapist is thrilled because of how he’s learning to use the controller.”

In 2016, as a part of the Gamers Give Back tour, GameChanger will meet 8,000 kids like Christian with life-threatening diseases. They will help the children and their families get through some of the most difficult challenges imaginable in life.

Learn more about GameChanger and the various ways you can help:

Make an online donation that goes directly to the cause

Send excess or obsolete electronics inventory to the charity

Schedule a pickup to donate video games, consoles and gear to the kids

 

August 18

plasticnotifier - a small tool to watch repos and show desktop notifications with new csets

Today we released plasticnotifier, a small utility to monitor Plastic SCM repositories and notify about new changesets on the Windows Desktop using “toast notifications”.

We published the code and binaries on GitHub so feel free to download it, use it and of course modify it for your own needs :-).

Continuous Integration for Android with Visual Studio Team Services

Commonly referred to as VSTS, Visual Studio Team Services is a developer’s dream, with tools for every step of development, including planning, building, testing, releasing, and insights for your application. Developers can pick just one service or utilize all of the tools in VSTS for their full DevOps pipeline. As I’m developing applications, it’s important that as soon as I push code to my repository that my application is built, tests are run, and it’s ready for deployment. VSTS has the perfect tools to build Xamarin applications in the cloud, and today we’ll take a look at building a Xamarin.Android application in the cloud.

AnyADeveloperAnyLanguage

Create Your Account

Before we begin, it’s required to create a new account at visualstudio.com and select a VSTS account name under which multiple projects can be created. If you already have an account, simply sign in and select an existing VSTS account or create a new one. During this step it’s possible to create a private code repository with a Git or Team Foundation Version Control for source control. These private repositories are a great option as they are completely free and unlimited, but it’s also possible to connect to an existing Git or on premise Team Foundation service for Continuous Integration.

Acreate account

With the account created, we will be redirected to our team overview page, where a new project has been created automatically. If you already had an account, simply add a new project.

Connecting to Code

If you’re hosting your application inside of VSTS, you can skip this step since you are ready to start automating your builds. Because we are able to connect to an existing code repository service, we can connect to GitHub to automate an existing app, Coffee Tipper. To add a service, we’ll have to go into our project settings on the top right of the page:

settings

We can add GitHub as a new service endpoint under the services tab. You’ll also find other services here such as External Git and Subversion.

new service endpoint

At this point, we can add a personal access token to authorize VSTS to talk to GitHub, or we can simply Grant Authorization by logging into GitHub.

Add GitHub

Creating the Build Definition

With GitHub connected, it’s time to create our first build definition that defines the workflow steps to build the application. Select Build at the top of our project page and then the Add button to open the Create new build definition, where we’ll find a build for Xamarin.Android.

New_Build_Definition

The next step is to select our repository source (in this case GitHub) and then a default agent queue. Think of an agent queue as a machine that will be used to pull down the source code and build the application fully. VSTS offers a hosted solution in the cloud that can be used with Xamarin.Android applications and includes 240 minutes of build time a month on a hosted build agent. It’s also possible to configure a local agent queue that’s running the VSTS agent to perform the builds on a machine of your choosing. For simplicity, we’ll select the hosted machine so there’s no further configuration needed!

AgentQueue

Configure Repository

After creating the definition, we can start adding and editing steps, but before we do, let’s finish configuring the repository that should be built under the Repository section of the build definition. Since we already connected to GitHub and selected it when creating the definition, all that’s left is to select and configure the repository:

ConfigureRepo

Configuring the Build Definition

The generated build definition has a few pre-defined steps that most Xamarin.Android applications need in order to be compiled, built, and signed for deployment. There are three steps that need configuration for the Xamarin License and for Xamarin Test Cloud. These can be configured later and are not required for building the application, so let’s simply right click and disable these steps so they aren’t run. If you don’t have any unit tests, the Build test can also be disabled.

Disable steps

All other steps, including restoring NuGet packages, building the Android project, and packaging the app can remain. Each step can be configured with properties specific for the step. The Build Xamarin.Android Project step allows us to configure the project to be built. By default, it will search any project that has “Droid” in the title. We can change this to point directly to the Coffee Tip Android project:

Update_property

Save and Queue Build

We’re now ready to test the build. Simply tap on Save to finalize the build definition and give it a unique name of your choosing. I’m going with Android – Release Build. Now, the Queue build… button will become enabled and we can manually queue our first build.

Just like that, our very first build is queued in the hosted agent and the build will start giving us a full readout of everything that’s happening.

AppBuilding

When the build is finished, a full build log is available and a list of artifacts that were built can be downloaded.

FInal_Build

Build with Every Commit

We manually queued this build, but to really integrate this newly created build definition into our DevOps cycle we can turn on Continuous Integration so a new build is started with each check-in. Under the Triggers section of the build definition, simply turn on Continuous Integration and configure as many or as few branch filters as you would like. By default it will only monitor for changes on the master branch.

CI

Going Further

There’s a lot more that we can do with VSTS for an Android application to get it ready for real production.

Signing with Keystore

One of the most important parts of releasing an Android application is signing it with a private keystore. VSTS can handle this easily with the built in Android Signing and Aligning step that was already added to the build definition. To use this step, we’ll need to have created a private keystore and have it accessible for the build agent. This can be accomplished by having it checked into a private repository or by downloading the keystore from secure blob storage.

To download the keystore for the build agent, we can use the command line step combined with curl, which is on the hosted agent.

AddCommandlline

Drag and drop the command line step above the sign step and set the following properties to download and copy the keystore to the root of the repository on the build agent:

Tool: c:\Program Files\Git\usr\bin\curl.exe
Arguments: -k “URL_TO_KEYSTORE” –output $(Build.SourcesDirectory)\NAME_OF_KEYSTORE.keystore

Signing_Settings

Now, we can create a private Variable for the KeystorePassword that will be encrypted for the Android Signing process. Under the Variables tab, enter the name and value of the password of the keystore and then enable the lock to encrypt it.

KeystoreVariable

Finally, specify the Jarsigner options and ensure that Zipalign is enabled for the Android APK:

SigningSettingsFinal

Continuous Deployment to HockeyApp for Testing

Everything that we’ve done so far is included in VSTS by default, but there’s an entire Marketplace for VSTS that enables developers to extend and add new functionality with new build steps. HockeyApp is a service that enables mobile app developers to easily distribute apps to testers and get feedback from them. We can install the HockeyApp VSTS extension, which will add new build steps to easily deploy to HockeyApp.

AddHockeyAPp

Just like we connected to GitHub under our projects services in settings, we can also connect to HockeyApp to specify our API Token:

AddHockeyApp_001

Back in our build steps we can add the HockeyApp step under the Deploy category:

HockeyAppStep

The last thing to do is configure the step with the connection, App ID from HockeyApp, and the APK to upload to HockeyApp.

Configure_HockeyApp

Once the build is completed, it will have been signed and shipped to HockeyApp!

InHockeyApp

Learn More

We’ve now set up full Continuous Integration and Continuous Deployment for our Xamarin.Android application in Visual Studio Team Services. With every commit, our application will be built, signed, and shipped directly to HockeyApp for testing. There’s still so much more to explore, including testing with Xamarin Test Cloud and exploring the marketplace for VSTS. Be sure to check out VSTS’ full documentation for building and distributing Xamarin applications.

The post Continuous Integration for Android with Visual Studio Team Services appeared first on Xamarin Blog.

Developing for HoloLens with the Emulator

This is a guest blog post

Hi, I’m René from IdentityMine/Valorem and a passionate developer working with 3D computer graphics. I’ve been in VR and AR for many years now. With all the amazing VR and AR/MR devices coming out, it’s a great time to be a developer working in that immersive space using Unity. As part of Microsoft’s HoloLens Agency Readiness Program, I was lucky enough to have been working on HoloLens experiences since last year and in this post I’d like to share some of the stuff we’ve done and things we learned.

My team and I are developing lots of different HoloLens apps and games for many different use cases. I can’t share all the projects we are working on but this video and the screenshots below give you a glimpse of the things we have been working on.

image03

We also recently released a little game for HoloLens called Tower Blocks. Tower Blocks was actually created by experimenting with two-handed interactions where we tried out new ways to transform holograms. We had so much fun playing it that we released it for free in the Microsoft Store.

I also shared what I’ve learned in recent talks presented and recorded at Unity’s Unite Europe event and Microsoft’s //build conference as well as a few blog posts like Getting Started with HoloLens Development and Top 10 HoloLens Development Recommendations.

A good portion of the talks and posts covered best practices and other things I learned while working on a project called HoloFlight which is a near real-time flight data visualization for HoloLens using real-world topographic and flight data showing the data in 3D as holograms instead of flat 2D plots.

The HoloLens Emulator

At IdentityMine, we had access to some HoloLens devices but not all of our team had access to them, therefore most of HoloFlight was actually developed using the HoloLens emulator and the special Unity build for HoloLens, which everyone can download for free.

HoloLens is a Windows 10 device and the HoloLens emulator runs as a Hyper-V virtual machine. You can learn more about system requirements here. The human input like gestures and other sensors are simulated using the PC’s keyboard, mouse, or Xbox controller.

Deployment

It is really easy to deploy a Unity game / app to the emulator. It just has to be built like a regular Unity app for HoloLens. Then from the Visual Studio output solution the right Platform and Target Device have to be selected from the dropdown:

image06

Emulator Input

The emulator can simulate positional changes (user walking), as well as rotational changes (user head rotating), gestures, hands and even voice commands.

Position and Rotation

The rotation can be simulated by pressing the left mouse button and moving the mouse. Positional changes can be simulated using the keyboard’s W, S, A, D and Page Up/Down keys.

Gestures and Hands

The air-tap gesture can be simulated with a right mouse button click; if the Alt key is pressed while pressing the right mouse button, the tap+hold gesture for hand scrolling movement can be simulated. The built-in bloom gestures which brings up the Windows start menu is mapped to the keyboard Windows key.

Voice and Speech Recognition

HoloLens is a Windows 10 device so it supports Microsoft’s voice-controlled assistant Cortana for speech recognition. This works well with the HoloLens emulator.

There’s More

Hand and head rotation and much more emulation features can be controlled even further. A detailed list of all simulated emulator inputs can be found here.

Spatial Mapping

Besides the fact that HoloLens is a fully untethered device, which can render holograms, another unique feature is that it constantly scans surroundings and performs a surface reconstruction providing a spatial map of the environment to your application. This feature alone is very impressive as you can see in this demo video when the virtual balls roll down in the real garden.
Of course the emulator also supports spatial mapping and, even better, it can actually load different environments / rooms to test.
These rooms can be extracted from a HoloLens device as .xef files, so you could use a HoloLens device, scan an environment, save it and then load into the emulator. For example the screenshot below shows a spatial mesh of a real-world staircase loaded into the emulator:

image01

Which is similar to this when seen through the HoloLens device:

image00

More details about the emulator and its Room feature can be found here.

Conclusion

The HoloLens toolset provides you with everything you need to get started for HoloLens development, including an amazing emulator, which is close to the real device. All of these tools are free of charge! Of course nothing comes as close to the behavior of a real device and in the end it is needed for a professional app to tune performance and UX but the emulator can provide a very good starting point. We leveraged the emulator in a distributed team to speed up development and to not be constrained by device availability, which worked out very well for us.

By the way, if you are interested in working with VR, AR and real-world HoloLens development, IdentityMine and Valorem are always looking for talented developers, designers and artists.

rzed portraitAbout author: René Schulte is the Director of Immersive Experiences at IdentityMine / Valorem Consulting. He has experience with VR, AR, MR development and 3D programming for more than 10 years and has been developing for HoloLens since 2015.

He is a frequent speaker at conferences like //build, Unite, NDC and writer of blogs about many developer topics.

René Schulte also created and maintains a few popular Windows open source libraries like WriteableBitmapEx or the Augmented Reality library SLARToolKit.  For all his community work, René Schulte was honored with the Microsoft MVP Award.

August 17

How to send Windows Toast notifications from Console apps

Toast notifications are these small panels showing up on the right side of the screen, displaying useful tips about running apps.

Creating Toasts notification is straightforward if you are coding Universal apps, but it takes a little bit more when you are on desktop or console apps.

This blogpost shows how to create Toast notifications from a C# console application. The code is available on a GitHub repo (pushed from Plastic, btw) and it runs both on W10 and W8.x.

Xamarin Developer Certification is Getting Better

Xamarin University has constantly improved and progressed since we launched almost three years ago. Today, I’d like to announce some great changes to the Xamarin Certified Developer Program. These changes not only help to keep certification high value and trusted, but also make it easier to stay certified once you’ve attained it.

First Year Certification Changes

Xamarin Certified Mobile Developer BadgeFirst of all, we’re changing core (first year) certification to be based on Xamarin.Forms. This is an important strategic shift due to the maturation of Xamarin.Forms as a platform and because most Xamarin developers turn to Xamarin.Forms first when building applications, only going platform-specific when they need to. The required classes will still include some iOS and Android content, but it will be restricted to the minimum necessary to give a comfortable introduction to the platforms. You can find a living list of the new classes required for first year certification here.

Additionally, we’re adding a more personal touch to certification: once you’ve taken 85% or more of the required certification classes, we’ll reach out to schedule a free one-on-one office hour session with your primary instructor to discuss the certification exam, answer any questions you have about preparing for it, and just generally check in to make sure you’ll be successful.

Recertification

We’re also introducing a huge change to the recertification track. Instead of a list of mandated classes, we’re transitioning to an elective model whereby you retain your certification status by studying your own choice of topics from a subset of the curriculum. There will still be a small number of high value classes that will be required, but they will remain few and strategic, and you can decide on the bulk of classes that you want to take. This means that you can tailor your education to what’s important to you and your career, while still getting important platform updates.

The best part as long as you’ve taken the required classes and your electives, and kept your Xamarin University subscription active, you’ll stay certified without taking another exam!

Effective Date

These changes will go into effect on October 15, 2016. If you’re already on your way to certification and only have a few classes left, then you have 60 days to finish up your coursework and take the current test before these changes will be applied.

We’re all excited about these changes. I think it’s both a simplification and makes certification an even greater asset. If you have any questions, don’t hesitate to reach out to us at training@xamarin.com.

The post Xamarin Developer Certification is Getting Better appeared first on Xamarin Blog.

A Look Inside: Tracking Bugs By User Pain

Continuing the Release Management Series, let’s talk about how we changed our bug prioritization system for 5.4 and why.

In recent times, we have been focusing a lot on quality. One common, though inaccurate, measurement of quality is the bug count. In the last two years, we’ve been crushing out over 11,000 bugs per year (!), but even so, we never came close to reaching zero bugs. We don’t make shrink wrapped software running on fixed hardware platforms with specifications that can be locked in. Aside from cases of our own optimizations or fixes creating new bugs, new issues arise daily. There are countless cases, some of them not even coming from our own code base.

So, the question we ask ourselves is, “Which bug do you fix first?” Unity has so many dimensions to work with, so is it fair to compare a “small platform bug” against a “editor usability bug”? Under the old system, we would track a priority, but the teams defined the priorities individually, so it was decidedly inconsistent. What is a shipstopper for one group does not make it a shipstopper for all. While some teams with larger overviews and ability to cross spaces had a consistent priority system, most did not and what was often organizational team priority was assigned at a global scope. You might see how this comes to be a release management problem.

So, in comes “user pain”. The “user pain” idea can be found in a lot of places, but the seeds for us started with another Director of Development in R&D, Erik Juhl, recalling a methodology used during his MMO days where the team would assess the risk of fixing a production bug. It went something like this:

Risk Assessment = Tech Risk + QA Risk + Business Concern + Community Impact


In that situation there was a threshold to reach in order for the whole group to believe a bug was worth fixing immediately. This worked for its purpose of “live” issues in a service and case by case analysis, but it doesn’t exactly scale to bug databases. However, the idea was something we latched on to.

Finding A Formula

With this example in mind, our release management sampled all the old priority system “Priority 1 (Drop everything now)” and “Priority 2 (Shipstopper)” bugs marked for fixing in 5.4, which amounted to some ~150 bugs at the time in mid-development.

We started with something like this:

User Pain = (5 – Severity) * IsRegression + QA Risk + Technical Risk

Here, Severity and IsRegression were information that previously existed in our bug tracking system (see below about Severity changes). “QA Risk” was an attempt to describe the risk in the ability to test the bug. “Technical Risk” was attempting to capture the complexity and “halo effect” (the likelihood the fix will influence another part of the system).

In looking at the sampling of bugs and calculated pain, the list ordering looked wrong from our perspective. Mainly, we decided to drop QA Risk & Technical Risk as they are things only for release assessment, “if we should accept a bug fix”, instead of user pain, which should represent “should I prioritize fixing this.”

So, we next refined the formula to something like:

User Pain = ((5 – severity) * (Platform Importance * Prevalence) ) * (1 + IsEnterpriseSupport + IsUpcomingPlatform) * (1+IsRegression) + IsInstability * 100 + Votes

 

We introduce a number of things here:

  • Platform Importance – to separate individual edge platforms spanning to cross platform
1 = default Single platforms, i.e. Tizen, PS4, etc.
2 = Core Platforms Desktops + iOS + Android + WebGL
3 = Editor Greater than Core Platforms, because working on making the game trumps shipping a particular platform
4 = Cross-Platform Most or all platforms
  • Prevalence to consider how widespread it is
1 = Affects few or very select users
2 = Affects some, but not majority of users
3 = Affects a majority
4 = Affects everyone
  • IsEnterpriseSupport – addressing Enterprise Support requests and their importance
  • IsUpcomingPlatform – working with various partners, this is a way to highlight issues that might need to be tracked
  • IsInstability – is a bug causing internal development slowdowns by introducing an automated test instability. While not obviously user pain, it’s indirect and very very impactful which is why it gets such a high rating. These can cause significant slowdowns that impact how much we can fix or improve quickly.
  • Vote – a simple vote counter collection from the Issue Tracker

This formula gave a nice spread of bugs that seemed to properly give weight to appropriate bugs, and we worked with this idea for a while. Over time we made the following adjustments:

  • IsUpcomingPlatform was dropped, as it would carry excessive weight beyond the life of the initial release. Plus it was expected that the team in charge of the platform would be owning, raising concern and chasing these bugs.
  • IsEnterpriseSupport was dropped. This was in recognition that the Enterprise Support team in conjunction with our Sustained Engineering were already on top of these marked bugs. We were running into each other looking at the same bugs with extra engineers now looking at bugs that someone was already working on.
  • “Release Manager” tag was added to give weight to items like Known Issues or other items showing up lower in the ranks that were of high importance to users, but scoring did not reflect so.

So now we’ve arrived at:

User Pain = ((5 – severity) * (Platform Importance * Prevalence) ) * (1+IsRegression) * (1 + RelMgr) + IsInstability * 100 + Votes

We started with a threshold of 54, on the basis of:

  • Severity (Major functionality impacted) >= 2
  • Platform Importance (at least Editor) >= 3
  • User Prevalence (Majority) >= 3
  • Is Regression (True) = 1

However once we went on and removed the Enterprise weighting, we dropped the threshold to 48 by arbitrary inspection. This is the current state of things, but we recognize it’s a living idea and may change over time.

The one other adjustment was made that our Severity classification was somewhat broken. It would allow minor issues to trump functional issues on the basis of “no workaround available.” Here’s the shift of mapping we decided to implement along side of things:

Severity Old New
1 Crash or major loss of functionality Crash, freeze, data loss or work stops
2 No workaround Core functionality majorly impacted
3 Workaround is possible Secondary functionality broken
4 Minor or cosmetic issue Minor or cosmetic issue

Adoption

Across R&D there’s been appreciation of the new approach. Many teams have adopted it and are quite pleased thus far. QA members and release management have gone through lots of the existing bugs to assign appropriate values for the newer variables we had to add.

With the adoption of this process, people are starting to step away from the old priority mechanisms and view the bugs in light of how they impact the users.

image00

What’s interesting about the graph above, is that painful bugs still counted for less than our per team assessments of priorities. The “Pain” line grew because we expanded scope of bugs being assessed far beyond 5.4 P1 + P2. It eventually encompassed any bug listed from the past 5.0 to the future 5.5 (5.x) for all old prioritizations of P1 – P3, plus our bug triage queue. The numbers still were less than the “high priority bugs” of our past weighting. Part of the up and down was the incorporation of 5.3 items and then dropping of the IsEnterpriseSupport bugs which already had coverage.

Thus far, what we’re tracking with user pain plus a couple other items like upgrade issues is showing to be largely the main user concerns.The current feeling about the release is fairly positive without correlating as strongly to the number of P1s and P2s.

Future

So, what’s next for the “user pain” system?

Well, currently it’s a fairly manual analysis for us, and not fully integrated into our bug system. Also, we need to take a pass at all the older bugs that haven’t been assessed for platform importance and prevalence.

Additionally, we still know there’s tweaking to the formula to consider. We may have missed some aspects to include or are still giving a lot of weight to area we shouldn’t. Also, there’s a great benefit to being able to change the formulas when needed, so it better reflects the issues of the moment. We know that the pain index is not an absolute measurement, but guidance to help show how we might consider prioritization.

Lastly, we’ve started experimenting with the idea across other areas including the release risks for acceptance of fixes during RC/patch. We’re also thinking how this might be useful to prioritize features or re-factors.

It’s all still an experiment and thus far current results and perception is that a more unified system of prioritizing is helping. We’ll continue the experiment forward and update you some time in the future on how things keep going.

For the next round, we’ll talk about some internal tooling changes.

August 16

“Document All the Things” Contest Winners

At the heart of Xamarin has always been a desire to empower developers to create great mobile apps, and this goal includes fostering an active developer community. For this reason, we were very excited when Stack Overflow announced a new documentation feature enabling experts within the community to write documentation to share their knowledge with their fellow developers. We were so excited, in fact, that we launched a contest asking members of the .NET community to contribute Xamarin documentation to the new portal.

The response to the contest from our community was amazing, and the Xamarin documentation on Stack Overflow is already growing, which means it’s time to announce the winners of our Stack Overflow Documentation contest!

Contest Winners

The following randomly-selected winners can select a choice of a Microsoft Band, Apple TV, or Azure IoT Starter Kit.

Thank you to everyone who entered this contest and to those contributing to the documentation portal on Stack Overflow. We’ll be reaching out to the winners via Direct Message on Twitter, so please be sure to follow @XamarinHQ!

The post “Document All the Things” Contest Winners appeared first on Xamarin Blog.

August 15

Webinar Recording | Continuous Everything: Why You Need Mobile DevOps

Whether you’re a mobile-only startup looking to turn early adopters into evangelists or a multi-million dollar enterprise mobilizing your workforce, you need to ship the right apps, to the right customer, at the right time. You need users to use your apps, turning downloaders into engaged users. To win mobile users’ loyalty, you have to continuously ship high quality software and continuously listen and learn from your users, giving them features before they know they want them. Mobile isn’t just build, release, and done; it’s a continuous cycle of designing, coding, testing, releasing, monitoring, fixing, and improvement. With the right mobile DevOps processes and the right technology, this “continuous everything” is within reach for any organization and all developers.

In this webinar, Xamarin VP of Product Keith Ballinger discusses:

  • What he learned from his failed startup experience and how you can sidestep common pitfalls to beat your competition
  • How to balance shipping high quality software with speed to market
  • Why agile isn’t enough and how mobile DevOps allows you to release faster
  • How to listen to your users, collect feedback, and prioritize new features to ship better apps
  • How Xamarin Test Cloud and HockeyApp can help any organization get started with mobile DevOps and continuous everything

 

 

The post Webinar Recording | Continuous Everything: Why You Need Mobile DevOps appeared first on Xamarin Blog.

August 12

Xamarin Dev Days: More Dates & More Cities!

With dozens of cities already announced, Xamarin Dev Days are active around the globe and we’re ready to announce even more cities all around the world! Come join your mobile developer community, brought to you by your local user groups and community leaders, for a full day of hands-on learning and training on how to build, test, and monitor native iOS, Android, and Windows apps with Xamarin.

XDD Redmond Photo

What are Dev Days?

XDD AgendaXamarin Dev Days are community run, hands-on learning experiences. More than just your average meetup, they are FREE, day-long events focused around learning how to deliver native iOS, Android, and Windows apps using existing skills, teams, and code.

After a morning of learning how to build beautiful, cloud-connected mobile apps with Xamarin, you’ll get a chance to put your new knowledge into practice with a hands-on workshop that walks you through the process of building your first cloud-connected, cross-platform mobile app. Xamarin experts will be there to help you get up and running, debug code, and answer any questions you may have.

 

New Xamarin Dev Days Cities!

9/10: Orlando, FL
9/17: Genk, Belgium
9/17: Prague, Czech Republic
9/23: Johannesburg, South Africa
9/24: Karachi, Pakistan
9/24: Warsaw, Poland
9/24: Santo Domingo, Domincan Republic
9/30: Cape Town, South Africa
10/1: Milwaukee, WI
10/1: Detroit, MI
10/1: Raleigh, NC
10/22: Miami, FL
10/22: Sante Fe, Argentina
10/24: Barcelona, Spain
10/28: Zurich, Switzerland
10/29: Munich, Germany
11/05: Singapore
11/05: Istanbul, Turkey
11/18: Rome, Italy

Use the map below to find an event near you or head over to our Xamarin Dev Days website for a full list of current Xamarin Dev Days cities around the world.

 

Get Xamarin Dev Days in Your City

If you didn’t see a city near you on the map but are interested in organizing an event locally, apply as a Xamarin Dev Days host! We’ll provide you with everything you need for a fantastic Dev Days event in your town, including all of the speaker content and lab walkthrough, a hosting checklist, and swag goodies to give away to all of your attendees.

Sponsoring Xamarin Dev Days

We’re working with tons of Xamarin Partners and community members’ companies around the world to help facilitate Xamarin Dev Days. If your company is interested in participating, apply to be a sponsor and get global recognition as a Xamarin Dev Days contributor, as well as access to our worldwide developer community.

The post Xamarin Dev Days: More Dates & More Cities! appeared first on Xamarin Blog.

Unity & OGA Partner to Increase Speaker Diversity

We are happy to announce the launch of a speaker database and event resource WISER – Women in Software & Entertainment Representation.

The goal of WISER is to shift the conversation — from getting (and keeping) women in gaming and entertainment to normalizing their very presence by increasing visibility and representation at events and on industry stages. This doesn’t mean women speaking about being a woman in the industry; it means encouraging and enabling women to be on stage speaking about their specific area of expertise.

WISER is a collective of peer-endorsed female professionals in gaming and software available for speaking and public appearances. These are experts in everything from product management to engineering and design, independent creators and leaders at companies.

We’re kicking off the project today and want you to take part. Interested in participating? Tell us about yourself. Know someone who’d be great? Pass this along! Trans and non-binary welcome too!

How it works:

Interested in Speaking?

  • If you’re interested in speaking at industry events and conferences please visit WISER and fill out the registration form.
  • Your background will then be vetted and you’ll be notified if you’re added to the database
  • Your information will not be sold, or shared beyond this purpose

Looking for a Speaker?

  • Access to the database will be limited to approved and vetted individuals. Please contact Wanda Meloni to request access.

Screen Shot 2016-08-10 at 3.43.19 PM

August 11

Authenticating Mobile Apps with Azure Active Directory B2C

Identity is a critical component of every mobile app, but it’s also tricky to get right. As developers, we have many different options in terms of authentication. Creating our own identity solution (with username/password or email/password combinations) is one approach. However, this also means that we must handle password reset and 2 Factor Authentication (2FA), not to mention ensuring that our solution is securely storing and handling user credentials. Utilizing social accounts has grown in popularity in recent years, but it’s not uncommon for users to not have accounts with the social providers you support; some users are also wary of privacy concerns with granting applications social permissions.

Azure Active Directory B2C allows developers to authenticate users with a single identity management solution that supports both social providers (Facebook, Google, Amazon, LinkedIn) as well as local accounts (username/password or email/password combinations). As developers, we can focus on building great cross-platform mobile apps without having to worry about the pains that come with identity management (scalability, sign in, sign up, password reset, 2FA, etc.), while still building a flexible solution that works for all of our users, whether they prefer authenticating with local accounts or social providers.

In this blog post, you’ll learn how to use Azure Active Directory B2C to authenticate users in your mobile apps and even add a cool “advanced” identity management feature like 2FA.

Creating an Azure AD B2C Tenant

Azure Active Directory B2C is completely cloud-based, which allows it to scale to hundreds of millions of consumer identities. To get started, you will need to have an Azure account. Azure B2C is currently available free of charge, so you shouldn’t incur any costs with using Azure B2C at this time. Once you’ve created an Azure account, we’re ready to get started creating an Azure B2C tenant.

1. Create an Azure B2C Tenant

Visit portal.azure.com and click New -> Security + Identity -> Active Directory. A new window will open in the Azure classic portal where we’ll create our Azure B2C tenant.

Creates an Azure Active Directory B2C instance from the new Azure Portal.

Enter a Name, Domain Name, and Country or Region for your tenant. Be sure to check the option that says This is a B2C directory. Click the checkmark in the lower righthand corner to create your Azure Active Directory B2C tenant.

Note: Azure B2C is only generally available in North America at this time. You may experience issues creating Azure B2C tenants in countries outside this region.

Create a Azure B2C directory in the classic Azure Portal.

When your tenant finishes deployment, click the tenant name, followed by the Configure tab, and click Manage B2C Settings.

Opens up B2C settings in the new Azure Portal for easy management.

This will open up the new Azure Portal for easier management of our Azure B2C tenant. Click the pin icon to pin the settings to your Azure Dashboard for easy management.

Pins Azure B2C tenant settings to the Azure Dashboard.

You’ve just created your first Azure AD B2C tenant! At this time, you can use the classic portal to manage users and groups, configure password reset, and enable company branding features. The new Azure Portal can be used for settings management and application creation.

2. Register Application

It’s time to register an application with the tenant we just created! This will allow our application to authenticate users using Azure AD B2C. In the settings for your B2C tenant (which you have pinned to the Azure Dashboard), click Settings, Applications, then Add. Enter an Application Name, select Yes for Include Native Client, and click Create.

Create an application that will authenticate with this B2C tenant.

After the application is successfully created, click on the app name and copy the Application Id field for later user.

Copy the Application ID for the the B2C tenant app you just created.

3. Create a Sign-Up/Sign-In Policy

Policies in Azure AD B2C describe a consumer identity experience, such as sign-up, sign-in, or editing a profile. Each policy type has options that we as developers can configure to achieve our ideal identity experience with options like supported account types, attributes to be collected during sign-up, use of 2FA, login page user interface, as well as the information our stored in authentication tokens for use in our apps. We can create multiple policies, but for this app, we will just create one that handles user sign-up and sign-in flows.

In the Settings for your Azure AD B2C tenant, click Sign-up or sign-in policies, Add, and enter a Name for the policy.

Add a sign-up or sign-in policy to our tenant.

For this application, we will be using local accounts to authenticate users. On the Add Policy blade, click Identity providers, select Email sign-up, and click OK. Let’s collect some information from our user at sign-up. Click Select sign-up attributes, select the user information to collect, and click OK.

Select sign-up attributes for our B2C tenant.

We want this information to be available for usage in the app, so we need to click the Select application claims blade, click the information to include in our authentication token, and click OK. One claim you want to be sure to grab is the Object Id, as this is the unique identifier for an authenticated user. Try to keep the number of claims minimal, and only select claims that were selected in the sign-up attributes blade. You can always request this information later using the Microsoft Graph API.

Enabling 2 Factor Authentication is as easy as clicking the Multifactor authentication setting and changing the setting to On.

Click Create and our sign-in or sign-up policy will be created! Be sure to note the name of the policy after creation (e.x.: B2C_1_SignInSignUp). In just a few clicks and without writing any code, we just added identity management to our app, complete with 2FA!

Authenticating iOS, Android, and Windows Apps with Azure AD B2C

Now that all the server-side configuration is completed on our tenant, let’s use Azure AD B2C to authenticate users! For authentication, we will be using a library named Microsoft Authentication Library, or MSAL. This library makes it extremely easy to authenticate users using Azure AD, Azure AD B2C, or Microsoft accounts as identity providers in a single library. If you are familiar with ADAL, MSAL will feel right at home. As a convenience, the MSAL NuGet has been already added to each project in the solution. MSAL does not support Windows Phone 8.1, so PCLs will need to remove this target in order to use MSAL.

1. Create an Authentication Client

Download the starter code, which contains some boilerplate code and a login screen, and open App.cs. Enter your Client Id and Policy Name from earlier into the corresponding fields. MSAL will use these to provide the correct authentication flow to the user. We have also created a PublicClientApplication and passed in our Client Id, which is the main class in MSAL for authenticating users.

Open up AppDelegate.cs in the iOS project and MainActivity.cs in the Android project. MSAL requires that we set the PlatformParameters property of the PublicClientApplication for iOS and Android. This helps to assist the library in presenting a native web view for users to sign-up or sign-in with, and is required when using MSAL.

2. Authenticate Users

Now that we have successfully created an authentication client, let’s use it to log the user in. Open up the LoginPage.xaml.cs file. When the user clicks the button to log in, the event handler LoginButton_Clicked will execute. Under the comment Step #2, add a call to AcquireTokenAsync to authenticate users.

// Authenticate users with Microsoft Authentication Library (MSAL).
var authenticationResult = await App.AuthenticationClient.AcquireTokenAsync(App.Scopes,
    "",
    UiOptions.SelectAccount,
    string.Empty,
    null,
    App.Authority,
    App.SignUpSignInPolicy);
// Navigate users into the main portion of our app.
await Navigation.PushAsync(new AuthenticationSuccessfulPage(authenticationResult));

This will present a web view to the user. If the user has an account, he can log in; if not, he can create an account using this flow. It’s worth noting that you don’t have to use a web view for authentication; you may create your own user interface for this flow and pass the information back to MSAL.

After successful login, users are taken to the main portion of the application, AuthenticationSuccessfulPage. Because we are now authenticated, we have access to the authentication token, as well as information like the user id. Let’s display that information to the user by adding the following code under the Step #3 comment in AuthenticationSuccessfulPage.xaml.cs.

UserId = $"User Id: {authenticationResult.User.UniqueId}";
ExpiresOn = $"Token Expires {authenticationResult.ExpiresOn.ToString()}";

3. Re-authenticate Users Silently

Authentication tokens only last for a short period of time, and we want to ensure that users can seamlessly use our application without having to re-authenticate. The MSAL library has a great method named AcquireTokenSilently, which will attempt to refresh the user token without requiring the user to log back in. Under the Step #4 comment in the AuthenticationSuccesfulPage.xaml.cs file, add the following code to refresh the user’s token.

await App.AuthenticationClient.AcquireTokenSilentAsync(App.Scopes,
    string.Empty,
    App.Authority,
    App.SignUpSignInPolicy,
    false);

In the event that we’re unable to successfully refresh the token, we present the LoginPage to the user to re-authenticate.

Build the app, and you’ll see a rich sign up and sign in experience with local accounts powered by Azure Active Directory B2C. Users signing up are prompted to verify their email address with a code, create strong passwords, enter information we asked for in our policy, and even verify their phone number for 2FA. Users signing in will be required to enter their credentials as well as enter the code that Azure Active Directory B2C automatically texts the user to authenticate with for maximum security, without any additional effort required from you.

 

 

Wrapping Up

Azure Active Directory B2C is a robust, scalable single identity management solution capable of handling both local and social accounts. In this blog post, we used Azure AD B2C to authenticate users in our mobile apps for iOS, Android, and Windows, and even took advantage of some “advanced” identity management features such as 2 Factor Authentication. To learn more about Azure Active Directory B2C, visit the documentation portal or download my sample on using Azure AD B2C to authenticate users in Xamarin apps.

The post Authenticating Mobile Apps with Azure Active Directory B2C appeared first on Xamarin Blog.

IL2CPP Optimizations: Avoid Boxing

In this final episode of our IL2CPP micro-optimization miniseries, we’ll explore the high cost of something called “boxing”, and we’ll see how IL2CPP can avoid it when it is done unnecessarily.

Heap allocations are slow

Like many programming languages, C# allows the memory for objects to be allocated on the stack (a small, “fast”, scope-specific, block of memory) or the heap (a large, “slow”, global block of memory). Usually allocating space for an object on the heap is much more expensive than allocating space on the stack. It also involves tracking that allocated memory in the garbage collector, which has an additional cost. So we try to avoid heap allocations where possible.

C# lets us do this by separating types into value types (which can be allocated on the stack), and reference types (which must be allocated on the heap). Types like int and float are value types, string and object are reference types. User-defined value types use the struct keyword. User-defined reference types use the class keyword. Note that a value type can never hold a the value null. In C#, the null value can only be assigned to reference types. Keep this distinction in mind as we continue.

Being good performance citizens, we try to avoid heap allocations unless they are necessary. But sometimes we need to convert a value type on the stack into a reference type on the heap. This process is called boxing. Boxing:

  1. Allocates space on the heap
  2. Informs the garbage collector about the new object
  3. Copies the data from the value type object into the new reference type object

Ugh, let’s add boxing to our list of things to avoid!

That pesky compiler

Suppose we are happily writing code, avoiding unnecessary heap allocations and boxing. Maybe we have some trees for our world, and each has a size which scales with its age:

interface HasSize {
   int CalculateSize();
}

struct Tree : HasSize {
   private int years;
   public Tree(int age) {
       years = age;
   }

   public int CalculateSize() {
       return years*3;
   }
}

Elsewhere in our code, we have this convenient method to sum up the size of many things (including possibly Tree objects):

public static int TotalSize<T>(params T[] things) where T : HasSize
{
   var total = 0;
   for (var i = 0; i < things.Length; ++i)
       if (things[i] != null)
           total += things[i].CalculateSize();
   return total;
}

This looks safe enough, but let’s peer into a little bit of the Intermediate Language (IL) code that the C# compiler generates:

// This is the start of the for loop

// Load the array
IL_0009: ldarg.0
// Load the current index
IL_000a: ldloc.1
// Load element at the current index
IL_000b: ldelem.any !!T
// What is this box call doing in here?!?
// (Hint: see the null check in the C# code)
IL_0010: box !!T
IL_0015: brfalse IL_002f

// Set up the arguments for the method and it call
IL_001a: ldloc.0
IL_001b: ldarg.0
IL_001c: ldloc.1
IL_001d: ldelema !!T
IL_0022: constrained. !!T
IL_0028: callvirt instance int32 Unity.IL2CPP.IntegrationTests.Tests.ValueTypeTests.ValueTypeTests/
                                   IHasSize::CalculateSize()

IL_002f: // Do the next loop iteration...

The C# compiler has implemented the if (things[i] != null) check using boxing! If the type T is already a reference type, then the box opcode is pretty cheap – it just returns the existing pointer to the array element. But if type T is a value type (like our Tree type), then that box opcode is very costly. Of course, value types can never be null, so why do we need to implement the check in the first place? And what if we need to compute the size of one hundred Tree objects, or maybe one thousand Tree objects? That unnecessary boxing will quickly become very important.

The fastest code is anything you don’t execute

The C# compiler needs to provide a general implementation that works for any possible type T, so it is stuck with this slower code. But a compiler like IL2CPP can be a bit more aggressive when it generates code that will be executed and when it doesn’t generate the code that won’t!

IL2CPP will create an implementation of The TotalSize<T> method specifically for the case where T is a Tree. the IL code above looks like this in generated C++ code:

IL_0009:

// Load the array
TreeU5BU5D_t4162282477* L_0 = ___things0;
// Load the current index
int32_t L_1 = V_1;
NullCheck(L_0);
IL2CPP_ARRAY_BOUNDS_CHECK(L_0, L_1);
int32_t L_2 = L_1;
// Load the element at the current index
Tree_t1533456772  L_3 = (L_0)->GetAt(static_cast<il2cpp_array_size_t>(L_2));

// Look Ma, no box and no branch!

// Set up the arguments for the method and it call
int32_t L_4 = V_0;
TreeU5BU5D_t4162282477* L_5 = ___things0;
int32_t L_6 = V_1;
NullCheck(L_5);
IL2CPP_ARRAY_BOUNDS_CHECK(L_5, L_6);
int32_t L_7 = Tree_CalculateSize_m1657788316((Tree_t1533456772 *)(
                (L_5)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_6))), /*hidden argument*/NULL);

// Do the next loop iteration...

IL2CPP recognized that the box opcode is unnecessary for a value type, because we can prove ahead of time that a value type object will never be null. In a tight loop, this removal of an unnecessary allocation and copy of data can have a significant positive impact on performance.

Wrapping up

As with the other micro-optimizations discussed in this series, this one is a common optimization for .NET code generators. All of the scripting backends used by Unity currently perform this optimization for you, so you can get back to writing your code.

We hope you have enjoyed this miniseries about micro-optimizations. As we continue to improve the code generators and runtimes used by Unity, we’ll offer more insight into the micro-optimizations that go on behind the scenes.

Monologue

Monologue is a window into the world, work, and lives of the community members and developers that make up the Mono Project, which is a free cross-platform development environment used primarily on Linux.

If you would rather follow Monologue using a newsreader, we provide the following feed:

RSS 2.0 Feed

Monologue is powered by Mono and the Monologue software.

Bloggers