January 28, 2015

Android Tips: Hello Material Design v7 AppCompat

By

Nexus 4 (KitKat) Screentshot 2Android 5.0 Lollipop introduced a complete refresh, known as Material Design, to the Android user interface which generated rapid adoption throughout the development community. Until Google introduced revision 21 of the Android Support v7 AppCompat library, Material Design themes, controls, and features were utilized only if you wanted to target devices running API 21.

We recently took a look at how this library gave developers an opportunity to add the ActionBar to applications targeting older devices all the way back to API 7. However, now you can use this updated library to add Material Design to any of your applications and use new controls like the new Toolbar, which replaces the ActionBar. Let’s see how easy it is to get started with the new Support Library v7 AppCompat by updating our Toolbar example.

Getting Started

To start integrating AppCompat into your Android project you will want to install the Support Library v7 AppCompat from the Component Store or directly from NuGet. This will also install the Support v4 Library, which is required because it provides controls that help maintain backwards compatibility.

Supportv7Component

Since you will now be able to target older versions of Android, you will want to adjust your Minimum and Target Android version under Android Application in the project options.

MinandTarget

Updating to Material Theme

There are many differences to the actual resources that are embedded into your app when you use the AppCompat library. This means that the actual themes and attributes are completely different between normal Material and AppCompat themes. You will find three new themes that you can inherit from:

Dark: Theme.AppCompat
Light: Theme.AppCompat.Light
Light with Dark ActionBar: Theme.AppCompat.Light.DarkActionBar

MaterialDesign

StylesFoldersTo use one of these themes, you’ll want to create two folders under your Resources folder named values and values-v21 where you will create a styles.xml where you can customize your applications theme. In our values/styles.xml you will create the base theme of your application and then set custom attributes. You will see that these attributes are different than using the standard Material Theme since they have dropped the android: prefix as they are now part of your application.

values/styles.xml

<resources>
  <style name="MyTheme" parent="MyTheme.Base">
  </style>
  <!-- Base theme applied no matter what API -->
  <style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <!--We will be using the toolbar so no need to show ActionBar-->
    <item name="windowActionBar">false</item>
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette-->
    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#2196F3</item>
    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#1976D2</item>
    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <item name="colorAccent">#FF4081</item>
     <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight and colorSwitchThumbNormal. -->
  </style>
</resources>

Then, inside of your values-v21/styles.xml, you’ll set a few more custom attributes that can take advantage of transitions on devices running Lollipop:

<resources>
  <!--
        Base application theme for API 21+. This theme replaces
        MyTheme from resources/values/styles.xml on API 21+ devices.
    -->
  <style name="MyTheme" parent="MyTheme.Base">
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
  </style>
</resources>

The last step is to open your AndroidManifest.xml under the Properties folder and add reference to your new theme under the application node with android:theme="@style/MyTheme".

Integrate Toolbar

Perviously, we saw how to integrate the new Toolbar into your application. The core of that remains the same, except that you will now directly reference the new Toolbar widget from the Support Library:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Note here the use of custom themes directly for the Toolbar and the use of custom attributes. These are a change form the normal use of the Toolbar when not using AppCompat.

Update that Activity

The core of any Android application are Activities. When you start using AppCompat, you simply need to update your activities inheritance.
From:

public class MainActivity : Activity

To:

public class MainActivity : ActionBarActivity

You can now setup your Activity to set the SupportActionBar with the new Toolbar that you have embedded into your layout. I prefer to use an alias to ensure the correct Toolbar is always referenced:

using Toolbar = Android.Support.V7.Widget.Toolbar;

Then you simply need to find the Toolbar, set it, and access it in your OnCreate:

protected override void OnCreate (Bundle bundle)
{
  base.OnCreate (bundle);
  // Set our view from the "main" layout resource
  SetContentView (Resource.Layout.main);
  var toolbar = FindViewById<Toolbar> (Resource.Id.toolbar);
  //Toolbar will now take on default actionbar characteristics
  SetSupportActionBar (toolbar);
  SupportActionBar.Title = "Hello from Appcompat Toolbar";
  //..
}

There you have it, you can now run your newly Material Themed Android application on devices that aren’t running Lollipop!

Nexus 4 (KitKat) Screentshot 1

Learn More

You can get the full source code for this project in the Support v7 Sample gallery. There you will also find other awesome examples of more Support v7 libraries such as CardView, RecyclerView, and Palette. During Evolve 2014, Jérémie Laval and I gave two talks on Material Design from Concept to Implementation. (Part 1 and Part 2) that are available to watch now.

