August 18, 2015

Using Auto Layouts for iOS 9 SplitView

By

The official launch of iOS 9 is on the horizon, which makes it a great time to ensure your Xamarin.iOS app is ready to take advantage of all of the upcoming features. One that I’m excited about is the new and improved multi-tasking experience on the iPad. With iOS 9, it’s possible to run two apps side-by-side in a split view on the iPad. This means that your app can’t assume that it’s going to have the device’s full resources, or, more importantly, the entire screen. If you already use Auto Layouts for your apps, then you’re all set to take advantage of split view on the iPad, but if your app is using the older layout option of Autoresizing, you’ll want to transition to Auto Layouts as soon as possible to make sure you’re ready for the change.

iOS 9 Split View Multitasking

Getting Started with Auto Layouts

Auto Layout for iOS is an extremely powerful layout system that allows you to create complex relationships between controls and how they should respond to changes in screen size or orientation. Let’s take a look at how you can take an existing Autoresizing layout and convert it to Auto Layout. Below is my simple iPad layout, which uses Autoresizing.

Screen Shot 2015-08-13 at 16.29.08This is how we want our app to look when Auto Layouts is switched on. To turn Auto Layouts on, we’ll first need to click on the canvas behind our view controllers. This will allow access to the Storyboard Document Inspector, as you can see in the right hand side of the above screenshot.

Select ‘Use Auto Layouts’. When you do this you’ll notice two extra buttons appear in the toolbar. These are adding and removing constraints from our controls. Now that Auto Layouts is enabled, we can begin to define our layout relationships between controls. We’ll begin with configuring the layout for the title. The key to successfully mastering Auto Layouts is understanding that you’re providing rules for width, height, and X and Y positions. If you don’t provide these four pieces of information per control, your layout won’t work. When you double click the ‘My Amazing App!’ label, you’ll see controls that look similar to “Ts” appear on the edges. Screen Shot 2015-08-13 at 16.37.30

We can drag these controls to form connections. In the example below, I’m defining the Y-value of the control relationship to the top of the view controller.

Screen Shot 2015-08-13 at 16.38.36

Dragging the square in the center of the label allows us to set its X position as the middle of the view. I can click the control on the bottom and right of the Ts to fix the height and width of the label. If you’ve done this successfully, you’ll see the Auto Layout guides change from orange (to indicate an issue) to blue.

Screen Shot 2015-08-13 at 16.42.18

If you repeat the process for the bottom button by fixing the height and drawing lines to the left button and right edges, you should be able to rotate the UI and see both the label and the button resize correctly.

Screen Shot 2015-08-13 at 16.48.51

Finishing Up

Hopefully this post has demonstrated that using Auto Layouts is straight forward and not as complex as you might have initially thought. If you’re looking for advanced examples or more in-depth understanding of how to utilize Auto Layouts, make sure to check out our documentation.

Remember, its not long before iPad users will expect your app to work with Split View, so make sure you’re ready today!

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 17, 2015

Free Xamarin Subscriptions for Windows Phone Developers

By

Xamarin developers have been coding the dream: crafting a single, shared codebase to target the multi-device world we live in. Here at Xamarin, we’re excited about the recent release of the Universal Windows Platform, and we know that both Xamarin and Windows Phone developers are excited about the improvements introduced in Windows 10.

Xamarin Heart Windows

To help usher in this new era, Xamarin would like to welcome Windows Phone developers to the family with a special offer this August:

Free, community-supported subscriptions of Xamarin.iOS and Xamarin.Android, including our Visual Studio extensions, for personal use.

If you’re a published independent Windows Phone developer and haven’t taken the plunge into native, cross-platform mobile development with C#, there has never been a better time than now to get started. To apply, simply fill out this short form sharing the details of your Windows Phone app published on or before August 17th, 2015:

Apply Now

This offer is limited to independent Windows Phone developers, so no more than one subscription will be granted to any given publisher. Don’t delay! This offer expires August 31st, 2015.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 14, 2015

Xamarin Podcast: MVVM Frameworks with James Montemagno

By

