December 29, 2014

The Top 12 Xamarin Blog Posts of 2014

By

We’ve seen a lot of exciting changes in the mobile space this year, and the Xamarin blog is a great place to find both inspiration and direction on keeping pace with these new developments. As the year draws to a close, we’ve been counting down our most popular blog posts of 2014 on Twitter in the “12 Days of Xamarin”. Today, we’re sharing the full list in one place for easy reference and revealing the #1 post.

As you look ahead to 2015, here are the top 12 posts from 2014 that will help ensure you’re ready for everything that the new year brings!

  1. Continuous Integration for Your Mobile App
  2. Xamarin Evolve 2014 Session Recordings Now Available
  3. Show Me the XAML
  4. Lights, Camera, Action – 3D in iOS 8 with Scene Kit
  5. Easier Code Sharing Across iOS, Android, and Windows
  6. Adding View Effects in iOS 8
  7. Real Time Code Iteration with Sketches
  8. Meet Xamarin.Forms: 3 Native UIs, 1 Shared Code Base
  9. Introduction to Android Material Design
  10. Using Custom Controls in Xamarin.Forms on Android
  11. Cheat Sheet for Top Mobile App Controls
  12. Introducing CocosSharp

We hope you find this re-cap useful, and can’t wait to keep sharing with you in 2015!

TwitterFacebookGoogle+LinkedInEmail
December 22, 2014

Extending Xamarin.Forms with Control Plugins

By

With an enhanced extensibility framework, Xamarin.Forms is an amazing platform for developing plugins that add cross-platform functionality; however, you can take it a step further by developing custom controls for Xamarin.Forms and packaging them into your very own Control Plugin for Xamarin.Forms. We have had several posts on how to use custom controls in Android, Windows Phone. Circle Image Control PluginMore recently how to create elegant circle images for Xamarin.Forms across all three platforms. Let’s see how we can take this custom control and create a re-distributable control plugin for Xamarin.Forms that you could enter in our holiday plugin for Xamarin contest.

Getting Started

Instead of embedding all of the circle image logic, which we have already finished, into our Xamarin.Forms application you will want to create your own library specifically for the control. This will consist of a Portable Class Library with the CircleImage class and then a class library for iOS, Android, and Windows Phone. I have created some handy templates for Visual Studio to get you started.

An important addition is that in each of your custom renderers you will need to add an initialization method:

public static void Init() { }

This will be familiar to you if you have been creating plugins for Xamarin.Forms, as this insures our control does not getting linked out in the application we add it to.

Adding Bindable Properties

Since your control plugin will be distributed you may want add a few custom bindable properties if it makes sense for your control. For the CircleImage I have added BorderThickness and BorderColor as additional properties that the CircleImage can use.

/// <summary>
/// Thickness property of border
/// </summary>
public static readonly BindableProperty BorderThicknessProperty =
  BindableProperty.Create<CircleImage, int>(
    p => p.BorderThickness, 0);
/// <summary>
/// Border thickness of circle image
/// </summary>
public int BorderThickness
{
  get { return (int)GetValue(BorderThicknessProperty); }
  set { SetValue(BorderThicknessProperty, value); }
}

CircleImagesPlugin

Packaging the Plugin