Discuss this post in the Xamarin forums.

TwitterFacebookGoogle+LinkedInEmail
January 27, 2015

Unified API Migration Example with the Dutch Spelling App

By

Earlier this month, I recorded a webinar showing an overview of what the new Unified API means for developers and how you can seamlessly migrate your existing apps to guarantee their longevity. As we approach Apple’s deadline for supporting 64-bit in new app submissions, iOS developers around the world are ensuring their apps will continue to be accepted into the App Store by making the necessary changes to enable the support. Xamarin developers will need to follow suit by making sure they’ve updated their apps to use the new Unified API, which replaces the Classic API.

During the webinar I demonstrated the migration process on an app I developed some time ago that needed to be migrated to the Unified API. The app in question is called Dutch Spelling, a language learning app originally built in just 2 hours! It’s available to download from GitHub in order for you to follow the guide I’ve created for you below.

screenshots

Dutch Spelling’s business logic is contained within a library that is referenced from the language specific project. This approach allows me to add new features and fix bugs in only one project, while maintaining the language based content of the app separate.

Migration to Unified.

The migration process from the Classic API to our new Unified API couldn’t be any simpler. If you’ve cloned Dutch Spelling onto your machines, you’ll notice that it currently has two branches. The master branch is our Unified API and the second branch uses the Classic API. I’ve taken this approach with my other iOS apps such as My StepCounter, as it allows you to see the differences in the solution before and after migration.

You’ll want to ensure you’re on the Classic-API branch before starting the migration. Open the project in your favorite IDE (in my case it’s Xamarin Studio) and double check that everything builds as expected. If it doesn’t, please create an issue on GitHub for me to investigate.

Migration Tool

Let’s select the ‘Dutch Spelling’ project and click ‘Project’ > ‘Migrate to Xamarin.iOS Unified API’. You’ll be presented with a dialog explaining what the migration tool will do to your project. You will want to click ‘Migrate to Unified API’.

Xamarin Studio

Visual Studio
Screen Shot 2015-01-26 at 10.15.58 AM

With this, your project will now reference Xamarin.iOS instead of MonoTouch and our Spelling.Core project will be marked as incompatible. This project is now using the Unified API and we don’t need to touch it again, however, we will now need to run the same process on Spelling.Core, and then we’re done.

If the migration tool doesn’t successfully migrate your project, or you’ve got a complex situation, you can manually migrate to the Unified API. Our documentation team has written a fantastic step-by-step migration guide.

Learn More

To learn more about the Unified API be sure to read through the full documentation. To see a full migration of Dutch Spelling in action, check out my Unified API Webinar recording online.

TwitterFacebookGoogle+LinkedInEmail
January 25, 2015

App Spotlight: Graphium Health

By

Danny Dura of Graphium Health talked to us about how his company is working to create better care for patients by bringing data and analytics into the peri-operative (surgical) healthcare space via mobile technology.

The Graphium Health app offers a better experience for both patients and providers by creating effective ways for providers to use the mobile devices they already have in their pockets to track patient data and analytics. Used by doctors, nurses, and other medical staff in hospitals nationwide, the app replaces paper charting with a more secure, accurate, and efficient way to keep track of patient information in an easy, usable format that doesn’t distract from providing top-notch care.

To understand the how the app streamlines care for both doctors and patients, we took a walk through the app with Danny:

I love that Graphium worked to make the app accessible and intuitive for health professionals, while increasing the efficiency and security of the process.

Learn More

To learn more about Graphium Health, or request a free trial, you can visit their website here.

To get started developing with the Xamarin platform, check out our developer documentation, or get live online training with Xamarin University.

TwitterFacebookGoogle+LinkedInEmail
January 23, 2015

Xamarin MVPs Expand with More Awesome!

By

Since the introductionXamarin MVP of the Xamarin MVP program in 2013, our MVPs have been busy sharing their love and understanding of mobile app development with a growing community of more than than 880,000 Xamarin developers worldwide. Supporting this growth are amazing community members who show their passion for all things C# and F# by sharing their experience and knowledge with the world.

Xamarin MVPs have earned recognition for significant contributions to the community, including:

  • Writing great articles, books, and blog posts
  • Speaking in public and online
  • Sharing and building amazing libraries
  • Helping developers online in our forums, on Twitter, Stack Overflow, and other communities
  • Shipping awesome apps