Deciding which patterns to use when developing your app can be difficult, which is why James Montemagno and I discuss MVVM frameworks and our approach to developing cross-platform apps with as much code reuse as possible on this week’s episode of the Xamarin Podcast.

Subscribe or Download Today

Knowing the latest in .NET, C#, and Xamarin is easier than ever with the Xamarin Podcast, available via iTunes, Stitcher, 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 MVVM frameworks, and don’t forget to subscribe!

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 12, 2015

Xamarin.UITest Reaches 1.0 Release

By

First impressions for your app are important. A good experience can create ambassadors who encourage their peers to download the app, while a bug or slow load times can make users abandon immediately to find an alternative.

We created Xamarin Test Cloud to help developers make apps that users love by providing a comprehensive testing framework integrated with the most comprehensive inventory of iOS and Android devices in the industry. With over 1,700 devices (and counting) running a variety of operating system versions, Xamarin Test Cloud ensures your apps work across the entire ecosystem of mobile devices.

Xamarin Test Cloud Dashboard

Today we’re pleased to announce Xamarin.UITest 1.0, our C# and NUnit-based test automation framework that powers these tests in Xamarin Test Cloud to test any mobile app – not just those built with Xamarin. You can also author tests in Ruby with the Calabash framework, and we recently announced support for the Appium framework.

We’ve introduced some great new features in Xamarin.UITest 1.0, summarized below. Glenn Wester, one of our Customer Success Engineers, also put together a short video on how to use these improvements to make your test authoring faster and easier so you can make sure your users are getting a high-quality app.

New Features

Xamarin.UITest lets you programmatically re-create complex user interactions and data-entry that would happen to your mobile app in the real world. Some of the notable new features in the 1.0 release include:

Recreating a New Install Experience

A flawless first-run experience is often the difference between customer loyalty and app abandonment. UITest 1.0 now includes app lifecycle modes to easily reset the state of the app during tests to make sure app install and first-run experiences are thoroughly tested.

AppDataMode.Clear (default), and AppDataMode.DoNotClear functions are now available to either reset the app back to a fresh installation on the device, or to resume tests in its current state.

Improved Scrolling Support

Support for additional scrolling operations are now supported for reaching elements that are on the page but not visible on the screen. In real life, this would require a user to scroll up or down with with a finger swipe.

These new functions can simulate a swipe or reaching a specific page element or page region, like ScrollTo and ScrollToVerticalEnd.

Behavior-Driven Development (BDD) Testing With SpecFlow

Integration with SpecFlow is now supported, enabling Cucumber BDD testing with the .NET Framework.

Shortcuts and Helper Functions

In addition to overall usability and stability improvements to the UITest framework, NuGet packages, and integration with Xamarin Test Cloud, test authoring is also simpler with short-hand overrides on all query and gesture methods.

For example, instead of writing ‘Query(x => x.Marked(“MyButton”))’, the override ‘Query(“MyButton”)’ accomplishes the same thing.

Get Started

Our developer docs have great tutorials on getting started with Xamarin.UITest, and all Xamarin customers get 60 minutes of Xamarin Test Cloud device time per month, so start testing your mobile apps by visiting testcloud.xamarin.com today!

On August 26, 2015 at 8:30 am PT we’re hosting a webinar on Xamarin Test Cloud and how to take advantage of Xamarin.UITest 1.0 to incorporate testing into your overall development process and create great mobile apps. Sign up here.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 11, 2015

Visualize Your Data with Charts, Graphs, and Xamarin.Forms

By

There’s even more to Xamarin.Forms than the 40+ pages, layouts, and controls that make it fast and easy to build native apps while sharing 90%+ code across platforms. With Xamarin.Forms’ custom renderer capability, you can extend Xamarin.Forms to gain access to every native control in iOS, Android, and Windows and even create your own custom controls. Nexus 4 (Lollipop) Xamarin.Forms Screenshot In addition to the ever-growing Xamarin.Forms ecosystem of open source Plugins, we also announced partnerships with leading control vendors at Xamarin Evolve 2014, bringing their 140+ components to Xamarin.Forms (check out a recap here). Recently, for instance, I found myself in need of a beautiful cross-platform chart control for Meetup Manager and Syncfusion Essential Studio was a perfect match.