After moving all of the logic into this new project you are ready to package your control and publish it on NuGet. Part of the Visual Studio templates that are available will automatically create the nuspec that will need to be uploaded. Here is what the Circle Image’s looks like:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
   <metadata minClientVersion="2.8.1">
       <id>Xam.Plugins.Forms.ImageCircle</id>
       <version>1.0.0.2</version>
       <title>Image Circle Control Plugin for Xamarin.Forms</title>
       <dependencies>
         <dependency id="Xamarin.Forms" version="1.2.3.6257" />
       </dependencies>
   </metadata>
   <files>
      <!--Core-->
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.dll" target="lib\portable-net45+wp8+win8+MonoAndroid10+MonoTouch10\ImageCircle.Forms.Plugin.Abstractions.dll" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.xml" target="lib\portable-net45+wp8+win8+MonoAndroid10+MonoTouch10+Xamarin.iOS10\ImageCircle.Forms.Plugin.Abstractions.xml" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.pdb" target="lib\portable-net45+wp8+win8+MonoAndroid10+MonoTouch10+Xamarin.iOS10\ImageCircle.Forms.Plugin.Abstractions.pdb" />
     <!--Win Phone Silverlight-->
     <file src="ImageCircle.Forms.Plugin.WindowsPhone\bin\Release\ImageCircle.Forms.Plugin.WindowsPhone.dll" target="lib\wp8\ImageCircle.Forms.Plugin.WindowsPhone.dll" />
     <file src="ImageCircle.Forms.Plugin.WindowsPhone\bin\Release\ImageCircle.Forms.Plugin.WindowsPhone.xml" target="lib\wp8\ImageCircle.Forms.Plugin.WindowsPhone.xml" />
     <file src="ImageCircle.Forms.Plugin.WindowsPhone\bin\Release\ImageCircle.Forms.Plugin.WindowsPhone.pdb" target="lib\wp8\ImageCircle.Forms.Plugin.WindowsPhone.pdb" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.dll" target="lib\wp8\ImageCircle.Forms.Plugin.Abstractions.dll" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.xml" target="lib\wp8\ImageCircle.Forms.Plugin.Abstractions.xml" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.pdb" target="lib\wp8\ImageCircle.Forms.Plugin.Abstractions.pdb" />
     <!--Xamarin.Android-->
     <file src="ImageCircle.Forms.Plugin.Android\bin\Release\ImageCircle.Forms.Plugin.Android.dll" target="lib\MonoAndroid10\ImageCircle.Forms.Plugin.Android.dll" />
     <file src="ImageCircle.Forms.Plugin.Android\bin\Release\ImageCircle.Forms.Plugin.Android.xml" target="lib\MonoAndroid10\ImageCircle.Forms.Plugin.Android.xml" />
     <file src="ImageCircle.Forms.Plugin.Android\bin\Release\ImageCircle.Forms.Plugin.Android.pdb" target="lib\MonoAndroid10\ImageCircle.Forms.Plugin.Android.pdb" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.dll" target="lib\MonoAndroid10\ImageCircle.Forms.Plugin.Abstractions.dll" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.xml" target="lib\MonoAndroid10\ImageCircle.Forms.Plugin.Abstractions.xml" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.pdb" target="lib\MonoAndroid10\ImageCircle.Forms.Plugin.Abstractions.pdb" />
     <!--Xamarin.iOS-->
     <file src="ImageCircle.Forms.Plugin.iOS\bin\iPhone\Release\ImageCircle.Forms.Plugin.iOS.dll" target="lib\MonoTouch10\ImageCircle.Forms.Plugin.iOS.dll" />
     <file src="ImageCircle.Forms.Plugin.iOS\bin\iPhone\Release\ImageCircle.Forms.Plugin.iOS.xml" target="lib\MonoTouch10\ImageCircle.Forms.Plugin.iOS.xml" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.dll" target="lib\MonoTouch10\ImageCircle.Forms.Plugin.Abstractions.dll" />
     <file src="ImageCircle.Forms.Plugin.Abstractions\bin\Release\ImageCircle.Forms.Plugin.Abstractions.xml" target="lib\MonoTouch10\ImageCircle.Forms.Plugin.Abstractions.xml" />
   </files>
</package>

With your control plugin packaged up you are now free to distribute it to everyone via NuGet. Be sure to read the NuGet documentation on how to get started.

Learn More

You can find the Circle Image Control Plugin live on NuGet and the full source code available on GitHub. To find out more information on creating plugins for Xamarin be sure to watch the recording of our live Google+ Hangouts session from last week.

In addition to these resources I have recorded a short getting started with the Plugin for Xamarin templates that enables you to get up and running quickly.

TwitterFacebookGoogle+LinkedInEmail
December 19, 2014

Elegant Circle Images in Xamarin.Forms

By

Circular images in apps are currently a popular trend in mobile, and it is a simple technique that can add a lot of polish to your mobile apps. We made use of them in this year’s Xamarin Evolve mobile apps, and with a little bit of code and a single custom renderer, you too can transform standard images in Xamarin.Forms into these elegant round images.

MonkeyCircleImages

Custom Image

After you create your Xamarin.Forms project, the first thing you need to do is create a custom control that inherits from Image. Let’s call this ImageCircle and then implement the custom renderers on each platform.

public class ImageCircle : Image
{
  //Optional custom properties could go here
}

Custom Renderers

Now you just need to tell Xamarin.Forms how to render this new ImageCircle on each platform by using custom renderers.

For all three projects, you will need to create an ImageCircleRenderer that inherits from ImageRenderer and then implement how to cut out the circle image.

public class ImageCircleRenderer : ImageRenderer
{
  //...Implementation
}

iOS Renderer

For iOS you are able to directly interact with the CALayer of our UIImageView to add a corner radius and set the border color.

private void CreateCircle()
{
  try
  {
    double min = Math.Min(Element.Width, Element.Height);
    Control.Layer.CornerRadius = (float)(min / 2.0);
    Control.Layer.MasksToBounds = false;
    Control.Layer.BorderColor = Color.White.ToCGColor();
    Control.Layer.BorderWidth = 3;
    Control.ClipsToBounds = true;
  }
  catch(Exception ex)
  {
    Debug.WriteLine("Unable to create circle image: " + ex)
  }
}

This method should be called on the initial OnElementChanged or when the Height or Width properties are updated:

protected override void OnElementChanged(ElementChangedEventArgs e)
{
  base.OnElementChanged(e);
  if (e.OldElement != null || Element == null)
    return;
  CreateCircle();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
  base.OnElementPropertyChanged(sender, e);
  if (e.PropertyName == VisualElement.HeightProperty.PropertyName ||
      e.PropertyName == VisualElement.WidthProperty.PropertyName)
  {
    CreateCircle();
  }
}

And of course you must export the renderer with an assembly export:

[assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]
namespace CircleImage.iOS
{
 //...
}

Android Renderer