Today, we’re extremely excited to recognize and welcome our latest Xamarin MVPs, below, for their remarkable contributions to the community!

enrique Enrique Aguilar Laurent Bugnion laurent
cheesebaron Tomasz Cielecki Jesse Liberty liberty
lipsky Jon Lipsky Roger Peters roger
rachel Rachel Reese Brent Schooley brent
snider Ed Snider Michael Stonis stonis
alec Alec Tucker

If you know of an outstanding developer who would make a great Xamarin MVP, please nominate him or her here.

TwitterFacebookGoogle+LinkedInEmail
January 22, 2015

Infographic: Build Right, Shift Left

By

You’re at the end of your mobile development cycle and just need to test your app before submitting to the app store. After testing on a handful of devices, you find several showstopper bugs that push your ship date out to weeks past your deadline. Is there a better alternative to this “build then test” workflow that slows your time to market, forces rework, causes bugs, and costs you money?

Download this infographic to learn why shifting your testing processes “left” in the development cycle to the start of your mobile project makes it faster and easier to find bugs before your users do.

Build Right, Shift Left infographic

TwitterFacebookGoogle+LinkedInEmail
January 21, 2015

Authenticate Xamarin Mobile Apps Using Azure Active Directory

By

When developing mobile apps, you often run into an instance where your app needs some kind of authentication mechanism to protect its contents. iPhone Active DirectorySome mobile app developers choose to create their own repository to create a username/password based solution. Others choose a social media authentication provider such as Facebook, Twitter, or LinkedIn. Using Xamarin.Auth makes authenticating to services such as these extremely simple to implement.

However, in the case of enterprise apps, people don’t want to remember ‘yet another’ username/password combo and social media authentication is the least expected solution. Users expect their organization account to allow them to use different resources and apps within their system. Welcome to the world of Azure Active Directory (or Azure AD for simplicity).

Azure AD allows developers to secure resources such as files, links, and Web APIs using the same organizational account that employees use to sign in to their systems or check their emails. This should sound a bit familiar, as it is the same authentication mechanism behind Office 365.

Let’s take a look at how to integrate Azure AD into your mobile app with two simple steps.

Step 1: Registering the application with Azure AD

  1. First navigate to https://manage.windowsazure.com and log in with your Microsoft Account or Organization Account in the Azure Portal. If you don’t have an Azure Subscription, you can get a trial from http://www.azure.com
  2. After signing in, go to your Active Directory (1) and select the Active Directory where you want to register the application (2)
    01. Active Directory in Azure Portal
  3. After selecting the desired Active Directory, ‘Add‘ a new application by either clicking the link at front or at the bottom. Then select ‘Add an application my organization is developing
    02. Add New Application
  4. On the next screen, give your app a name. In my case it is ‘XAM-DEMO‘. On this screen, make sure you select ‘Native Client Application‘ as the type of application.
    03. App Name
  5. On the final screen, provide a ‘Redirect URI‘, which is unique to your application as it will return to this URI when authentication is complete.
    04. App Redirect URI
  6. Once the app is created, navigate to the ‘Configure‘ tab. Write down the ‘Client ID’, which we’ll use in our application later. Also, on this screen you can give your mobile application access to Active Directory or add another application like Web API, which can be used by mobile application once authentication is complete.
    05. Configure Application

Step 2: Authenticating the application with Azure AD

In your application, add a reference to Azure Active Directory Authentication Library (Azure ADAL) using the NuGet Package Manager in Visual Studio or Xamarin Studio. Make sure you select ‘Show pre-release packages’ to include this package, as it is still in preview.

Note: Azure ADAL 3.0 is currently a preview and there may be breaking changes before the final version is released. I have included references at the end of this post where you can find more information on Azure ADAL.

06. ADAL NuGet Package

In your application, you will now need to add the following class level variables that are required for the authentication flow.

//Client ID from from step 1. point 6
public static string clientId = "25927d3c-.....-63f2304b90de";
public static string commonAuthority = "https://login.windows.net/common"
//Redirect URI from step 1. point 5<br />
public static Uri returnUri = new Uri("http://xam-demo-redirect");
//Graph URI if you've given permission to Azure Active Directory in step 1. point 6
const string graphResourceUri = "https://graph.windows.net";
public static string graphApiVersion = "2013-11-08";
//AuthenticationResult will hold the result after authentication completes
AuthenticationResult authResult = null;