syncfusion@2x

Syncfusion Essential Studio not only provides the charts that I need for Meetup Manager, but also a range of other components, such as Gauges, Barcodes, PDF readers, Notifications, and more. Today, I’m going to focus on the Essential Chart’s Stacking Column Series, which allows me to include a nice visual chart for group organizers and show them their group’s check-in performance over time.

Forming Data Structure

For background, Meetup Manager enables user group leaders to check their members in at events and add any unregistered guests that might show up. With this in mind, I created a simple data structure that I could bind to the chart with check-ins, guest check-ins, and the data to display:

public class DataPoint
{
  public string Date { get; set; }
  public int CheckIns { get; set; }
  public int Guests { get; set; }
}

Since I’ll be using data binding for the chart, I added an ObservableCollection of DataPoints. In my XAML page, I need to create a new instance of StatsViewModel and set it to the page’s BindingContext. This will enable the chart to see the new collection.

public class StatsViewModel
{
  public ObservableCollection<DataPoint> CheckInData { get; set; }
  public StatsViewModel()
  {
    CheckInData = new ObservableCollection<DataPoint>();
  }
}

Getting Started with Syncfusion

With my data structure and view model in place, it’s time to actually add the chart to the statistics page. Simply head over to the Xamarin Component Store and download the free trial of Syncfusion Essential Studio. You can also browse the Component Store straight from Xamarin Studio or Visual Studio to add Essential Studio directly to your iOS and Android apps.

Syncfusion Component Xamarin

After downloading the Component, you’ll want to ensure the following references have been added to each project and add a bit of initialization code.

iOS

lib/ios-unified/Syncfusion.SfChart.iOS.dll
lib/ios-unified/Syncfusion.SfChart.XForms.dll
lib/ios-unified/Syncfusion.SfChart.XForms.iOS.dll

Add new SfChartRenderer(); in the AppDelegate.cs after Forms.Init();.

Android

lib/android/Syncfusion.SfChart.Android.dll
lib/android/Syncfusion.SfChart.XForms.dll
lib/android/Syncfusion.SfChart.XForms.Android.dll

Add new SfChartRenderer(); in the MainActivity.cs after Forms.Init (this, bundle);.

Portable Class Library

lib/pcl/Syncfusion.SfChart.XForms.dll

Finally, I can add the base of the chart to my Xamarin.Forms statistics XAML page by adding a new xmlns to point to the Syncfusion library. This enables Xamarin.Forms to locate the custom controls library.

xmlns:chart="clr-namespace:Syncfusion.SfChart.XForms;assembly=Syncfusion.SfChart.XForms"

I reference the base of the chart inside the XAML page’s Content:

<chart:SfChart x:Name="Chart">
</chart>

Notice the chart prefix that comes from the xmlns specified earlier.

Building the Chart Components

With the base of the chart in place, we can now integrate our data and generate a display, but first we need to wire up and add a few key components under the root of the chart.

Primary Axis

This axis runs along the bottom of the chart and, for Meetup Manager, will display the dates for each event. We can select from several axis choices that tell the chart how to render the data. I have selected the CategoryAxis, used to display a string, and I rotated it -45 degrees to give my chart a nice slope.

<chart:SfChart.PrimaryAxis>
  <chart:CategoryAxis LabelRotationAngle = "-45">
    <chart:CategoryAxis.Title>
      <chart:ChartAxisTitle Text ="Meetup Date"/>
    </chart:CategoryAxis.Title>
  </chart:CategoryAxis>
</chart:SfChart.PrimaryAxis>

Secondary Axis

Along the left hand side, I want to display the number of check-ins per event. By specifying a NumericalAxis, the chart will automatically calculate numeric intervals for the data.

<chart:SfChart.SecondaryAxis>
  <chart:NumericalAxis>
    <chart:NumericalAxis.Title>
      <chart:ChartAxisTitle Text ="Count"/>
    </chart:NumericalAxis.Title>
  </chart:NumericalAxis>
</chart:SfChart.SecondaryAxis>