Android is a unique platform; you don’t have a physical layer to interact with, however, you are able to modify how Xamarin.Forms draws the child and cut out a path from the canvas. This method is a bit of complex math, but calculates the path to clip and then adds a circular border around the child.

protected override bool DrawChild(Canvas canvas, global::Android.Views.View child, long drawingTime)
{
  try
  {
    var radius = Math.Min(Width, Height) / 2;
    var strokeWidth = 10;
    radius -= strokeWidth / 2;
    //Create path to clip
    var path = new Path();
    path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
    canvas.Save();
    canvas.ClipPath(path);
    var result = base.DrawChild(canvas, child, drawingTime);
    canvas.Restore();
    // Create path for circle border
    path = new Path();
    path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
    var paint = new Paint();
    paint.AntiAlias = true;
    paint.StrokeWidth = 5;
    paint.SetStyle(Paint.Style.Stroke);
    paint.Color = global::Android.Graphics.Color.White;
    canvas.DrawPath(path, paint);
    //Properly dispose
    paint.Dispose();
    path.Dispose();
    return result;
  }
  catch (Exception ex)
  {
    Debug.WriteLine("Unable to create circle image: " + ex);
  }
  return base.DrawChild(canvas, child, drawingTime);
}

One intricate part here is that Android handles the clipping of paths differently depending on the version of Android. Hardware acceleration for this method was introduced in API 18, so you must tell Android to use software rendering on older devices. You can set the layer type flag in the OnElementChanged method:

protected override void OnElementChanged(ElementChangedEventArgs e)
{
  base.OnElementChanged(e);
  if (e.OldElement == null)
  {
    if ((int)Android.OS.Build.VERSION.SdkInt < 18)
      SetLayerType(LayerType.Software, null);
  }
}

And of course you must export the renderer with an assembly export:

[assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]
namespace CircleImage.Droid
{
 //...
}

Windows Phone Renderer

Last, but not least, we come to Windows Phone, which has a Clip property that you can use to create EllipseGeometry to cut out the circle from the image:

protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
  base.OnElementPropertyChanged(sender, e);
  if (Control != null && Control.Clip == null)
  {
    var min = Math.Min(Element.Width, Element.Height) / 2.0f;
    if (min <= 0)
      return;
    Control.Clip = new EllipseGeometry
    {
      Center = new System.Windows.Point(min, min),
      RadiusX = min,
      RadiusY = min
    };
  }
}

And of course you must export the renderer with an assembly export:

[assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]
namespace CircleImage.WinPhone
{
 //...
}

Custom Cell

With all of the custom renders in place, you can simply use your new ImageCircle anywhere you would like, including custom ViewCells for your ListViews. The key here is to ensure that you request the same Width & Height for your image and set the Aspect to AspectFill to ensure a perfect square to cut your circle from.

int photoSize = Device.OnPlatform(50, 50, 80);
var photo = new ImageCircle
{
  WidthRequest = photoSize,
  HeightRequest = photoSize,
  Aspect = Aspect.AspectFill,
  HorizontalOptions = LayoutOptions.Center
};
photo.SetBinding(Image.SourceProperty, s => s.Image);

CircleImages

See the Code in Action

You can grab the entire source code from GitHub. Additionally, I sat down with Xamarin’s own Steven Yi at this year’s Xamarin Evolve to explain how I implemented and used Circle Images in the Xamarin Evolve mobile apps:

TwitterFacebookGoogle+LinkedInEmail
December 18, 2014

Holiday Contest: Create a Plugin for Xamarin

By

tts_icon_largeOver the last few weeks, you might have seen a flurry of Plugins for Xamarin launching on NuGet and open sourced on GitHub. We have been working hard to kickstart Plugins and make it extremely easy for anyone to get started creating a Plugin for Xamarin.

What is a Plugin?

device_info_iconA Plugin for Xamarin is a special kind of NuGet that adds cross-platform functionality or abstracts platform specific functionality to a common API. These are both completely cross-platform and extremely small (i.e., they do 1 or 2 things really well with minimal-to-no dependencies). The Plugin API can be accessed on each platform, however, you will most likely only use the common API in a Portable Class Library or Shared Code project.

Contest

Build a Plugin for Xamarin or Xamarin.Forms to add powerful cross-platform functionality with a common API. We have the tools to get you going, including full Visual Studio Project and Item Templates and plenty of source code examples of existing Plugins on GitHub.

How to Enter

  1. Create a new Plugin for Xamarin that provides unique functionality
  2. Open source your Plugin under an app-store friendly OSS license (we like MIT)
  3. Upload your Plugin to NuGet with Documentation
  4. Follow the naming convention of: “FEATURE_NAME Plugin for Xamarin” for your NuGet
  5. Once published post a #PluginForXamarin tweet, like this:
    I just shipped PLUGIN_NAME #PluginForXamarin NUGET_URL!

Prizes

Each developer that completes and publishes a new valid Plugin for Xamarin or Xamarin.Forms will receive an Amazing and Exclusive Xamarin Swag Bag including a Xamarin Power Supply, Charles Petzold’s new Xamarin.Forms Book, a Xamarin Shirt, Embossed Notebook, and more! Our favorite Plugins will also be featured on Xamarin.com.