One thing to note here is commonAuthority. When the authentication endpoint is ‘common’, your app becomes ‘multi-tenant’, which means any user can use login with his Active Directory credentials. After authentication, that user will work on the context of his own Active Directory – i.e. he will see details related to his Active Directory.

At this time, you can modify the default button.Click event from the default Android application (or create your own flow to start the authentication). This will start the authentication and upon completion assign the result in authResult

button.Click += async (sender, args) => {
  var authContext = new AuthenticationContext(commonAuthority);
  if (authContext.TokenCache.ReadItems().Count() == 0)
    authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
  authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, new AuthorizationParameters(this));
}

In the above code, the AuthenticationContext is responsible for the authentication with commonAuthority. It has an AcquireTokenAsync method, which take parameters as a resource which needs to be accessed, in this case graphResourceUri, client ID, return URI. The app will return to the returnUri when authentication completes. This code will remain the same for all platforms, however, the last parameter, AuthorizationParameters, will be different on different platforms and is responsible for governing the authentication flow.

In the case of Android or iOS, we pass ‘this’ parameter to AuthorizationParameters(this) to share the context, whereas in the case of Windows, it is passed without any parameter as new AuthorizationParameters().

Along with it, we also need to override the OnActivityResult method in Android to resume the application.

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

For Windows Phone, modify the OnActivated method in the app.xaml.cs file with the below code:

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

Now if you run the application, you should see an authentication dialog. Upon successful authentication, it will ask your permissions to access the resources (in our case Graph API).
08. Authentication-Flow
If authentication is successful and you’ve authorized the app to access the resources, you should get an AccessToken and RefreshToken combo in authResult. These tokens are required for further API calls and for authorization with Azure AD behind the scenes.
07. Access_Token For Authentication

For example, the code below allows you to get a user list from Active Directory. You can replace the Web API URL with your Web API which is protected by Azure AD.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.windows.net/tendulkar.onmicrosoft.com/users?api-version=2013-04-05");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();

This way you can authenticate your mobile apps against Microsoft Azure Active Directory. ADAL makes it much easier with fewer lines of code, while keeping most of the code the same and thus making it shareable across platforms.

Learn More:

  • Azure ADAL is in preview. So, there can and most likely will be changes before the final release. Follow Vittorio Bertocci’s blog for more details and changes to the library.
  • The Azure Team has shared a complete example with Azure ADAL for each platform. Download it from here.
TwitterFacebookGoogle+LinkedInEmail
January 20, 2015

Introducing the Xamarin WatchKit Preview

By

Today, we are are happy to announce the release of our WatchKit Preview for Xamarin Studio, enabling you to build, run, and test your Apple Watch apps directly from Xamarin Studio.

frontpic_bezel

WatchKit Templates

We’ve added new templates for Watch apps and Watch extensions inside Xamarin Studio. Start with a new or existing iOS app, add a Watch App to house your interface, and then add a Watch extension to power the interaction. Xamarin Studio does all of the heavy lifting for you.

projects

Test in the Simulator

Get started testing your applications in the simulator so you can be ready when devices hit the market. Xamarin Studio has support for building, running, and debugging your Watch apps in app mode. You can also test your app in Glance and Notifications mode from the command line.

simulator

Get Started Today

You can download the bits for WatchKit Preview directly from the Xamarin Developer site. To get started with WatchKit, check out the WatchKit Preview guide.

Please note that this release is a Preview. It is not available on the Stable, Beta, or Alpha channels and is a separate install. We are working hard on adding even more features for WatchKit, including support for the Xamarin Designer for iOS and Visual Studio, in future releases.

Very Important: Since this release is missing our designer support, you must follow the steps outlined in the WatchKit Preview guide to build your UIs.

See everything that WatchKit support has to offer by running the WatchKit Catalog sample from our sample gallery.

TwitterFacebookGoogle+LinkedInEmail
January 19, 2015

Webinar Recording: Migrating Apps to the Unified API and 64-Bit

By

Earlier this month we announced that Xamarin.iOS 8.6, featuring the Unified API, is available in the stable channel. This release comes perfectly timed for Apple’s February 1st deadline for new iOS app submissions and June 1st deadline for all new and existing iOS app submissions or updates to include 64-bit support.

In this webinar recording, Xamarin Evangelist Mike James provides an overview on how to make sure your libraries and apps are 64-bit ready by Apple’s deadlines, including how to migrate apps to the Unified API. In addition to the Q&A at the end of the video, we have also included an extended Q&A, below, covering more of the many questions asked during the webinar.