Even without any data tied in, we have a nice base chart view in place:

Blank Graph

Series

To feed the meetup data to the chart, it’s necessary to supply a data “Series” that can be associated with the PrimaryAxis and SecondaryAxis. We can visualize the data in various ways, including: Line, Spline, Column, Range Column, Scatter, Area, Spline Area, Bar, Pie, Doughnut, Bubble, Stacking Bar, Stacking Area, and so on. For this graph, I opted for the Stacking Column Series, which will stack two sets of data in a single column, representing both check-ins and guests.

<chart:SfChart.Series>
  <chart:StackingColumnSeries
      ItemsSource="{Binding CheckInData}"
      XBindingPath="Date"
      YBindingPath="CheckIns"
      Label="Check-in"
      DataMarkerPosition = "Center"
      EnableDataPointSelection = "false"
      Color="#FF8D00">
    <chart:StackingColumnSeries.DataMarker>
      <chart:ChartDataMarker>
        <chart:ChartDataMarker.LabelStyle>
          <chart:DataMarkerLabelStyle LabelPosition = "Center"/>
        </chart:ChartDataMarker.LabelStyle>
      </chart:ChartDataMarker>
    </chart:StackingColumnSeries.DataMarker>
  </chart:StackingColumnSeries>
  <chart:StackingColumnSeries
      ItemsSource="{Binding CheckInData}"
      XBindingPath="Date"
      YBindingPath="Guests"
      Label="Guests"
      EnableDataPointSelection = "false"
      Color="#D32F2F"/>
</chart:SfChart.Series>

For both StackingColumnSeries, I am binding to the CheckInData ObservableCollection and setting the XBindingPath to Date; the difference is the YBindingPath property for either the check-in or RSVP to display. I have also spruced up the colors and added a marker label for the first column series.

Data in Syncfusion Char

Legend and Scrolling

Adding a legend at the top of the chart helps users understand what the chart colors represent. The label specified on the series will display next to a color indicator.

<chart:SfChart.Legend>
  <chart:ChartLegend/>
</chart:SfChart.Legend>

Lastly, I know that there are a lot of events that could happen in the lifespan of a user group, so I only want to display a few columns and then enable scrolling. By specifying a bit of XAML for chart behaviors, I can tell the chart to pan when the user touches it.

<chart:SfChart.ChartBehaviors>
  <chart:ChartZoomPanBehavior EnablePanning="true" EnableDoubleTap="false"/>
</chart:SfChart.ChartBehaviors>

The final step is to calculate the “ZoomFactor”. The ZoomFactor is used to control how much data should be displayed on the graph when it is rendered. This is calculated as a double between 0 and 1 (as a percentage). So, if we had 20 entries and wanted to show half of them and the other half as pannable, then the ZoomFactor would be .5. This can be calculated with a few lines of code in the code behind after loading the data and even optimized by incorporating max columns for either the phone or tablet form factor and device operating system.

var max = Device.Idiom == TargetIdiom.Phone ? 7.0 : 14.0;
var factor = max / (double)viewModel.CheckInData.Count;
if (factor > 1.0)
  factor = 1.0;
else if (factor < .1)
  factor = .1;
Chart.PrimaryAxis.ZoomFactor = factor;

Panning Chart Syncfusion

Learn More

This is just a small peek at the many controls that make up Syncfusion Essential Studio. To get started, head over to the Xamarin Component Store and read Essential Studio’s full Getting Started Guide for iOS, Android, and Xamarin.Forms, and start your free 30-day trial at Syncfusion.com. As always, you can download the full source code for Meetup Manager on my GitHub to try it out for yourself.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 10, 2015

Pearson is at the Top of the Class with Xamarin

By

Pearson LogoPearson is the world’s leading learning company, with 40,000 employees in over 80 countries helping people of all ages make measurable educational progress. Recently they introduced the Pearson System of Courses (PSOC), a vertically and horizontally aligned system that supports learning, motivation, and engagement through a coherent curriculum covering math from K-11 and English Language Arts for K-12, with a unique digital design that makes use of tablets and mobile devices. Pearson recognized the need to support multiple devices and operating systems early on, but while the importance of a cross-platform approach was obvious, the company was disappointed in the quality and fidelity of the options it tested.