Today’s Plugins

Take a look at a few Plugins that already exist today to integrate into your project or see how they are structured:

Plugin Ideas

There are endless possibilities for potential Plugins, but here are few ideas to get you started.

  • Camera
  • Compass
  • Contacts
  • Dialogs & Notifications
  • File Transfer
  • Media Playback (audio)
  • Media Capture (audio, images, and video)

Rules & Regulations

All submissions must be made by January 5th, 2015 at 8am EDT. A valid Plugin for Xamarin adds functionality that does not exist in a current Plugin that has been published. All Plugins will go through a review process and considerations will include functionality, code quality, and reliability.

Jump Start Development

Tomorrow, Friday, December 19th at 9AM PST we invite you to join us for a live Google+ Hangout covering all the tools and concepts for creating a Plugin for Xamarin.

Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail
December 17, 2014

Webinar Recording: Mobile Enterprise Success with Xamarin and IBM

By

We recently announced our collaboration with IBM, allowing businesses to build fully native iOS, Android and Windows Phone applications with shared code – while also leveraging the robust integration, security and connectivity of the IBM MobileFirst platform. With this partnership, enterprises are able to deliver both the UI/UX quality consumers demand and the enterprise-grade backend and reliability that corporations require.

In this webinar, IBM and Xamarin technical executives discuss the IBM and Xamarin partnership, demo the IBM MobileFirst SDK for Xamarin, walk through the IBM MobileFirst platform, and answer audience questions.

View the presentation slides for this webinar here.

Additional Resources

If you’d like to learn more about the IBM MobileFirst SDK for Xamarin, visit the homepage here.

TwitterFacebookGoogle+LinkedInEmail
December 16, 2014

How to Update NuGet Packages for 64-bit

By

Apple is requiring all apps submitted after February 1st, 2015 to include a 64-bit binary. As a library creator, your developers will need to have access to 64-bit versions of your libraries before this deadline so that they can update their apps.

The new Unified API that we introduced for both Mac and iOS not only allows you to improve code sharing between the two platforms, but it also enables you to create 64-bit compatible libraries for your developers.

We introduced two new target frameworks for Unified API projects: Xamarin.iOS and Xamarin.Mac. Support for these new frameworks has been added to NuGet 2.8.3 which was released last month.

Xamarin iOS, Mac and NuGet

With these new Unified frameworks now being recognized by NuGet, you can create a NuGet package that targets the Unified iOS and Unified Mac frameworks. We have also created a set of Portable Class Library (PCL) profiles for the Unified frameworks which allow you to add NuGet packages that have compatible Portable Class Libraries, such as Json.NET, into your Unified projects.

Now, let’s take a look at what software you need to be able to add NuGet packages to Unified projects and how to create a NuGet package that supports Unified project.

Getting Ready to Use NuGet Packages with Unified Projects

In order to fully support adding NuGet packages to Unified projects, you will need to use NuGet 2.8.3 or above and have the Xamarin Portable Profiles for Unified installed. Additionally, you will need the latest Beta releases with the finalized Unified API when creating 64-bit libraries.

Software needed on Windows

The simplest way to upgrade NuGet inside Visual Studio is to use the extension manager:

  • Select Extensions and Updates from the Tools menu.
  • In the Extensions and Updates dialog, select the Updates tab and then select Visual Studio Gallery.
  • If NuGet Package Manager for Visual Studio is listed as an update, then select it and click the Update button.

Extensions and Updates Dialog NuGet Update

Software needed on Mac

  • Xamarin Studio 5.7 or above.
  • Mono 3.12 or above.
  • Xamarin.iOS 8.6

Creating a NuGet Package for Unified Projects

A NuGet package can be installed into different project types that target different frameworks if it contains files for those frameworks. The NuGet package indicates it supports a particular target framework by containing directories named after that framework. In each of these directories, the NuGet package will contain your files that are specific for that target framework.

To have your NuGet package explicitly target Xamarin.iOS and Xamarin.Mac your .nuspec file should contain a section similar to the one shown below below:

<files>
    <file src="iOS\bin\Release\*.dll" target="lib\Xamarin.iOS10" />
    <file src="Mac\bin\Release\*.dll" target="lib\Xamarin.Mac20" />
</files>

The target directory is the important part and should be specified as shown above. The src attribute points to the assemblies that should be used with that particular target framework. The created NuGet package should have a directory structure that looks like the following:

NuGet Unified Lib Directories

When you install the above NuGet package into a Unified iOS project the assembly from the lib\Xamarin.iOS10 directory will be added as a reference. For a Unified Mac project, the assembly from the lib\Xamarin.Mac20 directory will be referenced.

For NuGet packages that contain Portable Class Libraries, the recommended approach is to not include Xamarin.iOS nor Xamarin.Mac in the lib directory name. This can happen if you are using NuGet.exe pack passing the project file as a command line argument on a machine that has the Xamarin Unified profiles installed.

The following PCL lib directory follows the recommendation:

lib\portable-net45+win+wpa81+wp80

Whilst the following PCL lib directory should be avoided:

lib\portable-net45+win+wpa81+wp80+Xamarin.iOS10

The reason for this is to ensure your NuGet package can be installed into projects on machines that do not have the Xamarin Unified PCL profiles installed or do not have a version of the NuGet Package Manager installed that has support for the Unified frameworks.

Here are a few example NuGet packages that include assemblies that explicitly target Xamarin Unified projects:

  • ModernHttpClient – Write your app using System.Net.Http, but drop this library in and it will go drastically faster.
  • Splat – A library to make things cross-platform that should be.
  • Xamarin.Forms – Build native UIs for iOS, Android, and Windows Phone from a single, shared C# codebase.

Learn More

If you would like to learn more about the Unified API and NuGet here are some resources:

TwitterFacebookGoogle+LinkedInEmail
December 15, 2014

Xamarin Android Player Update Brings New Features & Devices

By

Released just two months ago during the Xamarin Evolve 2014 keynote, the Xamarin Android Player has helped ease a major pain point in Android development, the emulator. Xamarin Android Player Nexus 7Our Android Player is a high-speed hardware accelerated emulator, available on both Mac and PC, that integrates directly into Xamarin Studio and Visual Studio. Now, we’re exited to release a brand new update for the Android Player with several fixes and new features that will make developing Android apps even more enjoyable.

Get the Update

If you haven’t installed the Xamarin Android Player, head over to its download page and get started. If you already have the current preview installed, all you have to do is open up the Android Player, select the Update tab, and click Update.
New Update

New Device Images

Once you have the latest version of the Xamarin Android Player installed, the first thing you will notice is some new Android devices available to download. We’ve added new screen resolutions and form factors, including the Nexus S and Nexus 7 devices, enabling you to test your app’s appearance on phone and tablet.

Xamarin Android Player New Devices

We are continuously adding new system images, so be sure to check back because they will automatically appear in the list.

Naming & Duplicating

A major feature of this release is the ability to rename your emulators. When you download an emulator image for the first time, you will automatically be prompted to give it a name so you can recognize it immediately. This is very important, as you are now able to create full duplicates of any emulator image that you have from a brand new context menu. You can get device information, rename, reset, delete, or duplicate with a single click.

Duplicate Device Android Player

Learn More

To learn more about the Xamarin Android Player, be sure to read the full documentation on how to get started.

TwitterFacebookGoogle+LinkedInEmail
December 11, 2014

Apple’s February 1st Deadline and Xamarin 64-bit Support

By

In October, Apple announced that starting in February, submissions to the App Store must be built against the iOS 8 SDK and must include 64-bit support. Additionally, apps already published in the App Store must meet the requirements as of June 1st, 2015.

We have made significant progress on our Unified API that brings improved code-sharing for our Mac and iOS products as well as 64-bit support to those platforms. We expect the Stable release of our Unified API to be released in mid-January, so please watch for communications about that release to migrate your iOS apps to the Unified API. The migration should not take more than a day for most apps.

What you need to know:

  • Today: The latest Unified API build is available on our Alpha channel, and we strongly encourage all library developers to update any NuGet, Components, or other published libraries they maintain for iOS to use the Unified API. If you are publishing an iOS Component in the Xamarin Component Store, please use this alpha release to update and submit your updated Component this month. The Unified API template previews currently in Stable are deprecated and should not be used.
  • Mid-January: Unified API will be published on our Stable channel in Xamarin Studio and Visual Studio, and all Xamarin published Components in our Component Store will be upgraded to support the Unified API. This is when we recommend you start porting your iOS apps to 64-bit. This release contains a migration assistant for Xamarin Studio and Visual Studio that will upgrade your Classic 32-bit projects to dual 32/64 with Unified APIs.
  • February 1st: All new apps and app updates published to the Apple App Store must be built with 64-bit support.

ios and osx logos

What To Do Today:

If you are a developer with NuGets, Components, or Plugins that target iOS, you should get started right away porting your library to 64-bit with the Unified API release currently in the Alpha channel so that your library is ready to be consumed in 64-bit applications. The below resources can help you.

If you are an app developer, you should prepare now, and then migrate your app in early January when the current version of the Unified API is released to the Stable channel. The below resources can help you prepare.

We have a full guide on our documentation site to help you plan what you need to do. Here are a few important topics to read through before you start your migration.

We have provided simple manual migration steps to upgrade, or you can use our migration assistant to handle most of the heavy lifting for you.

Installation

Additionally, Windows users with Visual Studio should:

To learn more, be sure to read our full Xamarin.iOS 8.6 release notes and documentation.

TwitterFacebookGoogle+LinkedInEmail
December 5, 2014

Creating Reusable Plugins for Xamarin.Forms

By

Xamarin.Forms enables you to share not only your app’s business logic, but also a shared user interface across iOS, Android, and Windows Phone mobile apps. Using Xamarin.Form’s built-in dependency service, it is extremely easy to get access to the native platform to expose rich functionality unique to the underlying platform. However, what happens once you write this code and want to share it between other apps you are building or with developers all over the world? Using the power of the dependency service, portable class libraries (PCL), and NuGet, sharing this code is also straightforward. Today, I want to show you how easy it is to create your own reusable plugin for Xamarin.Forms.