Additional Resources

The sample used in the demo can be found here.

If you’d like to learn more about the Unified API and 64-bit, our documentation has everything you need to get started here. You can also read our blog posts on the Unified API here and here.

Q&A

General

Do we need 64-bit versions of portable libraries coming as NuGet packages to use in a ‘unified’ project?

Library creators will need to update to the new Unified API, and we’ve got some excellent documentation about this here.

Why does the compiler not decide to use int or nint for us? This does not seem to be very “.NET like”.

In a 32-bit world, NSInteger could very easily be mapped to the System.Int32 (short: int) and it worked very well. With NSInteger now being both 32-bit and 64-bit (depending on the underlying architecture of the platform), this approach no longer works.

We’ve gone through all of our iOS and Mac API’s and found every instance of the Objective-C API using NSInteger that originally was mapped to int and these now take an nint.

You can learn more about our decisions behind nint here.

What is a Type Registrar?

On startup, Xamarin.iOS will registered managed classes (which include the [Register] attribute) and methods (which include the [Export] attribute) with the Objective-C runtime. This allows managed classes to be created and managed methods to be called from Objective-C. This is how methods and properties are linked between the C# and Objective-C worlds.

You can learn more here.

How should we handle the new “n” types in shared code?

The new native types found in the Unified API should only be shared in iOS and Mac projects. When creating libraries for consumption outside of these platforms (PCL, Share libraries, etc.) you should be using Int for 32-bit values and Long for 64-bit values.

Learn more about the new type here.

So with non-64-bit devices, will we have to do something different or will it just work?

When you build your Unified API based app, it will by default build dual 32/64-bit binaries transparently.

You alluded to new garbage collection; please elaborate.

We now have a garbage collector called sgen, which is now the default (as opposed to Boehm) which was used for the Classic iOS apps. We’ve also shipped support for our new reference counting system, which helps solves a number of problems that caused apps to crash. Another benefit of the change means your app consumes less memory. (The new reference counting can also be enabled in the Classic API from the project settings)

Learn more here.

Xamarin.Forms

Should I migrate my UI shared project on Xamarin.Forms? Or just the iOS Project?

You will only need to update the iOS project rather than the shared project. You can find our documentation on Xamarin.Forms migration here.

What about migration of an existing Plugin for Xamarin.Forms? How do we keep compatibility with existing apps that might be using our control and also provide the 64-bit support?

You simply need to upgrade your plugins to 1.3.1 and add a unified Library. I have already updated mine on GitHub. You can also check out other examples here and here.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail
January 16, 2015

Contest: Show Us Your App!

By

Have you created a beautiful app with Xamarin? Here’s your chance to show the world what you’ve built!

In this contest, you will create a short video showing us the app you have created, how it works, and any other fun details about the development process while building your mobile application.

blog phone pic 2

How to Enter:

  1. Record a short video demoing your Xamarin app
  2. Post your video to the Show Us Your App forum thread
  3. Tweet your video with the hashtags #Xamarin #BuiltWithXamarin

Here is a sample from our own James Montemagno, demoing his Android app “Bike Now”:

Prize:

  • Best App: $100 App Store / Google Play credit to help promote your app!
  • Best Video: $100 App Store / Google Play credit to help promote your app!

All submissions must be made by Monday, February 2nd at 12pm EST. We will evaluate each video and choose the winner based on concept, video quality, and originality. A valid entry consists of a tweet and forum post with a demo video of your personal app. Contestants should follow @XamarinHQ to enable us to DM you for private follow-up. There is no purchase necessary to enter the Show Us Your App Video contest.

TwitterFacebookGoogle+LinkedInEmail
January 15, 2015

Xamarin Event: TechDays 2015 in Paris

By

Join Xamarin at Microsoft TechDays 2015 in Paris, France from February 10-12. Key members from Team Xamarin will be available all three days to answer your questions, discuss your apps and projects, and catch you up on our incredible 2015 roadmap.

Xamarin at TechDays 2015

Mike James, Xamarin Developer Evangelist, will speak about cross-platform development with Xamarin and Xamarin.Forms on Wednesday, February 11th at 11:00am.

Visit us at Booth S67, or schedule a dedicated time to speak with one of our team members.

À bientôt!

TwitterFacebookGoogle+LinkedInEmail