Pearson found the expertise it sought in Xamarin Partner Fino Consulting, an IT consulting firm based in New York City. Xamarin enabled Fino to leverage key components of Pearson’s existing iOS codebase to achieve 65% shared code and create a solution that could be supported on a wide variety of devices. This shared code not only dramatically reduced total development time across all platforms, but also increased stability and performance. Further quality control comes from Xamarin Insights, an intelligent analytics and crash reporting system that helps the team spot potential problems early in the development cycle, before they create problems for PSOC users.

Pearson found Microsoft Azure to be the perfect complement to Xamarin, providing support for anticipated loads of 40 TB in the first year of operation for cross-platform tablet interfaces on iOS, Windows 8.1, and soon, Android.

Pearson PSOC app on an Apple iPad

“PSOC moves a terrific amount of data around,” explains Keith O’Conner, Director at Fino Consulting. “The digital curriculum can be media rich. It’s one thing to have someone at home downloading a movie that’s 1 GB, but it’s a different situation when you have 1,000 students in a single school who need to download 5 or 10 GB each. There can be huge challenges around managing that content flow and facilitating the data transfer.”

PSOC, already active in eight school districts serving 85,000 students in 2014, is expected to grow by about 50% by the end of 2015. With Xamarin and Microsoft Azure in their corner, Pearson and Fino are confident in PSOC’s ability to go the distance:

“The robustness of the Xamarin Platform and its alignment with .NET make it a powerful tool to take advantage of,” says Christian Jungers, CTO of Fino Consulting. “Few companies in technology are so active with respect to introducing solid new features every year that directly address the needs of their customers.”

 

View the Case Study
 

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 7, 2015

Contest: Test Your Way to Xamarin Evolve

By

Have you started testing your apps with Xamarin.UITest yet? With our recent announcement that all Xamarin Platform subscriptions include Xamarin Test Cloud device minutes, there’s never been a better time to start using User Interface Testing (UITest) to ship better apps.

If that wasn’t enough incentive to get you started, this contest will have you testing your apps quicker than you can say, “How do I get a ticket to Xamarin Evolve 2016?”

Screen Shot 2015-04-21 at 14.53.00

What is Xamarin.UITest?

Xamarin.UITest is a C# test automation framework that enables testing mobile apps on Android and iOS. Tests are written locally using either physical devices or simulators/emulators and then submitted to Xamarin Test Cloud for more extensive testing across hundreds of devices.

Contest

Test your app in Xamarin Test Cloud and enter to win a ticket to Xamarin Evolve 2016!

Xamarin Evolve 2016 Banner

How to Enter

Simply Tweet a photo of your to app running in the Xamarin Test Cloud and include @XamarinHQ and the hashtag #TestCloud, like this:


How to Win:

You can improve your odds of winning with a few simple steps to help your entry stand out:

  • Share your tests on GitHub.
  • Blog about your tests.
  • The more tests you share the more chances you have to win!

Don’t forget to include links to your blog post and tests in your entry tweets.

Prizes

  • First Place: One Full Admission Ticket to Xamarin Evolve 2016!
  • Second Place: $100 iTunes Gift Card
  • Third Place: A Xamarin Monkey

 

Rules and Regulations

All entries must be submitted by Monday, August 17th at 12pm EST. A valid entry consists of a Tweet with a photo of your app running in the Xamarin Test Cloud that highlights a unique UITest running and includes both @xamarinhq and the hashtag #TestCloud. We will review and evaluate your submissions based on a variety of factors, including creativity and number of likes, retweets, and shares. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up if you win. This contest is open to individuals and there is no purchase necessary to enter.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 6, 2015

What is Xamarin.UITest?

By

A key component of Xamarin Test Cloud is the development of test scripts to automate mobile UI testing. The Xamarin Test Cloud team started working on Xamarin.UITest in December of 2013 and released a public version at Xamarin Evolve in October, 2014. In this blog post, I’m going to share some thoughts and advice about the framework and our design decisions.

TestCloudReport