The Idea

Cross Settings LogoUsually an idea for a plugin comes directly from developing an application. A while back, I ran into the issue of having a common API to save settings across all platforms from shared code. That is how my cross-platform settings plugin was born and published to NuGet. Recently, I wanted to have a way to somehow vibrate the phone from shared code, so let’s see how to build and share this functionality.

The Interface

Our plugin will start with a simple interface inside of a PCL describing the functionality we would like to expose. First, let’s create a new PCL. I prefer to name the solution after the functionality I am exposing and follow this naming scheme:

  • PCL: Company.Functionality.Abstractions
  • iOS: Company.Functionality.iOS
  • Android: Company.Functionality.Android (renaming the default namespace to .Droid so it doesn’t conflict).
  • Windows Phone: Company.Functionality.WinPhone

Creating New PCL

Now we just need to create and populate our interface. We are going to simply define and implement one method that accepts a measure of time for how long to vibrate the device.

public interface IVibrate
{
  /// <summary>
  /// Vibrate the phone for specified amount of time
  /// </summary>
  /// <param name="milliseconds">Time in Milliseconds to vibrate (500ms is default)</param>
  void Vibration(int milliseconds = 500);
}

Platform Libraries

With the interface in place, we will want to create three new class libraries, one for each project type: iOS, Android, and Windows Phone (silverlight). Once we have our libraries setup, we will need to add the PCL that we just created and also add Xamarin.Forms NuGet to our iOS, Android, and Windows Phone projects to start implementing our IVibrate interface.

FullSolutionSetup

Android Implementation

The implementation on Android is pretty straight forward. We are able to use Xamarin.Forms to get our current Context and ask for the VibratorService. After a few checks to make sure no one is passing in low numbers, and that the device has a vibrator, we will execute the vibrate command.

public void Vibrate(int milliseconds = 500)
{
  using(var v = (Vibrator)Forms.Context.GetSystemService(Context.VibratorService))
  {
    if (!v.HasVibrator) {
      Console.WriteLine("Android device does not have vibrator.");
      return;
    }
    if (milliseconds < 0)
      milliseconds = 0;
    try {
      v.Vibration(milliseconds);
    }
    catch(Exception ex) {
      Console.WriteLine("Unable to vibrate Android device, ensure VIBRATE permission is set.");
    }
  }
}

iOS Implementation

On the iOS side of things, this might be our easiest implementation. Living inside of AudioToolbox is SystemSound, which has a way to vibrate the device. Unfortunately, there is no fine grain control over the length, so we will have to document this in the Readme file of our plugin.

/// <summary>
/// Vibrate device with default length
/// </summary>
/// <param name="milliseconds">Ignored (iOS doesn't expose)</param>
public void Vibration(int milliseconds = 500)
{
  SystemSound.Vibrate.PlaySystemSound();
}

Windows Phone Implementation

Windows Phone also has a simple API to vibrate the device with Microsoft.Devices.VibrateController. We simply need to grab the default VibrateController and call start.

public void Vibration(int milliseconds = 500)
{
  var v = VibrateController.Default;
  if (milliseconds < 0)
    milliseconds = 0;
  v.Start(TimeSpan.FromMilliseconds(milliseconds));
}

Pulling Everything Together

With everything fully implemented, we now need to finalize a few Xamarin.Forms details and package up our NuGet. Since Xamarin.Forms uses the built in dependency service to allow anyone to access platform specific functionality we need to make sure we export each of our projects:

[assembly:Dependency(typeof(Vibrate))]
namespace Refractored.Xam.Vibrate.WinPhone
{
  //code
}

Inside of each project, we need to ensure that we do not link away our assembly when the application using our assembly is compiled. To ensure this doesn’t happen, simply create an empty static Init method in each of the three projects. The Readme file will need to tell anyone that is using our library that they should call Vibrate.Init(); after calling the Xamarin.Forms Init(); methods.

public static void Init() { }

Create the NuGet and Test

All that is left to do is to create our NuGet package’s nuspec, which defines what dlls get packaged and deployed for each project type. There is great documentation on how to do this on the NuGet website; however, the important part is that you package your Abstraction library into a PCL and all three platforms. Additionally for iOS, Android, and Windows Phone, you should package each of your platform specific libraries. I tend create and package XML documentation and the pdb file along with the dlls and name the package with the naming scheme of Feature Plugin for Xamarin.Forms. Here is what my nuspec looks like:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
   <metadata minClientVersion="2.8.1">
       <id>Xam.Plugins.Forms.Vibrate</id>
       <version>1.0.0.0</version>
       <title>Vibrate Plugin for Xamarin.Forms</title>
       <authors>James Montemagno</authors>
       <dependencies>
         <dependency id="Xamarin.Forms" version="1.2.3.6257" />
       </dependencies>
   <!--More Metadata-->
   </metadata>
   <files>
     <!--Core PCL-->
    <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.dll" target="lib\portable-net45+wp8+win8+MonoAndroid10+MonoTouch10\Refractored.Xam.Vibrate.Abstractions.dll" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.xml" target="lib\portable-net45+wp8+win8+MonoAndroid10+MonoTouch10\Refractored.Xam.Vibrate.Abstractions.xml" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.pdb" target="lib\portable-net45+wp8+win8+MonoAndroid10+MonoTouch10\Refractored.Xam.Vibrate.Abstractions.pdb" />
     <!--Win Phone-->
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.dll" target="lib\wp8\Refractored.Xam.Vibrate.Abstractions.dll" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.xml" target="lib\wp8\Refractored.Xam.Vibrate.Abstractions.xml" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.xml" target="lib\wp8\Refractored.Xam.Vibrate.Abstractions.pdb" />
     <file src="..\Refractored.Xam.Forms.Vibrate.WinPhone\bin\Release\Refractored.Xam.Forms.Vibrate.WinPhone.dll" target="lib\wp8\Refractored.Xam.Forms.Vibrate.WinPhone.dll" />
     <file src="..\Refractored.Xam.Forms.Vibrate.WinPhone\bin\Release\Refractored.Xam.Forms.Vibrate.WinPhone.xml" target="lib\wp8\Refractored.Xam.Forms.Vibrate.WinPhone.xml" />
     <file src="..\Refractored.Xam.Forms.Vibrate.WinPhone\bin\Release\Refractored.Xam.Forms.Vibrate.WinPhone.xml" target="lib\wp8\Refractored.Xam.Forms.Vibrate.WinPhone.pdb" />
     <!--Xamarin.Android-->
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.dll" target="lib\MonoAndroid10\Refractored.Xam.Vibrate.Abstractions.dll" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.xml" target="lib\MonoAndroid10\Refractored.Xam.Vibrate.Abstractions.xml" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.pdb" target="lib\MonoAndroid10\Refractored.Xam.Vibrate.Abstractions.pdb" />
     <file src="..\Refractored.Xam.Forms.Vibrate.Android\bin\Release\Refractored.Xam.Forms.Vibrate.Droid.dll" target="lib\MonoAndroid10\Refractored.Xam.Forms.Vibrate.Droid.dll" />
     <file src="..\Refractored.Xam.Forms.Vibrate.Android\bin\Release\Refractored.Xam.Forms.Vibrate.Droid.xml" target="lib\MonoAndroid10\Refractored.Xam.Forms.Vibrate.Droid.xml" />
     <file src="..\Refractored.Xam.Forms.Vibrate.Android\bin\Release\Refractored.Xam.Forms.Vibrate.Droid.xml" target="lib\MonoAndroid10\Refractored.Xam.Forms.Vibrate.Droid.pdb" />
     <!--Xamarin.iOS-->
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.dll" target="lib\MonoTouch10\Refractored.Xam.Vibrate.Abstractions.dll" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.xml" target="lib\MonoTouch10\Refractored.Xam.Vibrate.Abstractions.xml" />
     <file src="..\Refractored.Xam.Vibrate.Abstractions\bin\Release\Refractored.Xam.Vibrate.Abstractions.pdb" target="lib\MonoTouch10\Refractored.Xam.Vibrate.Abstractions.pdb" />
     <file src="..\Refractored.Xam.Forms.Vibrate.iOS\bin\iPhone\Release\Refractored.Xam.Forms.Vibrate.iOS.dll" target="lib\MonoTouch10\Refractored.Xam.Forms.Vibrate.iOS.dll" />
     <file src="..\Refractored.Xam.Forms.Vibrate.iOS\bin\iPhone\Release\Refractored.Xam.Forms.Vibrate.iOS.xml" target="lib\MonoTouch10\Refractored.Xam.Forms.Vibrate.iOS.xml" />
   </files>
</package>

With the NuGet package all ready to go we are now able to create a new Xamarin.Forms project and install our NuGet locally before publishing by going into the NuGet Package Manager and specifying a path to our NuGet Packages that were just generated.

NuGetPackageManager

Distributing

As long as you have a NuGet account created you are now able to externally distribute your NuGet package. Read through the distribution documentation for the few steps that it takes to do this.

Using this simple plugin architecture you are easily able to create highly reusable and shareable plugins across all of your Xamarin.Forms projects. You will find this Vibrate plugin live on NuGet right now and you can browse the full documentation and source code on GitHub. In addition to creating Xamarin.Forms specific NuGet packages you are also able to create full NuGet packages that span all platforms without using the dependency service. To see an example of this be sure to take a look at my Xamarin.Plugins GitHub Repo or Paul Betts’ Akavache project.

TwitterFacebookGoogle+LinkedInEmail
December 1, 2014

Getting Started with Xamarin and IBM Worklight

By

One of the many exciting announcements at Evolve this year was our partnership with IBM, which also introduced the IBM MobileFirst SDK for Xamarin. The IBM MobileFirst SDK for Xamarin enables C# developers to build rich native enterprise grade mobile apps for iOS and Android devices by seamlessly integrating with the IBM Worklight server.

Xamarin-IBM

IBM Worklight is a middleware platform to secure mobile apps, manage their lifecycle and integrate them into the enterprise. This platform provides a single secure point of integration into the enterprise and enables management of mobile solutions. IBM MobileFirst SDK for Xamarin is a rich set of client side APIs that helps build mobile apps to connect, secure and manage the apps using IBM Worklight. To learn more, be sure to check out Greg Truty’s talk on Connecting Xamarin Apps with IBM Worklight from the Evolve videos. Also, Join IBM and Xamarin technical executives on Thursday, December 11 at 8 am PST/ 11 am EST/ 5 pm GMT for a live webinar.

Adding IBM MobileFirst SDK to your project

First things first, you need an instance of IBM Worklight server on your development machine to run your project locally. Download and install the Worklight CLI (Command Line Interface) from the IBM Worklight download page. Now, create a new solution and add the IBM MobileFirst SDK component to it.

Xamarin-IBM-Add-Component

Adding Worklight Add-In to Xamarin Studio

IBM MobileFirst SDK also includes an extension for Xamarin Studio that enables developers to configure and access IBM Worklight server locally. To add this extension to Xamarin Studio, click on Xamarin Studio (on Mac) or Tools (on Windows) and click Add in Manager. Click Install from file… and navigate to <Solution Folder>/Components/ibm-worklight-<version>/component/addin  and select IBMWorklight.IBMWorklight_<version>.mpack and install it. Restart Xamarin Studio and Enable the Add-in.

Xamarin-Studio-IBM-Worklight-Addin

Once the Add-in is installed, be sure to check if the JDK and Worklight CLI path is configured correctly. Go to Preferences (Tools->Options in case of Windows) and navigate to IBM Worklight.

Xamarin-Studio-IBM-Worklight-Addin-Preferences

Running IBM Worklight Server locally

In Xamarin Studio, Click on Tools -> IBM Worklight -> Start Server.

Xamarin-Studio-IBM-Worklight-StartServer

Please note, on the first run, the server may take a while to start. This operation will also automatically create a Worklight project in the server. To access your projects on the server, click on Open Console from the same menu. Use the username: admin and password: admin to login to the IBM Worklight console and you will see the IBM Worklight project listed there.

Configuring the Xamarin.iOS and Xamarin.Android projects

Once IBM Worklight project is setup and is running locally, you need to configure your iOS and Android projects to connect to it. The Worklight SDK on iOS and Android needs a property file that contains information on how to connect to the Worklight server. This information is pre-populated with some data (like the IP address of the server, application name, etc). These files get created automatically when the server is first run. Now, add them to your projects.

Android

  • Add the < Solution Folder>\worklight< SolutionName>\apps\android< SolutionName>\wlclient.properties file to the Xamarin.Android Assets folder and set the build action to AndroidAsset.

iOS

  • Add the < Solution Folder>\worklight< SolutionName>\apps\iOS< SolutionName>\worklight.plist file to the Xamarin.iOS resources folder and set the build action to BundleResource.

Code

IBM MobileFirst SDK provides a unified API on Xamarin so developers can write all the common code in a shared project. The code that essentially needs to reside in a platform project is the code for initialization of IWorklightClient.

Initializing IWorklightClient on Xamarin.Android

public class MainActivity : Activity
{
    IWorklightClient client = Worklight.Xamarin.Android.WorklightClient.CreateInstance (this);
    //...
}

Initializing IWorklightClient on Xamarin.iOS

public partial class SampleiOSViewController : UIViewController
{
    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        IWorklightClient client =  Worklight.Xamarin.iOS.WorklightClient.CreateInstance ();
        //...
    }
}

Connecting to Worklight Server
Once you have created the instance of IWorklightClient, you can pass this object to your shared code to further perform operations on IBM Worklight server (for e.g. connect to the server, register a challenge handler for authentication, invoking a procedure, or even for client side & server side logging).  To connect, call the client.Connect():

public async Task Connect()
{
    string appRealm = "SampleAppRealm";
    ChallengeHandler customCH = new CustomChallengeHandler (appRealm);
    client.RegisterChallengeHandler(customCH);
    WorklightResponse task = await client.Connect ();
    // client side loggin
    client.Logger("Xamarin").Trace ("connection");
    // server side logging for analytics
    client.Analytics.Log ("Connect response : " + task.Success);
    return task;
}

The following code shows how to invoke a procedure on the server:

WorklightProcedureInvocationData invocationData = new WorklightProcedureInvocationData("SampleHTTPAdapter", "getStories", new object[] {"technology"});
WorklightResponse task = await client.InvokeProcedure(invocationData);
StringBuilder retval = new StringBuilder();
if (task.Success)
{
    JsonArray jsonArray = (JsonArray)task.ResponseJSON["rss"]["channel"]["item"];
    foreach(JsonObject title in jsonArray)
    {
        System.Json.JsonValue titleString;
        title.TryGetValue("title",out titleString);
        retval.Append(titleString.ToString());
        retval.AppendLine();
    }
}

Check out the Getting Started guide on the component page for more details. Additionally, be sure to join us for a live webinar on December 11th to learn how to achieve Mobile Enterprise Success with Xamarin and IBM.

Register Now


Discuss this blog post in the Xamarin Forums

TwitterFacebookGoogle+LinkedInEmail