What is Xamarin.UITest?

Xamarin.UITest is a C# test automation framework that enables testing mobile apps on Android and iOS. Mobile automation is far from an easy endeavor, and Xamarin.UITest aims to provide a suitable abstraction on top of the platform tools to let you focus on what to test. Tests are written locally using either physical devices or simulators/emulators and then submitted to Xamarin Test Cloud for more extensive testing across hundreds of devices.

Available from NuGet, there are two restrictions for non-Xamarin Test Cloud users: 1) they can only run on simulators/emulators and 2) the total duration of a single test run cannot exceed 15 minutes.

A Simple Example

Here is a simple example of a test written with Xamarin.UITest:

[Test]
public void MyFirstTest()
{
  var app = ConfigureApp
    .Android
    .ApkFile("MyApkFile.apk")
    .StartApp();
  app.EnterText("NameField", "Rasmus");
  app.Tap("SubmitButton");
}

First, we configure the app that we’re going to be testing. Then we enter “Rasmus” into a text field and press a button.

The main abstraction in Xamarin.UITest is an app. This is the gateway for communicating with the app running on the device. There is an iOSApp, an AndroidApp, and an IApp interface containing all of the shared functionality between the platforms, allowing cross-platform app tests to be written against the IApp interface.

Design Goals

Xamarin.UITest is designed with a few design goals in mind, which help focus our efforts and provide a level of consistency. Some of the goals are inspired by Mogens Heller Grabe and his Rebus project. Goals are only as good as the reasons that back them, so let’s take a look at some of the goals for Xamarin.UITest and why we decided that each of them was important.

Discoverable

Part of the power of C# is amazing tools; for example, we have come to depend heavily on IntelliSense. One goal in designing Xamarin.UITest was to harness these tools and make as much functionality as possible discoverable through IntelliSense. In order to do this, you must minimize the number of entry points that the end user has to know about.

At the time of this writing, the only entry point for writing tests in Xamarin.UITest is the static ConfigureApp fluent interface. Once you have this entry point, everything else in the framework can be discovered through IntelliSense. The only exception is the TestEnvironment static class, which provides a bit of contextual information about the test environment that can be helpful when configuring the app.

Declarative

Mobile testing is hard. Platforms and tools are constantly changing and, as a result, the underlying framework often has to adapt. In addition to the rapid pace of change, the test has to perform on a wide range of devices with different sizes and processing power.

We built Xamarin.UITest with this in mind. We strive to provide a succinct interface for describing intent, such as the interactions you want performed or what information you are interested in.

A common issue in testing that’s very evident in mobile testing is waiting: you tap a button and have to wait for the screen to change before you can interact with the next control. The easy solution is to use a Thread.Sleep call to wait just enough time, but what amount of time is “enough”? This leads to slow tests that wait too long or tests that are brittle because they’re pushing the limits. A better solution would be wait for a change in the app. In Xamarin.UITest, one option is app.WaitForElement, which will continuously poll the app. However, waiting is an artifact of making the test work. The scenario we are trying to solve is to interact with two controls. Our solution for most gestures is to automatically wait if the element is not already present on the screen. In the best case, this alleviates the tester from worrying about details that are not important to the test. The only downside is that a failure will be a bit slower.

No Visible External Dependencies

In recent years, .NET has been greatly enhanced by technology such as NuGet, which allows us to create software that utilizes many other libraries, but there are still has a few problems. One of these problems is versioning, and a prime example is depending on a NuGet package that depends on a specific version of a popular package such as Newtonsoft.Json. This then restricts you in your own Newtonsoft.Json version and could possibly mismatch with other NuGet packages you want to use.

For Xamarin.UITest, our aim is to have no visible external dependencies. This doesn’t mean that we code everything from the ground up; rather, we take care to not use any types from our dependencies in our public interface, so that we can use ILMerge (or ILRepack in our case) to combine everything into a single assembly with our dependencies internalized. In the case that we need something that is available on our public interface, we could open the framework up and provide a separate integration NuGet package. A nice example of this approach can also be seen in Rebus.

Helpful Errors

Errors happen. Mobile testing exercises many components and interacts with quite a few external systems, and there may be prerequisites or other environment settings that are not set up properly. In these cases, we often have no choice but to report the error, because our aim is to provide the best possible information about what went wrong. In addition, if we have any information that might help the user resolve the problem, we attempt to include this information in the error message as well.

More Information

For more information, follow the tutorials in our documentation. Karl Krukow and I also did a presentation featuring a general overview of Xamarin Test Cloud, a demo of Xamarin.UITest, and a live stream of one of the Xamarin Test Cloud labs that you can watch here.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 5, 2015

Put Some Azure Active Directory in Xamarin.Forms

By

The Azure Active Directory Authentication Library (aka ADAL) makes authentication with Azure Active Directory a breeze. We’ve already covered usage of ADAL in various posts on authenticating with Active Directory, adding storage, and adding collaboration (SharePoint) to your mobile apps. azure-active-directoryADAL is available for various platforms and supports Xamarin.Android, Xamarin.iOS, and Windows Phone. It’s easy to integrate ADAL into these projects by adding a NuGet package. Although ADAL hasn’t released a specific Package for Xamarin.Forms, there have been many questions in the Xamarin forums and on StackOverflow about how to use ADAL in a Xamarin.Forms app.

Recently, Vittorio Bertocci, Principal Program Manager at Microsoft, posted a blog about integrating ADAL into Xamarin.Forms apps using a PageRenderer. In this post, I’ll be sharing another way to integrate ADAL into Xamarin.Forms apps using Dependency Service, which is available in Xamarin.Forms.

 

Step 1: Create a Xamarin.Forms App

Create a Xamarin.Forms app in Xamarin Studio or Visual Studio. If you create this project with Visual Studio, it will create four projects: PCL, Android, iOS, and Windows Phone. In this solution, the Windows Phone project created with Xamarin.Forms uses the Silverlight framework, which has different requirements for implementing ADAL than iOS, Android, or Windows Runtime apps. So let’s add a Windows Phone 8.1 project, for which we’ll use the new Windows Runtime framework by following the steps in the documentation. Follow the guide and make sure your project structure looks similar to my solution below:

ADAL-In-Xamarin-Forms-01

Step 2: Add NuGet Package References

For each project (excluding Windows Phone 8.0 Silverlight), add an ADAL NuGet package (currently pre-release). The same NuGet package with the same version should get added to each platform project.

ADAL-In-Xamarin-Forms-02

Step 3: Create IAuthenticator Interface

In your PCL, add a new interface with the Authenticate method. It should return AuthenticateResult from ADAL, which contains the AccessToken and other details that are required for further API calls.

public interface IAuthenticator
{
  Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri);
}

Step 4: Create IAuthenticator Implementations

The Authenticate method body is almost the same in each platform. The only change that occurs is different parameters for PlatformParameters, which governs the authentication flow and maintains the context of the app.

Let’s review the implementations one at a time.

Android Implementation

PlatformParameters needs an Activity in Android, and in Xamarin.Forms you can cast Forms.Context to grab the main Activity. The entire implementation in your Android project would look like this:

[assembly: Dependency(typeof(ADALForForms.Droid.Helper.Authenticator))]
namespace ADALForForms.Droid.Helper
{
  class Authenticator : IAuthenticator
  {
    public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
    {
      var authContext = new AuthenticationContext(authority);
      if (authContext.TokenCache.ReadItems().Any())
        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
      var uri = new Uri(returnUri);
      var platformParams = new PlatformParameters((Activity)Forms.Context);
      var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
      return authResult;
    }
  }
}

Apart from this, you’ll also need to override the OnActivityResult method in the MainActivity.cs file, which will continue the authentication flow.

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
  base.OnActivityResult(requestCode, resultCode, data);
  AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}

iOS Implementation

For iOS, PlatformParameters accepts a UIViewController to maintain the context. We can set RootViewController to use it as context, so the implementation on iOS should be as follows:

[assembly: Dependency(typeof(ADALForForms.iOS.Helper.Authenticator))]
namespace ADALForForms.iOS.Helper
{
  class Authenticator : IAuthenticator
  {
    public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
    {
      var authContext = new AuthenticationContext(authority);
      if (authContext.TokenCache.ReadItems().Any())
        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
      var controller = UIApplication.SharedApplication.KeyWindow.RootViewController;
      var uri = new Uri(returnUri);
      var platformParams = new PlatformParameters(controller);
      var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
      return authResult;
    }
  }
}

In the case of iOS, we don’t need to override/implement any separate method to continue the authentication flow. We should get authResult back whenever the authentication flow completes.

Windows Phone Implementation

PlatformParameters doesn’t need any parameter as such for the Windows Phone app, so we’ll use the following code to allow us to authenticate with AD:

[assembly: Dependency(typeof(ADALForForms.Phone.Helper.Authenticator))]
namespace ADALForForms.Phone.Helper
{
  class Authenticator : IAuthenticator
  {
    public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
    {
      var authContext = new AuthenticationContext(authority);
      if (authContext.TokenCache.ReadItems().Any())
        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
      var uri = new Uri(returnUri);
      var platformParams = new PlatformParameters();
      var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
      return authResult;
    }
  }
}

Just like Android, Windows Phone needs to handle the continuation after login. This can be done by overriding the OnActivated method in the App.xaml.cs file and calling back to the WebAuthenticationBrokerContinuationHelper.

protected override void OnActivated(IActivatedEventArgs args)
{
#if WINDOWS_PHONE_APP
  if (args is IWebAuthenticationBrokerContinuationEventArgs)
  {
    WebAuthenticationBrokerContinuationHelper.SetWebAuthenticationBrokerContinuationEventArgs(args as IWebAuthenticationBrokerContinuationEventArgs);
  }
#endif
  base.OnActivated(args);
}

Step 5: Call Authenticate() in the Apps

Now, we need to call the Authenticate method. Let’s add a new HomePage with a button, which should call the Authenticate method on its click event. Before this, let’s declare some variables that are required for authentication. To do so, add a new XAML Page and declare your variables for ADAL.

public static string clientId = "your-client-id";
public static string authority = "https://login.windows.net/common";
public static string returnUri = "your-redirct-uri";
private const string graphResourceUri = "https://graph.windows.net";
private AuthenticationResult authResult = null;

Now, we can use the Dependency Service from Xamarin.Forms to locate the Authenticate method in each platform and execute it.

private async void Button_OnClicked(object sender, EventArgs e)
{
 var auth = DependencyService.Get<IAuthenticator>();
 var data = await auth.Authenticate(authority, graphResourceUri, clientId, returnUri);
 var userName = data.UserInfo.GivenName + " " + data.UserInfo.FamilyName;
 await DisplayAlert("Token", userName, "Ok", "Cancel");
}

Here, you should have results in the authResult variable. You can use the Access Token from authResult to call any APIs that are secured by Azure Active Directory, e.g., Office 365 and Graph.

ADAL-In-Xamarin-Forms-Last-Image

Note: ADAL used in this blog post is in preview mode. There may be changes by the time it is released.

You can download the sample created for this post, update your credentials (e.g. Client Id and Redirect URI), and test the app from GitHub

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
August 4, 2015

Webinar Recording: Mobile Enterprise Success with Xamarin and Oracle

By

We’re excited to help our customers build better enterprise apps through our recently announced partnership with Oracle. With this partnership, developers can build native iOS and Android Xamarin apps that quickly integrate with Oracle Mobile Cloud Service (MCS) for robust backend functionality, including push notifications, mobile APIs, storage, analytics, and more.

Watch the recording of the live “Mobile Enterprise Success with Xamarin and Oracle” webinar below to hear leading Forrester Analyst Michael Facemire and Xamarin and Oracle executives discuss our partnership and its impact on enterprise mobility. You’ll also learn about each platform and see a live demo on configuring MCS, building a Xamarin Project, and adding the Xamarin SDK for Oracle Mobile Cloud Service to your projects.

View the presentation slides for this webinar here.

Additional Resources

Visit xamarin.com/oracle for more information about our partnership and to download the Xamarin SDK for Oracle Mobile Cloud Service.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone