August 26, 2014 4:57 GMT

Introduction to Android Material Design

We recently announced preliminary support for Android L Developer Preview, and as you dive into playing with the new SDK you will immediately notice one of the biggest enhancements is the brand new Material Design concepts that Google has developed. This is the first time that Google has created a full design specification for developers to work off of when creating Android applications. In this post I will introduce the main concepts and impact of Material Design for Xamarin developers including:

  1. Theming and Accenting your Android App
  2. Elevation and View Shadows
  3. New Drawable Capabilities

material design

Additionally, Jérémie Laval and I will be giving a wonderful session at this year’s Evolve entitled Android Material Design from Concept to Implementation. In this session we will cover every aspect of Material Design including design concepts, new widgets, animations, compatibility, and so much more.

Setting Up Your Project

Before we get started be sure you have all of the latest Xamarin.Android and Android SDKs installed. Be sure to read our Android L Developer Preview Support announcement for full details of how to get started. Once you have your project open you will want to update the Target, Minimum, and Compile Target Framework found under your project options General and Android Application settings. In the future, you will want to change your Minimum Target to support older frameworks, but since Android L is not officially released you won’t be able to ship L apps to Google Play yet. Additionally, be sure to create an Android L emulator or have a device such as a a Nexus 5 or 7 that can run the Android L Developer Preview.

MinTarget Android L
General Target

Material Theme

When developing Android applications you are able to use and customize themes to brand your application. You might already be familiar with the Holo theme that has become very popular in the last few years. Android L introduces a brand new Material Theme in multiple flavors that you are able to use in your application. These will not only theme your ActionBar, but will give you a refreshed style for all of the controls. Here are the three themes available:

  • @android:style/Theme.Material (dark theme)
  • @android:style/Theme.Material.Light (light theme)
  • @android:style/Theme.Material.Light.DarkActionBar

Android Material Themes

To start to use these themes you will first need to create a new folder in the Resources folder called values-v21. This is where any of your Material Theme customization should be placed. Since you will most likely need to support older versions of Android you would want to fallback to a supported Theme in the Resources/values folder for older versions. With this folder in place you should now create a new styles.xml file and create a new theme for your application that inherits from one of the themes above (to support older versions create a styles.xml in your /values folder and create a theme with the same name there). Here is a new theme for my app called AppTheme which is of the default dark material theme:

<resources>
  <style name="AppTheme" parent="android:Theme.Material">
  <!--Customizations Here-->
  </style>
</resources>

To use this theme you simple need to add it to your AndroidManifest.xml under the application node:

<application android:label="My Awesome App" android:theme="@style/AppTheme">
</application>

Alternatively, you can set it on a specific Activity with the Theme attribute.

[Activity (Label = "MaterialTheme",
           Theme = "@style/AppTheme")]

Add Branding

CustomThemeSometimes the default color schemes might not match your companie’s brand or you might just not like them. No worries, as Google has made it extremely simple to customize the Material themes by setting these three properties in your theme:

  • android:colorPrimary – Your app’s branding color
  • android:colorPrimaryDark – Darker variant of colorPrimary, used by default for status bar
  • android:colorAccent – Accent color for UI controls

Here is what a Xamarin based theme might look like with these colors:

<style name="AppTheme" parent="android:Theme.Material.Light">
  <item name="android:colorPrimary">#3498DB</item>
  <item name="android:colorPrimaryDark">#2C3E50</item>
  <item name="android:colorAccent">#B455B6</item>
</style>

You can customize the status bar with the android:statusBarColor attribute.

Elevation

When developing for Android L you are no longer restricted to just the X and Y properties of a control and have the ability to adjust the Z value to elevate controls off the page. To achieve this we are able to set the android:elevation attribute on our element using a specific size such as 2dp, which is used to determine the size of the shadow.

The shadow is drawn against the view’s background drawable. Let’s say you wanted to add an elevation to a TextView. You could set a background color and elevation, but you can spice it up and create a circle drawable for the TextView’s background with a specific fill color:

<!-- Resources/drawable/mycircle.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
    <solid android:color="#3498DB" />
</shape>

You would then set the elevation and background attributes on the TextView:

<TextView
  android:id="@+id/my_circle_text"
  ...
  android:background="@drawable/mycircle"
  android:elevation="2dp" />

Here are three lined up with different elevations:
Android Elevations

You are also able to set a translation of a view for animations using the View.SetTranslationZ method.

Drawable Tinting

A unique addition to Android L is that you can now define bitmaps as an alpha mask and easily tint them by using the android:tint attribute. You no longer have to create multiple versions of your assets to simply change their colors. Mixed with the new theme color attributes and the brand new Palette Library that enables you to get colors samples from an image you can do some amazing things. Here is an example of a white Xamarin logo tinted in a few different colors with a circle background:

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal">
    <ImageView
        ...
        android:src="@drawable/xamarin_white"
        android:background="@drawable/mycircle"/>
    <ImageView
        ...
        android:src="@drawable/xamarin_white"
        android:background="@drawable/mycircle"
        android:tint="#2C3E50"/>
    <ImageView
        ...
        android:src="@drawable/xamarin_white"
        android:background="@drawable/mycircle"
        android:tint="#B4BCBC"/>
</LinearLayout>

XamarinTint2

So Much More

This is just an introduction to Material Design, but there is so much more including animations, notifications, CardView, and RecyclerView just to name a few. Be sure to check out our Android L samples on GitHub and our Android Samples page.

Discuss this post in the Xamarin forums.

August 26, 2014 12:57 GMT

IBM Joins Xamarin Evolve 2014

IBM LogoWe’re excited to announce IBM as a Diamond sponsor of Xamarin Evolve 2014. Greg Truty, Distinguished Engineer, Chief Architect SWG Mobile Build & Connect at IBM, will lead two sessions at the conference focused on how to easily build cross-platform native apps on the client-side with Xamarin, powered by the Worklight Server on the backend.

“Connecting Xamarin Apps with IBM Worklight” is a hands on session designed to show you the power of Xamarin and Worklight together. Greg will cover how to connect native Xamarin apps to IBM Worklight Server for easy integration into your enterprise’s environment, and you’ll walk away with the ability to leverage existing resources and infrastructure for mobile, as well as manage cloud-based services directly to the end-user device.

Creating a successful enterprise app that employees actually adopt into their workflow requires much more than just delivering a great UI and UX on the employee’s choice of device. It doesn’t matter how good the app is if employees don’t know about it, can’t easily get it onto their device, or if it fails to keep up with new workflow processes and/or device features that make their lives easier. Greg’s second session, “Keeping Apps Relevant: Deployment, Support, and Management Best Practices for Your Enterprise Mobile Apps,” will teach you best practices for managing the last, but not least, parts of the mobile application lifecycle.

Don’t miss your ticket to native mobile app expertise – register here to join us at Xamarin Evolve 2014 today.

August 25, 2014 4:53 GMT

Salesforce Joins Xamarin Evolve 2014

Salesforce Cloud LogoWe’re happy to announce that Salesforce will be joining the roster of amazing industry-leaders that are sponsoring and speaking at Evolve 2014, October 6-10 in Atlanta, Georgia. Join us there for the mobile development event of the year for cutting-edge enterprise content, networking, and more, including a Salesforce session from Grant Davies, founder and CEO of Bluetube Interactive, a Premier Xamarin Consulting Partner.  Grant is a seasoned Evolve speaker who co-presented the Kimberly-Clark field sales app with Kimberly-Clark at Xamarin Evolve 2013.

Grant’s talk, “The Salesforce1 Platform: The Enterprise Back-End for All Your Mobile Apps,”Grant Davies will focus on building cross-platform apps faster with Xamarin and Salesforce. You’ll learn how to easily connect Xamarin apps to the Salesforce1 Platform, a scalable enterprise back-end for mobile apps with a variety of mobile services that make apps more contextual, user-centric, engaging, secure, and scalable.

Register now to take your mobile apps to the next level with Xamarin and Salesforce at Xamarin Evolve 2014.

August 24, 2014 9:29 GMT

Enhanced Xamarin.Android Designer with Tools Attributes

The announcement of Android L Developer Preview support for Xamarin.Android developers brings tons of goodies to start playing around with, but did you know that there has been several updates to the Android designer as well? If you look through the release notes of Xamarin Studio 5.3 you will several enhancements such as the new Android L & Wear themes and devices, but also support for Action Bar menu icons and navigation style via the menu and actionBarNavMode XML attributes. More information on those attributes can be found at http://tools.android.com/tech-docs/tools-attributes#TOC-tools:menu. So, let’s take a look at these new features in the Alpha Channel.

Tools XMLNS

To take advantage of any of the features you will need to add this attribute to your root node in your layout:

xmlns:tools=”http://schemas.android.com/tools”

So your layout might look something like this:



Now we can take advantage of the tools and other attributes and add them onto our root node.

Menu

Normally your menu’s live completely separate away from your layouts, however the tools attributes allow you to get a preview right in the designer. First we will want to add the tools attribute:

tools:menu=”menu_name”

Notice that we don’t use any @menu or anything like this. It is just referencing the name in the Resource/Menu folder. This will give us a nice preview:

Navigation Style

Additionally, you might be using tabs or a spinner as part of your navigation in your ActionBar and you can now visualize this with another attribute

tools:actionBarNavMode=”tabs”

The actionBarNavMode can be set to tabs, list, or standard. I actually use a list navigation in My StepCounter, so this is great to be able to visualize:



That is just the beginning as Jérémie Laval has hinted at some more awesome updates coming soon:


Issues with Menu?

If you are having issues with the tools:menu property you might need to remove the Unicode BOM from your xml file. This is just a side effect currently of how the xml files are generated. Once you delete the 3 invisible bytes you will be able to browse things just fine. It is relatively easy and quick to do this. First make sure the file is CLOSED inside of Xamarin Studio. Then you will want to say open in HEX Editor:



Now simply delete the first 3 bytes on the right hand side that:
Alright you are all set now :)
August 23, 2014 4:21 GMT

Clean ViewModels with Xamarin.Forms

I like to keep my view models focused on just the code needed for a particular view, and to keep as much plumbing and infrastructure code out of the view model as possible. I've already covered how to use Fody to implement INotifyPropertyChanged and use auto properties in our view models. Now I want to cover how to connect the ViewModel to the View automatically.

The most straight forward way to access our view model would be to simply instantiate it in the constructor of our view.

using Xamarin.Forms;

namespace CleanViewModels
{    
    public partial class UserPage : ContentPage
    {   
        UserViewModel _viewModel;
        public UserPage ()
        {
            InitializeComponent ();
            _viewModel = new UserViewModel ();
            BindingContext = _viewModel;
        }
    }
}

This technique requires us to add this bit of code to every view that uses a view model though. I'd prefer to have that handled automatically for each view.

View Model

Let's begin by creating a marker interface for our view model. At its simplest, this interface is just used to constrain the generic type later.

namespace CleanViewModels  
{
    public interface IViewModel {}
}

Each of our view models will need to implement our marker interface.

using PropertyChanged;
using System.Windows.Input;
using Xamarin.Forms;

namespace CleanViewModels
{
    [ImplementPropertyChanged]
    public class UserViewModel : IViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public ICommand LoadUser {
            get {
                return new Command (async () => {
                    this.FirstName = "John";
                    this.LastName = "Doe";
                });
            }
        }
    }
}

View Page

Now that we have the ViewModel defined, we can wire it up to the View. We'll create a new class, named ViewPage.cs. This will be our base class for each view. We will derive ViewPage from ContentPage and pass in the type of our view model. In the constructor, we will create a new instance of the requested ViewModel and set the view's BindingContext to the current ViewModel. We also provide a read only property to be able to access the view model in the page, if needed.

using Xamarin.Forms;

namespace CleanViewModels
{
    public class ViewPage<T> : ContentPage where T:IViewModel, new()
    {
        readonly T _viewModel; 

        public T ViewModel
        {
            get {
                return _viewModel;
            }
        }

        public ViewPage ()
        {
            _viewModel = new T ();
            BindingContext = _viewModel;
        }
    }
}

View

When using XAML in Xamarin.Forms, I was not able to set the root to use ViewPage<T> directly. Instead, we will create a wrapper class that defines the parameter for us, so that we can use the wrapper class in XAML.

namespace CleanViewModels
{    
    public class UserPageBase :  ViewPage<UserViewModel> {}

    public partial class UserPage : UserPageBase
    {   
        public UserPage ()
        {
            InitializeComponent ();
        }
    }
}

Once the code behind is defined, we can add our xml namespace local: and create our view in XAML as UserPageBase

<?xml version="1.0" encoding="UTF-8"?>  
<local:UserPageBase  
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="CleanViewModels.UserPage" 
    xmlns:local="clr-namespace:CleanViewModels;assembly=CleanViewModels">

    <ContentPage.Padding>
        <OnPlatform 
            x:TypeArguments="Thickness" 
            iOS="5,20,5,5" 
            Android="5,0,5,5" 
            WinPhone="5,0,5,5" />
    </ContentPage.Padding>

    <StackLayout>
        <Entry Text="{ Binding FirstName, Mode=TwoWay }" />
        <Entry Text="{ Binding LastName, Mode=TwoWay }" />

        <Button 
          Text="Load User"
          Command="{Binding LoadUser}"></Button>
    </StackLayout>
</local:UserPageBase>  

By using a base view page, along with Fody, we are able to keep our view models clean and focused only on the properties and commands that are needed for the view, thereby increasing the readability of the code.

Check out the sample project on my Github repo.

August 22, 2014 4:08 GMT

Favorite Xamarin Studio Feature Contest Winners!

Xamarin’s new $25 per month Indie subscriptions, brings new opportunities to get involved with Xamarin for developers around the world. Our latest contest was an opportunity to get to know more about users favorite Xamarin Studio’s features, and it’s exciting to read the different perspectives from all different types of Xamarin users.

Thank you to everyone who participated! There was one stand-out among the many contestants, and that’s Patrick Sullivan! In his blog, Patrick talks about NuGet Packet Manager, saying that, “the NuGet package manager integration into Xamarin Studio is one of the reasons I really wanted to try it out in the first place.”

Congratulations! You’ve won a 6-Month Xamarin Indie Subscription for iOS and Android.

nuget

Thank you to everyone who participated in the Favorite Xamarin Studio Feature contest! All valid entries will be receiving an exclusive Xamarin swag bag. If you didn’t manage to get an entry submitted this time, no worries; keep an eye on the Xamarin Blog for future contest announcements.

August 20, 2014 4:35 GMT

Amazon Joins Xamarin Evolve 2014

We’re excited to welcome Amazon as the first Gold Sponsor of Xamarin Evolve 2014, the must-attend event for mobile developers October 6-10 in Atlanta, Georgia. Amazon joins a growing list of industry-leading sponsors bringing great technical content, connections, and hacking opportunities to the event.

Amazon Logo

The conference line-up now includes two new technical sessions delivered by Amazon speakers David Isbitski and Tara Walker, covering Amazon Fire and Amazon Web Services.

Amazon Web Services LogoIn the “Mobile Ecosystem” track, Tara Walker, will show you how to build great mobile apps that leverage AWS Cloud services bringing identity management and data sync (Amazon Cognito), push notifications (Amazon SNS Mobile Push), cloud storage (Amazon S3), and a fully-managed NoSQL database (Amazon DynamoDB) to your mobile apps. Tara will take you on a step-by-step journey so you can see how to configure and add AWS services to your apps, and then integrate them into your backend architecture.

Amazon Fire PhoneIn the “Emerging Devices” track, David Isbitski, Worldwide Developer Evangelist for Amazon, will show you how to build native Amazon Fire Phone, Fire TV, and Kindle Fire Apps with Xamarin. This session will include both a walk-through of how to quickly use Xamarin to run your apps and games on Amazon devices, as well as an overview of how to get started and get noticed in the Amazon Appstore.

Register now to get your ticket to mobile expertise with Amazon Web Services and the Amazon Fire line of devices at Xamarin Evolve 2014!

August 20, 2014 12:44 GMT

Ultimate guide to ASP.NET MVC and Xamarin.Forms Mashups

In this blog I show you how to take an asp.net application and then code share both Razor Views and Business logic with a Xamarin.Forms native application. This integration will allow full sharing between the application, so changes to the Razor views or Business Logic will apply to both projects. The mobile application will also work completely offline in which the Razor Views and Business Logic run completely locally on the device.

And that’s just the start of it! Imagine being able to jump in and out of native/web elements, sharing razor views when it’s a good fit and then jumping into a gorgeous native UI when you like.

This blog takes a already existing ASP.NET MVC project that’s been setup as a sample application with typical Views, Script and Styles.

Video: Seamless Native and Hybrid

Video: 3Way Communication between C#/Native and Hybrid/JS Integration

Diagram: Shared Files Setup

Hybrid Razor File Setup

Diagram: Offline Support with Shared Views and Logic

Offline Mode

Step 1. Create new solutions

Create a new Xamarin.Forms PCL solution and place it in a directory next to the asp.net MVC project. Because we’re sharing files between projects the directory setup is important. In this case we can call it JellyBeanTracker.Mobile.

Step 2. Adding the external files and RazorTemplatePreprocessor

In this example I’ve added the files from the MVC project into the XF PCL project as ‘linked’ files. Create a new directory called ‘External’ and add the following files as per the screenshot. ps, to add files right click the directory and hit add files, Xamarin studio will then ask you if you’d like to link or copy files, in this case you need to link.

Screen Shot 2014-08-13 at 8.15.13 am

Secondly you need to add the javascript files and css files to the resources directory on each of the platform projects, as per screenshot.

Screen Shot 2014-08-13 at 8.20.55 am

For each of the razor files you need to right click->properties and set the Custom tool to the RazorTemplatePreprocessor.

Screen Shot 2014-08-13 at 8.22.15 am

Step 3. Clone and Add the MVCPolyfils into your Xamarin.Forms Project

Available here: https://github.com/rid00z/MVCPolyFils

Step 4. Use the Polyfils

On the Razor page remove @model and replace with @inherits System.Web.Mvc.WebViewPage<T> (from MVCPolyfils).

This step is required to have the file work in both MVC and the Xamarin.

Screen Shot 2014-08-19 at 9.29.47 pm

Step 5. Install Xamarin.Forms.Labs which has a HybridWebView

I’ve done a few modifications to the Xamarin.Forms.Labs project to get this to work and only just put it in my fork, so you’ll need to get the code from my fork until it gets put in the actual project.

https://github.com/rid00z/Xamarin-Forms-Labs

Step 6. Setup the Xamarin.Forms Project, with the Page and PageModels

This step requires knowledge of Xamarin.Forms, if you’ve not used Xamarin.Forms before then there’s some good videos over here: http://www.michaelridland.com/mobile/xamarin-hack-day-talks-thanks-retrospective/

Step 7. Sharing Business Logic and Offline

It’s possible to have shared business logic between both of the projects. You can share it via file linking, PCL or a shared project. In my sample application I’ve used file linking so it’s the same as the razor files.

In order to share business logic between asp.net and Xamarin Native you need to code your business logic classes against abstractions/interfaces. If we take a look at the JellyBeanGraph Calculator we can see that it uses a IDataSource for it’s calculations.

The IDataSource needs to be implemented in two or three places, two places if you’re not supporting offline and three place if you are supporting offline. As you can see in the sample project there’s two sources in the Xamarin project, a LocalDataSource and a RemoteDataSource. These two classes a switched between depending on if it’s online or offline.

LocalDataSource

RemoteDataSource

Step 8. Diff Logic in Razor Views using compiler directives

It’s not highly recommended to have logic within your Razor views but it is possible to have different view logic between the platforms. If you’re using file linking the best option is it use #ifdefs, to do this you need to add a compiler Symbol to the native project, as per screen shot.

Screen Shot 2014-08-14 at 8.10.36 am

Once you’ve setup the compiler Symbol you can then add setup a static IsNative boolean value in a shared file. As per below.

Screen Shot 2014-08-20 at 9.32.21 am

Finally you can add different functionality for the Native applications within your Razor views.

Screen Shot 2014-08-20 at 9.32.40 am

Step 8. Partial Views and Shared Partials

In the open source project I’ve release with this blog post there’s the ability to use Partial views within the Xamarin app. If you provide the classname as a string into the partial the framework will pick it up and run the razor view locally. In order to have the partials work on both the MVC and Xamarin application you need to have the partial views come from a static variable on a class.

Step 9. Combining the Javascript Logic

It’s also possible to take your javascript files and share them with Xamarin. Mostly they will just function as normal unless you’re doing ajax calls to collect the data. In the case you’re doing ajax calls and want to support offline then you need to communication back and forth between the C#/native and javascript.

There’s three type of communication available in this solution using the HybridWebView (soon to be)in Xamarin.Forms.Labs

a) Injecting javascript from c#

b) Calling a c# method from javascript

c) Calling a c# Func and returning into a closure

Step 9a. Injecting Javascript

Using the HybridWebView available in Xamarin.Forms you’re able to execute javascript from outside a webview. This is as easy as calling a method named InjectJavaScript, as per example below.

1
2
string data = JsonConvert.SerializeObject (PageModel.GraphData).Replace ("\r\n", "");
_hybridWebView.InjectJavaScript ("JellyBeanTrackerApp.buildChartStr('" + data + "');");

 Step 9b. Calling Native Methods

Also using the HybridWebView you’re able to call Native methods, so this is going from within javascript running in the web view out to a native method written in c#. As a little side note, this works with Mvvm so your business logic is contained within your view model.

Registering a method with the HybridWebView.

1
2
3
_hybridWebView.RegisterCallback ("EditVisible", (data) => {
  PageModel.EditVisible.Execute(data);
});

Calling the native method from javascript

1
2
3
$('#editVisible').click(function() {
  Native('EditVisible', JellyBeanTrackerApp.currentChartData);
});

The c# method that’s called from the javascript.

1
2
3
4
5
6
7
8
public Command<string> EditVisible
{
  get {
    return new Command<string> ((data) => {
      PushViewModel<ManageGraphPageModel>(data, true);
    });
  }
}

 Step 9c. Calling Native Funcs with Closure support

This one I’m a bit proud of as it’s pretty sweet. Using the HybridWebView you now have the ability to call a Native function and the return values of the Native function is injected back into the original closure. Also same as above this works with Mvvm.

Registering the Function in the WebView

1
2
3
_hybridWebView.RegisterNativeFunction ("GetGraphData", (input) => {
  return PageModel.GetGraphData(input);
});

Calling the function from javascript with the closure being called on return.

1
2
3
4
5
$('#getGraphData').click(function() {
    NativeFunc('GetGraphData', null, function (returnData) {
        JellyBeanTrackerApp.buildChartStr(returnData);
    } );
});

The c# function that runs

1
2
3
4
5
6
7
8
9
public Func<string, object[]> GetGraphData
{
  get {
    return (data) => {
      GraphData = new JellyBeanGraphCalculator (_dataSourceFactory.GetDataSource ()).GetGraphData();
      return new object[] { GraphData };
    };
  }
}

Step 10. Debugging from Safari

Another thing I should mention is Safari has the ability to debug UIWebViews, the setup details can be found here.

Just another (awesome)tool for the belt!

This is just one tool for the belt, it’s not the only mobile architecture that you can implement. There’s also the traditional Xamarin approach(Native UI for each platform) and Xamarin.Forms approaches which are still great architectures for mobile applications.

So when should you use this Hybrid type solution?

My personal belief is that using the HybridWebView is acceptable when the view is Not highly interactive as when interacting with a user you want to have everything looking and feeling native. Really it’s up to you to decided and initially it’s good to prototype and test within a device. Of course when you’ve got a large investment in web/mvc assets this is also a good choice.

All the code is available on https://github.com/rid00z/JellyBeanTracker, currently it’s only working with iOS devices. I will attempt add other platforms soon.

Thanks

 

 

The post Ultimate guide to ASP.NET MVC and Xamarin.Forms Mashups appeared first on Michael Ridland.

August 19, 2014 7:28 GMT

Major Xamarin.Mac Updates

We are happy to announce a few major updates to Xamarin.Mac. The first major update is the result of more than a year of development on our API bindings and Mono’s runtime which brings the following features to Xamarin.Mac:

  • 64-bit support
  • New 64-bit Frameworks
  • Support for lighter mobile profile
  • Easier code sharing between Mac and iOS

These features are available today in the Beta channel.

Yosemite OS X Logo On top of these new features we have been hard at work binding the new Mac OS X Yosemite APIs. We are pleased to announce support for Yosemite is now available. Since Yosemite is still an unreleased platform and may continue to change you will find these APIs in the Alpha channel along with all of the other features I mentioned earlier.

64-bit support & Easier Code Sharing

We recently announced the brand new Unified API for Xamarin.iOS and Xamarin.Mac. The Unified API allows developers to support both 32 bit and 64 bit applications with the same source code (as well as binaries) on both Mac and iOS.

In addition to this we also took the time to enhance the code sharing story between iOS and Mac. An example of this is that you no longer are required to add any namespace prefixes. This means code that looked like this:

#if MAC
using MonoMac.Foundation;
#elif IOS
using MonoTouch.Foundation;
#endif

Can now simply be written in one line:

using Foundation;

For more information, read our new Guides for Cross Platform Mac and iOS code.

New 64-bit Frameworks

With the introduction of our Unified API we are finally able to support all of those 64 bit-only frameworks that Apple has introduced in the last few years, including but certainly not limited to the many new 64 bit-only frameworks in Yosemite.
What's new in scene kit

Shadows in Scene Kit

Lightweight Profile

Also with the Unified API comes the ability for users to adopt Xamarin’s Mobile profile. The Mobile profile is the same API profile that we use on Android and iOS which has been designed to be linkable and have a much smaller footprint on disk than the regular desktop edition. This is convenient for applications going into the AppStore or that wish to share more code across Android and iOS.

Samples!

Many of our Mac samples are being ported to the Unified API and currently live in their own branch. In addition, we are starting to publish our internal ports of the Yosemite samples which can be found in the Yosemite directory.

August 19, 2014 7:25 GMT

Unified API with 64-bit Support for iOS and Mac

Today we are pleased to share some major improvements to the APIs for our iOS and Mac products.

ios and osx logos

Why a new API?

The Classic Xamarin.iOS and Xamarin.Mac APIs had two major flaws:

  1. They did not support 64 bit applications.
  2. They made iOS and Mac code sharing cumbersome.

As Mac OS X evolved, more and more frameworks became available only as 64 bit frameworks. Additionally, iOS recently made the 64-bit jump when the iPhone 5s was launched.

Last year we started a redesign for our 64-bit support, one that would meet the following goals:

  1. The same source code must work on both 32 and 64-bit platforms
  2. Libraries and binaries would run either in 32 or 64 bit modes, depending on the host platform and build settings, with no source code changes or recompilation required
  3. Improved code sharing story between our Mac and iOS products.

Enter The Unified API

The result of more than a year of development on our API bindings and Mono’s runtime is our Unified API, which we are introducing today as a preview feature. The Unified API accomplishes everything we set out to and so much more.

First, we addressed the 32/64 bit split, by surfacing an API that is 32/64 bit agnostic.

Second, we dropped the namespace prefixes. This makes sharing code between iOS and Mac apps less tedious to maintain and easier on the eyes. An example to demonstrate this is what you had to do before when you had to use a using:

#if MAC
MonoMac.Foundation;
#elif IOS
MonoTouch.Foundation;
#endif

With the Unified API you can simply use:

Foundation;

64bitThis means with the new Unified API we have not only made it easier to share common code across your iOS and Mac applications, but you are now able to take advantage of all of the new 64-bit APIs on each platform.

Get Started & Backwards Compatibility

The new Unified API is available now in the Beta channel. We made the new Unified API opt-in, which means there is no need to upgrade to this new API unless you want to take advantage of the features outlined above. Xamarin will continue to support the Classic API you are familiar with for both Mac and iOS alongside the Unified API indefinitely.

We have ported all of our Mac samples and our iOS samples to the new API so you can see what is involved. They are both maintained on a branch that for historical reasons is called “magic-types”.

We are currently working on both templates to get you started (or you can migrate on your own), as well as a migration assistant that will do the bulk of the port for you.

What is Missing?

We are aware that the following features are currently missing and we are working on them:

  • Binding Project Types, to easily call into native libraries
  • Complete templates for all the scenarios previously supported
  • Xamarin’s Components are not available yet
August 17, 2014 5:01 GMT

Adding a Windows Phone Project to an Existing Xamarin.Forms Solution

So, you've fired up Xamarin Studio, created a new Xamarin.Forms app for iOS and Android and your app is super successful. Now that the two major platforms are coded and deployed to their respective app stores, you'd like to add Windows Phone as well.

This is where Xamarin and particularly Xamarin.Forms really shines. It's possible to have your app running on a whole new platform in a matter of minutes.

Xamarin Studio does not support Windows Phone projects, so in order to create a new Windows Phone project, we will need to be using Xamarin Business Edition in Visual Studio on Windows. The .sln file is exactly the same between Xamarin Studio and Visual Studio and can be opened in either IDE. Simply commit your solution to source control on your Mac, pull it down on Windows, and open it in Visual Studio.

Add Windows Phone Project

Add Project -> Blank App (Windows Phone Silverlight)

At this point, we will only have iOS and Android projects so the first step is to add a Windows Phone project.

Right click on the solution and choose Add New Project. From the dialog, choose Visual C# -> Store Apps -> Windows Phone Apps -> Blank App (Windows Phone Silverlight)

Create the project in the existing solution folder, and give the project the extension .WinPhone (this is optional, but adheres to what the Xamarin.Forms wizard would have created).

Next, we'll get a wizard dialog asking which version of the Windows Phone SDK we want to use. The Xamarin.Forms wizard creates a Windows Phone 8.0 project, so we'll choose that same version here.

This will create the Windows Phone project for us and add it to the solution.

Add Xamarin.Forms

Now that the project is created, all we need to do is connect the Windows Phone project to our Xamarin.Forms app. This has two steps. First, we need to add the Xamarin.Forms Nuget packages to our Windows Phone project. When the Nuget package is installed, it creates a new folder named Toolkit.Content. We need to make sure that the files in this folder are set to Content/Copy Always.

Install-Package Xamarin.Forms

Next, we need to add a reference to our shared code project, which will be either a PCL or a Shared Project. This will allow us to access all of the Xamarin.Forms UI that we have already created.

Edit MainPage.xaml

The last task that we need to do is to change the XAML and the C# that was generated by default. With Xamarin.Forms, we won't be defining our UI in the platform specific projects, but we do need the MainPage to initialize the Xamarin.Forms framework for us.

All we need in the MainPage.xaml file is the following XAML.

<phone:PhoneApplicationPage  
    x:Class="SuperSuccessfulApp.WinPhone.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">
</phone:PhoneApplicationPage>  

Note : Be sure to change the x:Class attribute to your namespace

In the MainPage.xaml.cs file, add the following C#.

using Microsoft.Phone.Controls;  
using Xamarin.Forms;

namespace SuperSuccessfulApp.WinPhone  
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            Forms.Init();
            Content = SuperSuccessfulApp.App.GetMainPage().ConvertPageToUIElement(this);
        }
    }
}

Note : Be sure to change the relevant namespaces

At this point, we have a funtioning Windows Phone app, leveraging all of the work that we previously did for iOS and Android. The only remaining tasks would be to implement any custom renderers and/or platform specific interfaces, and add the appropriate icons and images.

August 16, 2014 12:47 GMT

Parallels: The best Android Emulator I've ever used

If you're doing Android development, a non-default VM is a must; the ARM Emulator is a complete pain to work with. There are several options based on QEMU and VirtualBox (Intel HAXM and Genymotion, respectively), and both of them are vastly better than the default.

At my day job, I do a lot of Windows development on Parallels Desktop - for Windows, I find it to be the best VM software for Mac. Super fast, and the integration features are great.

In the past, I've had problems installing >1 VM software on my machine at the same time, so I've been on the lookout for a way to get Parallels working with Android. The "New VM" wizard offers to download and install Android, but the version it installs is old and busted - you definitely want to go with something newer.

Fortunately, the Android-x86 Project has done a ton of awesome work in order to enable running Android on laptops and virtual machines - they've recently released a KitKat image that works great; hit up that link to get started.

Setting up Android-x86

Setting up an installation of Android-x86 is pretty straightforward, especially if you've installed Linux before. However, one thing that is confusing is the Disk Partitioning process, which is pretty raw in the Android-x86 installer.

Once you select "Create / Modify Partitions", you're dropped into cfdisk. What you want to do, is go to "New" => "Primary", Hit Enter to choose the entire drive, then hit "Bootable". The result should look something like this:

Pick Write, then Quit. When asked to pick which filesystem to format, pick ext3. Unlike installing Linux Proper™, we won't have a Swap partition (Android devices don't have swap either!)

When asked to install GRUB, say Yes. You'll need to Reset the VM because it hangs after startup. A few seconds later, you should have a Super Fast Android VM, with Google Apps (like Play Store) as well as it being rooted which makes digging into your app's data much easier.

Setting up adb Debugging

This is the only part that isn't ideal - once you enable debugging via the standard "Tap on Build seven times to become Developer", you have to run a few commands every time you want to enable debugging.

First, hit Alt-F1 in the VM to drop to the Linux Terminal, then type netcfg:

Remember the IP address, then run:

adb tcpip  
adb connect 10.211.55.7:5555   ## Replace with your IP

> connected to 10.211.55.7:5555

You're now good to go - logcat, debugging, everything is good to go!

What's Missing

A few of the testing-related features of higher-end emulators like Genymotion aren't present in Android-x86, if you need features like Geolocation fakes, or simulating sensors, you might have to stick with Genymotion (though to be honest, I never got the appeal of features like this - can't you just mock it?).

For me though, Parallels + Android is <3.

August 14, 2014 8:10 GMT

Contest: 4 days left! Favorite Xamarin Studio Feature

With recent updates to Xamarin Studio and the introduction of very affordable $25 per month Xamarin Indie subscriptions, more developers than ever are finding out just how fast, easy, and fun mobile development with Xamarin Studio can be. Submissions are needed by August 18,  so don’t let this pass by with just 4 days left. Click on the Xamarin blog post below for more info on how to enter and some great prizes.

http://blog.xamarin.com/contest-favorite-feature-of-xamarin-studio/

XamarinStudioDocumentWindow[1]

August 14, 2014 7:31 GMT

What do Tom Hanks and Xamarin have in common?

Attention App Developers! See my 1st Xamarin  blog post!

http://blog.xamarin.com/tom-hanks-vintage-typewriter-inspired-hanx-writer-app/

I interviewed developer Jonathan Peppers of Hitcents about his Tom Hanks inspired app called Hanx Writer.   How did Tom Hanks inspire this app? Read the blog to find out! I think you will enjoy this post as it provides great info on how this app was built using the Xamarin Platform. He includes a wealth of knowledge including which API’s he used when he built this app. Enjoy and  by all means please share!

Please tweet w #hanxwriter   and download the Hanx Writer iPad app which was just released today!

3

Screen shot from the new Hanx app just released today!

JonPeppers

Jonathan Peppers, Senior Application developer.

August 14, 2014 5:54 GMT

Where in the World is Russ Fustino?

My calendar has been filling up in my new Developer Evangelism role at Xamarin. Here is my current itinerary, I hope to see you at one or more of these events! If you have an event you would like to have me speak at, please let me know. @RussFustino

8/18/2014
South Florida Xamarin User Group

The Best of Xamarin University
http://www.meetup.com/South-Florida-Xamarin-User-Group/events/199391772/

8/19/2014
TechNite in Miami

Networking Event
http://technightattheballpark.com/

8/20/2014
Tampa Xamarin UG

The Best of Xamarin University
http://www.meetup.com/Tampa-Bay-Xamarin-User-Group/events/199363032/

9/4/2014
Tallahassee .NET UG

Xamarin.Forms
http://www.meetup.com/tally-dot-net/

9/13/2014
Jacksonville, Code Impact

Xamarin.Forms
http://www.codeimpact.org

9/18/2014
Portland, Maine, Casco Bay .NET Users Group
Xamarin.Forms
http://www.cbnug.org/

9/20/2014
Vermont Code Camp
Xamarin.Forms
http://vtcodecamp.org/

9/25/2014
Space Coast UG

Topic TBD
http://www.meetup.com/Space-Coast-Net-User-Group/

10/6 thru 10/10
Evolve – Atlanta

Topic: TBD
Http://evolve.xamarin.com

August 14, 2014 5:43 GMT

YouTube Android Player for Xamarin.Android

Xamarin-YouTube-Android-Player Have you tried embedding a YouTube video into your android app? May be you tried using the HTML to embed the YouTube player in a WebView. From a developer perspective they aren’t programmable – meaning if you wish to interact with the player like play, pause, forward, go full screen, change video quality etc from your app, there isn’t a straight way to do it. From a user perspective the experience isn’t nice and you definitely want to work a better way out. Fortunately, Google provides a slick native YouTube Player on Android platform and a player API written in Java. The player API is a set of client libraries that interacts with a service that is distributed as a part of the YouTube Android app itself. That said, you need to ensure that the YouTube App is installed in the user’s device beforehand. The advantage is – your app size does not bloat up and you can upgrade the client libraries to incorporate new changes to the YouTube app anytime. And, upgrading is not necessary if you do not care about new features or bug fixes.

Bringing this beauty to Xamarin in C#

Lot of developers out there haven’t unleashed the full potential of the Xamarin platform yet. One of the big wins for Xamarin over any other cross-platform solutions is the power to reuse the existing Java and Obj-C (in case of iOS) libraries in C#. Apps built-in Xamarin are fully native and anything that you can do with Java in Android or Objective-C/Swift in iOS can be done in C# using Xamarin. Java ecosystem is large and it is  likely that a functionality that you want in Xamarin.Android may have already been written in Java just like the YouTube Android player in this case. Technically, you will use Bindings to bring any reusable Java library to Xamarin.Android. Alternatively, you can use JNI framework or port the entire Java code to C# using an automated tools like Sharpen. In this case, I downloaded the YouTubePlayer API jar file  and bound this using the Java Bindings Library project which is part of my solution. This project generates C# dll of your jar file and they are referenced into my Android project just like any other C# dll.  I have plans of writing a dedicated post on bindings and you can expect that soon. For now, I suggest, you read the official documentation.

Using the YouTubeAndroid player in C#

The bindings project dll that is referenced into your main Android app has the full Java API in C# along with the beautiful features of C# that you can utilize – like anonymous methods, lambdas, Linq etc. The solution also includes a samples project that helps you understand each of the API features in detail. So, you can copy and paste the entire code “as is” to make it work with your app.

[Update:] See how @xakpc adds async-await feature to his YouTube Thumbnail sample and unleashes the full potential of C#.

Source Code

If all that you care is the binding library or you are aware of how to get started with it – Head straight to my github for download. Please note: You can execute theses samples only on a physical device that has YouTube App installed. If you have an emulator that has the Google Play Services installed then it may work there too – I haven’t tested this so can’t guarantee!

Before you start

Get a developer key from Google and register your application. Add your key to the DeveloperKey.cs file

public static class DeveloperKey
{
 public static string Key = "";
}

Simple PlayerView

This sample shows how to use a YouTubePlayerView to play a video.

Resource file (PlayerView.axml)

First add the player to your resource file -


Activity(PlayerViewActivity.cs)

In the onCreate() method, instantiate your YouTubePlayerView and initialize it with your DeveloperKey.

YouTubePlayerView youTubeView = FindViewById(Resource.Id.youtube_view);
youTubeView.Initialize(DeveloperKey.Key, this);

To start playing your video cue the video to the player’s playlist.

public override void OnInitializationSuccess (IYouTubePlayerProvider provider, IYouTubePlayer player, bool wasRestored)
{
if (!wasRestored) {
player.CueVideo("wKJ9KzGQq0w"); }
}

CueVideo method takes the YouTube video id that you want to play and loads them to your playlist. When user clicks play, well, they get played :-) Noticed the OnInitializationSuccess method that is overriden? I use a helper activity called YouTubeFailureRecoveryActivity as the base class for all the samples. This class handles all the failure and recovery mechanism in the Android player.

That’s it!

Don’t forget to take a look at the PlayerControlsActivity.cs file if you want to know how to interact with the player – like play, pause, seek to position, change player style etc.

ScreenShot1

Hope this helps you!

Thanks!


August 14, 2014 5:02 GMT

Android L Developer Preview & Android Wear Support

Today we have published support for Google’s Android L Developer Preview in the Alpha channel. Additionally, we are introducing preliminary support for new SDKs that Google has released, including Android Wear, Android TV, and brand new Support Libraries.Android Robot

Installing our Android L Preview

  • With this release, a Java JDK 1.7 is now required to properly compile applications. You can download one for your system from Oracle website.
  • Update your Android SDK Tools to 23.0.2 from the Android SDK Manager
  • Install Android SDK Platform & Build-tools to 20

Android SDKTools

  • Download the Android L and Android 4.4W SDKs

Android L Preview SDK Download

Android Wear

Android WearWhen Google announced their new wearable platform, Android Wear, last March, they only made a new library for enhancing existing notifications available.

At Google I/O, an official developer SDK to create full-featured applications capable of running on an Android Wear device was unveiled. With this release, Xamarin developers will now enjoy the same ability.

We are also making available the Android Wear UI Library preview on NuGet to include in your wearable apps. Our Android Support Library v4 was also updated to include many of the new Android Wear interaction APIs, such as NotificationCompat and RemoteInput.

Android Support Libraries

Not only did the Android L Preview come in with a new series of core APIs, it also brought a large update to the Android Support Libraries set.

Along with Android Support Library v4 updates, additional Support Libraries are now in preview release, including great new features such as RecyclerView, CardView, Palette, Android TV Leanback, and update to Support Library v13. All of these libraries are now available straight from NuGet.

IDE Improvements

We have also added some new features to help you design for those new platforms to our Android designer for both Xamarin Studio and Visual Studio. You’ll find Wear device support, Material theme selection, and Action Bar previewing, among others, starting today.

Android Wear Designer support

See the Xamarin Studio release notes for more information and known caveats.

Getting Started

You should have the new APIs available now. Check our release notes for more details and a detailed list of the new APIs.

August 14, 2014 3:56 GMT

Tom Hanks’ Vintage-Typewriter Inspired Hanx Writer App

The Hanx Writer app, built with Xamarin, was released today after several months of work. I had the great pleasure to get the scoop on what it took to build this nostalgia-inducing app from a very cool developer at Xamarin Premier Consulting Partner, Hitcents.
HanxWriterKeyboardCropped

Jonathan Peppers is a Xamarin MVP, Senior C# Developer and App Specialist at Hitcents, and will be speaking about in-app purchases, piracy protection, localization, culturalization, and more in his, “If You Can Ship Your app in China, You Can Ship it Anywhere,” talk at Xamarin Evolve this October. Here are some questions from my Q&A session with Jonathan:

Can you please describe the app and how you got the idea?

Jonathan Peppers

The app is called “Hanx Writer.” That’s Hanx, with an “X”, but sounds like Hanks as in Tom Hanks. An agency that represents a lot of celebrities contacted Hitcents on behalf of Tom Hanks, who has an interest in collecting vintage typewriters, but also regularly uses an iPad. He wanted an app that made him feel like he was using a typewriter; he wanted that nostalgic feeling, but to still have the app function as a word processor to send emails, write letters, that sort of thing. So, we built an app that feels, looks, and sounds like a real typewriter for iOS.

How long did it take you to develop it?

It’s been about 5 months. But a lot of that time was refining and I was not working full time on this. My younger brother, Nick Peppers, also worked on the app. He did the iOS layouts and some of the UI stuff. There were 2 of us that committed code, and we also have a designer, Adam Diestelkamp, to do the cool graphics and a 3D artist, Matt Lester, do some of the 3D Models.

Tom Hanks basically said, “I want an app like this,” and you wrote it?

Yes, basically. He really just had the concept for the app, but our team took the idea and had to figure out how to translate the typewriter onto a flat screen. What things do we make like a real typewriter? What things do we make like a word processor? People are used to doing a copy and paste, so we didn’t want to get in the way of that. People know how to use word processing, but we still want to provide that cool vintage feel.

HanxWriterManageDocuments
Do you see going to other platforms besides iOS?

That was one of the reasons we chose Xamarin. We now have the option to share code with other platforms, so we’ll look at iPhone next and see if it makes sense there, and Android after that.

What API’s are you using?

We used iOS TextKit for entering text and saving. You can also go beyond the end of the page, and you can copy and paste and it splices it by page automatically and word wraps. There is a lot of text processing work going on in this app.

There are many items in the app that move around, the page flips in and out, and the keys dip when pressed. The keys need to look just like a real typewriter key when pressed down, for example. I use a lot of CoreAnimation for these effects.

I also used NSKeyedArchiver to save and read rich text.

Did you use Shared Project or Portable Class Library (PCL)? Why?
HanxWriterWirelessKeyboard
Parts of the app are in a PCL. We are using MVVM so all of our View Model classes are in a PCL. The app does have a lot of native iOS API calls, so these are not in the PCL. I prefer PCL over Shared Projects. I just get a better feeling passing around the same DLL that I know always works. I feel #IF can easily be abused with a developer using it too freely.

Anything else you want to tell us about your app and the experience?

It was definitely a cool app to work on. In the beginning, we tried to get a solid concept. All we knew is we were trying to make a typewriter. We really re-iterated and prototyped and added some different concepts along the way. It was fun to work on and I think it was a great choice to use Xamarin because we were able to complete development quicker.

To learn more about Hanx Writer, join @TomHanks for a live Twitter Q&A online this morning:

And to learn more about building apps with Xamarin, come see Jonathan Peppers present at Xamarin Evolve 2014.

August 13, 2014 6:00 GMT

Pack Xamarin in your Cardboard

Virtual Reality is a hot topic these days and is viewed by many as the platform of tomorrow in some fields, like game development.

cardboard-xamarin

At this year’s Google I/O conference, among the flurry of product announcements, Google presented an interesting project called Cardboard. The experiment sprouts from a desire to make virtual reality, as popularized by devices like the Oculus Rift, more accessible to everybody. The result is a simple, affordable, and open virtual reality headset based on off-the-shelves parts that uses an Android phone for the heavy lifting of sensors, computation, and display.

Thanks to our newly released Google Cardboard component, Xamarin.Android developers can now also create virtual reality applications that work on the Cardboard platform.

Be sure to check out the included CardboardMonkey app for an example of a simple game that takes advantage of the immersive nature of the platform:

xamarin-cardboardmonkey

You can visit the official Cardboard website for instructions on how to build your own Cardboard shell. Alternatively, pre-assembled versions are available from several online retailers.

You can also head to the Google Developers website for more details on the Cardboard API.

August 13, 2014 5:27 GMT

Enhancing Xamarin.Forms ListView with Grouping Headers

Sometimes a plain ListView just isn’t good enough. You can easily spice it up with images or custom cells, but what about organizing the data. With C# and LINQ it is easy to sort your list, but how about giving it some visuals? How about some headers? With Xamarin.Forms it is extremely simple to add in headers and to create a custom view as well.



I am working out of my Xamarin.Forms-Monkeys project that I have blogged about before, which consists of a nice list of Monkeys with Images. You can browse this code on my GitHub.

Bindable Group Structure

There are a few examples of using headers with Xamarin.Forms, but I wanted to create an ultimate “Group” that would allow me to sort, organize any data, and that is when I came up with Grouping:



Grouping seems simple, but is very extensible, especially if using data binding. Notice that a Grouping is really just an ObservableCollection of type T. However, each Grouping also has a Key. Now this key is of type K, which means it could be anything including a complex data structure. This means you could in theory bind your header to a data structure of K and then bind multiple controls to multiple properties, which is very cool. For this example though we will just make K a string for sorting.

Sorting Our Monkeys

Before we get to our Monkeys we will create a new new public ObservableCollection<Grouping<string,Monkey> > MonkeysGrouped{get;set;} in our ViewModel. The reason for this is that we actually have multiple lists, which is a list of a list of grouped monkeys. Then we will add a new property to our monkey that we can use for sorting, which will be a name sort property:


And now we can sort our list of Monkeys in our view model, which we will set as the ItemsSource on our list view:

Enabling Headers

Enabling headers is very simple. There are a few properties to set on the ListView itself to get things going. First is to enable grouping, and then to set the property that the headers will bind to:

list.ItemsSource = viewModel.MonkeysGrouped;
list.IsGroupingEnabled = true;
list.GroupDisplayBinding = new Binding(“Key”); //this is our key property on grouping.



Jump List

Of course, we could stop there, but what fun would that be, as we can add a jump list with just a single line of code:

list.GroupShortNameBinding = new Binding(“Key”);

This results in a nice jump list:


Custom Headers

Let’s take it one step further and implement our own custom header cell with a nice background color. Right now our Key, K, is only a string, but we could pass in a full data structure if we wanted to make the custom view more complex and bind to multiple pieces of information.

My HeaderCell is very simple and just contains a Label, which binds to Key and I am placing it inside of a StackLayout with a bit of custom padding and a background color. It should be noted that I am setting a fixed Height of 25 here as the Xamarin.Forms ListView needs to know what to render.



The last thing to do is to update the the ListView with this new template:

if(Device.OS != TargetPlatform.WinPhone)
list.GroupHeaderTemplate = new DataTemplate(typeof(HeaderCell));
list.HasUnevenRows = true; //you might want to enable if using custom cells.

We don’t set it on Windows Phone because the default styling is standard on Windows Phone with accent colors. However, you can customize it here as well. Here is our outcome on all three platforms:

XAML?

As Charles Petzold would say… Show me the XAML! Of course it is just as easy, as all we need to do is bring over our updated ViewModel and Grouping and create the rest all in XAML:

Conclusion

It is extremely easy to not only customize your cells in your ListView, but also add rich functionality like list sorting with group headers with just a few lines of shared C# code with Xamarin.Forms!
August 11, 2014 5:08 GMT

Top 3 Xamarin Studio Features

At last month’s meetup of #SydMobNet in North Sydney I spoke about some of the updates and new features available in Xamarin 3, and Filip Ekberg (@fekberg) gave a great presentation on Xamarin.Forms.

You can see videos of the presentations here:

Introduction to Xamarin and New Features in Xamarin 3

Xamarin.Forms

Following on from this, and having played with these new features more I thought I’d list my top three.

I’m a Visual Studio fan when it comes to mobile development and I won’t pretend it’s an easy thing to tempt me away from this. I develop on a MacBook Pro running Windows 8.1 under VMWare Fusion. Prior to Xamarin 3 I would hop across to the Mac and Xamarin Studio to launch XCode for my iOS UI design, call in briefly at Xamarin Studio to let it generate the C# code from my XCode changes and then I’d be straight back into Visual Studio. Recently however, Xamarin Studio has taken several big steps in the right direction. Whilst the setup on the Mac works very well there’s no getting away from the fact that VMWare hits the battery over the head with a big stick. Repeatedly. Mine submits in under an hour from full charge. With these improvements to Xamarin Studio it’s suddenly a lot more practical to leave the VM powered down and get more life out of my battery.

The iOS UI designer has to get an honorary mention. I’ve been looking forward to this since it was first announced at Evolve last year. The only reason I’ve not included it in my top three is Xamarin Forms – I'm currently using this (including its platform specific capabilities) for all my UI.

NuGet

I used to make a lot of use of MvvmCross, which in turn relied on NuGet – or at least the way I usually used it did. Although I’m not making so much use of this now I still let NuGet do the legwork for me when it comes to using things like SQLite or Azure Mobile Services – or both (see my previous posts). I can now knock up a quick project making use of things like this without firing up my VM and launching Visual Studio. It also supports custom package repository paths, so I can set up my own local repository and work offline when I’m on the train – thanks to Geoffrey Huntley (@GeoffreyHuntley) for info on setting this up.

There's a great post with more details about this here.

Shared Projects

Described here

I first came across this in Windows Phone world with the introduction of universal projects for Win 8 and Windows Phone 8 in Visual Studio Update 2, which was explained well by Nick Randolph and Craig Dunn back at the April meetup of #SydMobNet. Prior to this I was a fan of the PCL approach to code sharing, finding linked files just too much hassle to maintain. I’ve heard shared projects described as “linked files on steroids”, which does sum it up quite well. At its simplest it allows a project to be shared, with all files within that project automatically shared as well, so no more adding a file and forgetting to share it in one of your platform specific projects. You can still make use of the platform specific capabilities of Xamarin Forms like this:

        <OnPlatform x:TypeArguments="Font">

          <OnPlatform.iOS>Small</OnPlatform.iOS>

        </OnPlatform>

However, you also get to make use of precompiler directives. Whilst I’m not an all-out fan of these per se, there are times when they can make life simpler. It’s also great to see Xamarin heading in the same direction as Microsoft on this front.

Side by Side Editing

When I’m editing pre Xamarin Forms projects which are using MvvmCross it’s a big help to be able to see the xaml/axml of two views side by side when both writing and debugging across multiple platforms.

There are more features available (see the Xamarin blog) but these make my top three for now. I’ve not listed Xamarin Forms as it’s more of a product enhancement than just a feature of Xamarin Studio, but it would be at the top of the list if I’d included it!

Also worth a mention is the new monthly pricing plan for the Indie license, detailed here (note that the monthly figures quoted for the business and enterprise licenses are for comparison only as these licenses are still payable annually). At $25 a month it becomes a lot more viable for hobbyists to get started, which will hopefully go a long way towards broadening the appeal of Xamarin and creating more opportunities for all of us.

August 11, 2014 4:00 GMT

Custom UITableViewCells with Xamarin and XIBs

Sometimes when we are creating an iOS app with Xamarin, we choose to forego using the Storyboard designer, and simply create the user interface in C#. This works fine, but when using a UITableView, there are times when we want to design the UITableViewCell with the designer. Luckily, this is easy enough to do using a single .xib file in Xamarin Studio.

I have created a sample project in my Github repo to demonstrate using a .xib file to design our cell.

Create the project

For this sample, we will start off with the Empty Project template.

File -> New Solution -> iOS -> iPhone -> Empty Project

Create the table view

Next, add a new class for the UITableViewController, cleverly named MyTableViewController.cs. In the AppDelegate.cs, set the RootViewController to our new class. In MyTableViewController, we'll load our data and wire the TableView.Source to MyTableViewSource.

public override void ViewDidLoad ()  
{
    base.ViewDidLoad ();

    var conferences = ConferenceRepository.GetConferences ();

    TableView.Source = new MyTableViewSource (conferences);
}

Create the cell

At this point, we have not used a designer for any of our UI. In fact, we don't even have a .storyboard or .xib in our project. In order to design our table view cell, we're going to add one now. We'll add a new file using the iPhone Table View Cell template, and name it MyCustomCell.xib.

Add -> New File -> iOS -> iPhone Table View Cell

Xamarin Studio does not support designing .xib files, but double clicking on the file will open it in Xcode and allow us to design the cell.

As we drag our controls on to the design surface, we have to make sure that we wire up the Outlet in the header file. In Xcode, we do this by ctrl-click-dragging the control into the header file. Without the Outlets, we wouldn't be able to access the controls in our C# code.

Save the .xib and quit Xcode. Xamarin Studio will detect the change, and update the MyCustomCell.designer.cs file with the new Outlets.

using MonoTouch.Foundation;  
using System.CodeDom.Compiler;

namespace XibTableCellDesign  
{
    [Register ("MyCustomCell")]
    partial class MyCustomCell
    {
        [Outlet]
        MonoTouch.UIKit.UILabel ConferenceDescription { get; set; }

        [Outlet]
        MonoTouch.UIKit.UILabel ConferenceName { get; set; }

        [Outlet]
        MonoTouch.UIKit.UILabel ConferenceStart { get; set; }

        void ReleaseDesignerOutlets ()
        {
            if (ConferenceDescription != null) {
                ConferenceDescription.Dispose ();
                ConferenceDescription = null;
            }

            if (ConferenceName != null) {
                ConferenceName.Dispose ();
                ConferenceName = null;
            }

            if (ConferenceStart != null) {
                ConferenceStart.Dispose ();
                ConferenceStart = null;
            }
        }
    }
}

Add the model

Notice that these Outlets are private. We will not be able to access the controls from our UITableViewSource GetCell method, which is where we normally set our control properties, such as label.Text = value. We can get around this by adding a public property in the custom cell to set with our model data.

public partial class MyCustomCell : UITableViewCell  
{
    public Conference Model { get; set; }
}

Then, in the LayoutSubviews method of our custom cell, we can set the control properties to the model object's properties.

public override void LayoutSubviews ()  
{
    base.LayoutSubviews ();

    this.ConferenceName.Text = Model.Name;
    this.ConferenceStart.Text = Model.StartDate.ToShortDateString ();
    this.ConferenceDescription.Text = Model.Description;
}

Use the cell

The last step is to create and use the cell in our table view source's GetCell method.

public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)  
{
    var conference = _conferences [indexPath.Row];
    var cell = (MyCustomCell)tableView.DequeueReusableCell (MyCustomCell.Key);
    if (cell == null) {
        cell = MyCustomCell.Create ();
    }
    cell.Model = conference;

    return cell;
}

Checkout the sample app on my Github repo for an example of designing a table view cell with Xamarin Studio and .xib files.

August 10, 2014 11:44 GMT

NuGet Support in Xamarin Studio 5.2

New Features

  • Automatic package update check
  • Package framework retargeting
  • Support for custom packages directory in NuGet.Config
  • Add all checked packages even if they are not visible

More details on all the new features and changes in Xamarin Studio 5.2 can be found in the release notes. Now let us take a more detailed look at the new NuGet features.

Automatic package update check

On opening a solution Xamarin Studio will check in the background for updated packages used by your projects. When the update check begins the status bar will show a Checking for package updates message.

Checking for package updates status bar message

If Xamarin Studio finds there are new updated packages available then the status bar will show a Package Updates are available message.

Package updates are available status bar message

The Solution window will show information about the updates in the Packages folder.

Package updates shown in Solution window

The Packages folder will show the number of updated packages available for a project. For each package inside the Packages folder you can see the version number for the update.

Note that Xamarin Studio will only show updates that are for non-pre-release packages.

The automatic package update feature can be disabled in Preferences by unchecking Check for package updates when opening a solution.

Preferences dialog - Check for package updates when opening a solution

Framework retargeting

A NuGet package will often contain assemblies for several target frameworks. Json.NET, for example, contains assemblies for:

  • .NET 2.0
  • .NET 3.5
  • .NET 4.0
  • .NET 4.5
  • .NET Core 4.5 (Windows Store)
  • Portable Class Library (PCL)
    • .NET 4, Silverlight 5, Windows Phone 8, Windows 8, Windows Phone Application 8.1
  • Portable Class Library (PCL)
    • .NET 4.5, Windows Phone 8, Windows 8, Windows Phone Application 8.1

When you install this NuGet package into your project the assembly that is referenced is determined by your project’s target framework. NuGet will reference the assembly which it considers to be the best match for your project’s target framework. So if you install Json.NET into a project that targets .NET 4.5 the Json.NET assembly referenced will be taken from the .NET 4.5 folder inside the NuGet package.

If you change your project’s target framework after you have installed the NuGet package your project may be referencing a different assembly compared with what would have been referenced if you had installed it after changing the project’s target framework. In some cases the project’s target framework may not be compatible with the NuGet package. For example, your project targeted .NET 4.5 and you then changed it to .NET 2.0. In this case you would be referencing a .NET 4.5 assembly that would not work with .NET 2.0. Another example is if you change the PCL profile of your project which could affect which PCL assemblies are used from the NuGet package.

In Xamarin Studio 5.2 if you change your project’s target framework then the NuGet packages referenced by your project are checked to see if they are still compatible. The result of this check is displayed in the Package Console.

Packages need retargeting messages in Package Console

In the screenshot above the project’s target framework was changed from .NET 4.5 to .NET 2.0 whilst the project had the Json.NET and Moq NuGet packages installed. Json.NET is compatible with .NET 2.0 and can be retargeted. Moq does not support .NET 2.0 and is not compatible.

To retarget an individual NuGet package you can select the package in the Solution window, right click and select Retarget.

Solution window - Retarget menu item

To retarget all packages in the project you can select Packages in the Solution window, right click and select Retarget.

Solution window - Retarget project packages menu item

Selecting Retarget will remove the NuGet package and then add it again so the correct assembly is referenced by your project. The status bar will be updated as the package is retargeted and full details can be seen in the Package Console.

The Retarget menu item is only available if NuGet packages need to be retargeted.

Note that if you retarget a NuGet package that is incompatible with your project’s target framework then the retargeting will fail and the NuGet package will be removed from the project.

Support for custom packages directory in NuGet.Config

When a NuGet package is installed into a project the NuGet packages are by default downloaded into a packages directory inside the solution directory. The location and name of this packages directory can be configured by specifying the repositoryPath in the NuGet.config file.

<configuration>
  <config>
    <add key="repositoryPath" value="../../MyPackages" />
  </config>
</configuration>

If you create a NuGet.config file and put it the .nuget directory inside the solution, or in the project’s directory, then Xamarin Studio will read the repositoryPath and use it when downloading NuGet packages. The path is relative to the NuGet.config file but you can specify a full path if you need to.

Note that if you make a change to the repositoryPath whilst the solution is open you will need to close and re-open the solution for the changes to be detected.

Add all checked packages even if they are not visible

The Add Packages dialog will now add all packages that were checked when you click the Add Packages button even if they are not currently being displayed in the dialog. This allows you to run multiple searches in the dialog, check multiple packages and then add them to the project in one step without having to open the Add Packages dialog multiple times. Previously only the checked packages that were displayed in the list of packages would be added to your project.

Bug Fixes

Incorrect path separator used for MSBuild Import

A NuGet package can contain custom MSBuild .targets and .props files. Previously when a NuGet package was installed on the Mac a forward slash path separator was used when adding the paths for custom MSBuild .targets file. This would cause Xamarin Studio on Windows to fail to compile the project. Now backslashes are used for all paths added to the project file.

Xamarin Studio will also now add a Condition to the project file that checks the imported MSBuild .targets file exists. Without this condition the project cannot be opened in Visual Studio if the NuGet packages are missing.

As an example, if Xamarin.Forms 1.1.1.6206 is installed into a project the following Import element will be added.

<Import 
    Project="packages\Xamarin.Forms.1.1.1.6206\build\portable-win+net45+wp80+MonoAndroid10+MonoTouch10\Xamarin.Forms.targets"
    Condition="Exists('packages\Xamarin.Forms.1.1.1.6206\build\portable-win+net45+wp80+MonoAndroid10+MonoTouch10\Xamarin.Forms.targets')" />

Repositories.config not restored

When NuGet packages were restored for the solution the repositories.config file was not being restored. The repositories.config file contains references to all the projects in the solution that have NuGet packages. This information is used by NuGet to determine whether a NuGet package can be removed from the packages directory when a NuGet package is removed from a project. Without this information a NuGet package that is still referenced by other projects could be removed from the packages directory and cause the compilation to fail.

Package Dependencies not resolved from enabled package sources

Xamarin Studio will now use all enabled package sources when resolving dependencies for a NuGet package even if a single package source is selected in the Add Packages dialog. This allows the use of a NuGet package source that has packages that have dependencies that are not available from that particular package source but are available from another package source.

Packages are up to date status bar message

If you have the automatic check for updates disabled and update one or more NuGet packages the status bar will now display a message indicating that the packages are up to date if there are no updates available. Previously Xamarin Studio would show a message that the packages were updated when they were not.

Updating an unrestored package

If you have automatic package restore disabled and you attempt to update a NuGet package the package will now be restored before the update is attempted. Previously this would fail when an update was available since NuGet looks at the old package to work out how to remove it from the project before updating to the new NuGet package.

August 07, 2014 11:05 GMT

My Favorite Xamarin Studio Features

There have been a lot of exciting announcements recently from Xamarin for developers. First, is that Xamarin Indie now has a monthly subscription option for just $25 a month! Then there was the release of Xamarin Studio 5.2, which brought awesome new features such as side-by-side editing and awesome new NuGet updates. I have been a Visual Studio user for probably over 10 years and I have been using Xamarin Studio for nearly 3 years now. I have to say I find myself more and more developing on my Mac inside of Xamarin Studio. It is finely tuned for mobile development and has some amazing features packed into it, so I thought I would point out my top 3!



Source Analysis


I have been spoiled for years with ReSharper on Visual Studio, however Xamarin Studio actually ships with Source Code Analysis right out of the box. With the launch of Xamarin 3 this feature has been enabled by default, but I have been using it for some time and it makes daily development so much better. Simply look on the side of your code file for an overview of all the enhancements and optimizations you can make to your code.

TestFlight Integration

Distributing beta builds of my apps to my testers is always tricky. On Google Play you can have a beta/alpha channel and upload your APK and on Windows there is a beta option, but you have to leave the IDE. With TestFlight integration into Xamarin Studio you can easily upload your iOS applications with 1 click!

Workspaces

I am often working on multiple apps at the same time and Workspaces make it extremely easy to work on everything all at once. With this feature you don’t need multiple instances of Xamarin Studio open to work on multiple libraries or apps. Simply create a workspace and add as many solutions or projects as you would like.


So Much More

These are just 3 features I chose to highlight, but there is so much more include all of the unit test features, app archiving, universal search, version control, and about a thousand other awesome features. I would love to see what features of Xamarin Studio you love the most.
August 04, 2014 6:09 GMT

Video – Build Your First iOS App with Visual Studio and Xamarin

Here’s a video I made for Microsoft’s Flashcast series showing how to develop an iOS application using Visual Studio:



My colleague James did one for Android as well: http://flashcast.azurewebsites.net/stream/episode/5

Later this month we’ll have more Flashcasts, including one that shows how to use Xamarin’s iOS Designer for Visual Studio, and another on Xamarin.Forms. Keep an eye out for these, as well as other great topics at http://flashcast.azurewebsites.net


August 04, 2014 5:47 GMT

Custom ListView ViewCells in Xamarin.Forms

I love it when frameworks have built-in cells for lists. It allows me to easily shove some data into a list and get my prototype up and running extremely quickly. However, sometimes I don’t to ship the final app with these cells and I want to do some customization. Xamarin.Forms has 4 built-in cells to get you up and running and like everything else in Xamarin.Forms it is extremely easy to customize and create your own controls in XAML or C#.

On Twitter this morning I was asked how I would take my Xamarin.Forms Monkey’s and put the images on the right hand side:



The task was laid out, so I went to work on creating a new custom cell in XAML. The same code just needs to be translated over to C# if you are creating your app in the code behind.

The first thing is that I needed to remove my old TextCell that was in the DataTemplate and add a new base ViewCell. With the ViewCell in place it acts almost like any other “Page”, in that it has Content where you can lay down your controls. For this I am going to use a nice Grid control with 2 rows and 2 columns.



We will notice a few things of importance, which is that I set the rows height to 55, set the padding to 5 on the Grid, and made sure the image as 40x40. Here is the result:



This is just a quick example of how to add a custom ViewCell to your ListViews. The full source code for the Monkeys example is on my GitHub: https://github.com/jamesmontemagno/Xamarin.Forms-Monkeys
August 04, 2014 12:19 GMT

Xamarin Hack Day Talks, Thanks and Retrospective

In June this year I put together a Xamarin hack day(with some amazing help by SSW)  in Sydney. The idea of the Hack Day was to get Sydney’s most experienced Xamarin professionals and people who want to learn Xamarin together for a day of learning and loving Xamarin. The day started with some presentations on various Xamarin technology’s and then the attendees sat down with their laptops to code with the help of the Xamarin experts.

The vibe of the day was great as everyone was very helpful towards each other and attendees were able to help each other.

People are doing amazing things in Xamarin, we all know this but the problem is that we’re all so busy making great products that we don’t get the time to share notes and that’s why I wanted to start the Xamarin hack day. Thanks to SSW the Xamarin hack day has become even more than I expected, it’s now global. Xamarin hack day events will be hosed worldwide including Brisbane, Melbourne, Hong Kong and more. Visit the Xamarin Hack Day website to find out more details on locations.

I would like to thank the experts and presenters Filip, Alec, Geoffrey, David and Rod. I’d also like to thank Adam Cogan and the SSW team for hosting the event and the huge amount of effort they put into the website. A big thank you to all the attendees who made the day a success.

We’re always taking feedback and improving the days for the attendees, so future hack days are only going to get better. I’ve embedded the videos below for your viewing pleasure.

Please sign up for the next Hack Day at http://xamarinhackday.com/

 

Introduction to Xamarin

Xamarin.Forms Deep Dive

Introduction to iBeacons with Xamarin

The post Xamarin Hack Day Talks, Thanks and Retrospective appeared first on Michael Ridland.

August 03, 2014 2:56 GMT

I Am Not Web Scale: Wunderlist Edition

A few months ago, I posted about the Open Source projects I was currently working on, and that I was maintaining too many things. Fortunately, most of those things were accomplished! ModernHttpClient, ReactiveUI, and Akavache all have had new major releases recently.

In that post, I screenshotted my Wunderlist list of what I'm working on. Fortunately, with the release of Wunderlist 3, I can now share that list on an ongoing basis as an Open Source Experiment:

Each of the items has notes that describe more about what's going on, or a link to the relevant discussion, though I don't think that this isn't visible unless you hit "Add to Wunderlist"

Getting Involved

You can get to this list via the new Public Lists feature, and if you see something that interests you, get ahold of me. The best way is via chatting to me on Slack in the ReactiveUI Chat Room. It's not a public chat room, but if you Email me using the Email address you want to use, I can add you. Emailing me privately always works too!

August 03, 2014 1:24 GMT

Akavache 4.0 is Released

After 8 months of work and 424 commits from 7 authors, Akavache 4.0 is now released! Thanks to the contributors for this release:

  • Johan Laanstra
  • Oren Novotny
  • Brendan Forster
  • Phil Haack
  • Herman Banken
  • Oskar Hermansson

In particular, a huge thanks goes to Johan, who migrated the SQLite-based backend to Eric Sink's SQLitePcl.Raw - a ton of work!

A Universal Akavache

Akavache 4.0 now supports a native SQLite on all platforms, as well as including support for new platforms:

  • Xamarin.Android
  • Xamarin.iOS
  • Xamarin.Mac
  • Xamarin Forms (iOS + Android + WP8)
  • .NET 4.5
  • Universal Windows Apps (WPA81)
  • Windows Phone 8.0 Apps (Silverlight-based)
  • Windows Store Apps (WinRT)

Akavache is also much smaller, because it no longer depends on ReactiveUI, instead depending on a much smaller library called Splat. Akavache also has now moved to the latest version of the Reactive Extensions, v2.2.5.

SQLite Performance is Significantly Improved

The SQLite driver has been completely rewritten in Akavache 4.0 for performance, especially when used by multiple threads at the same time. Synthetic benchmarks on the new SQLite backend show that it is 8x faster at reading random data, and a whopping 82x faster than the previous version at writing random data.

This improvement was done without any on-disk metadata changes - existing SQLite databases are immediately compatible. This new driver also completely resolves the "locking" issues that people would see when executing many operations in parallel.

Garbage Collection and Cleanup

Akavache now allows applications to explicitly schedule cleanup of the underlying database, via a new Vacuum API. This will drop all expired keys from the database, as well as its name implies, execute a VACUUM operation on SQLite to compact the database.

Migration Notes

  • Akavache now no longer ships the deprecated filesystem backend. You can now find this backend in the Akavache.Deprecated NuGet package. You should plan to move away from this backend and into the SQLite-based backend in your next release.

  • GetAllKeys is now an asynchronous operation.

  • TestBlobCache is now called InMemoryBlobCache

August 01, 2014 10:08 GMT

Azure Mobile Services with Offline Sync to SQLite using Xamarin Forms

This post:

http://blog.alectucker.com/post/2014/05/02/cross-platform-azure-mobile-services-with-xamarin-and-mvvmcross.aspx

detailed how to set up and use Azure Mobile Services from a portable class library (PCL) in a Xamarin project with the help of MvvmCross. Since I wrote that two major updates have hit the scene. The first is Xamarin Forms, which allows us to write cross platform xaml and bring the UI into the shared code while still rendering natively on each platform and, critically, still allowing or platform specific customisations. The second is the addition of offline sync capability to Azure Mobile Services using SQLite.

This post covers both. Note that version 1.3 of the Azure Mobile Services components is still pre-release. If you're looking to use Xamarin Forms but want to stick with the current stable release then you can still work through this post - I'll highlight where the differences are. You just won't get the offline sync ability. (The code is almost identical.)

As was the case with that previous post, I'm not attempting to walk through how to create the Azure Mobile Service. If you need a hand with this there's a link in the other post.

The last difference from the previous post is that this is now all being done without the help of MvvmCross.

So, first let's create a Xamarin Forms app. We'll use a PCL again.

Those already familiar with Xamarin Forms PCL solutions will recognise the structure generated:

First let's add the references we need. Right click on the solution node and select 'Manage NuGet Packages for Solution' - this way we can do this once and have the correct references added to all constituent projects.

To get the offline sync capability you'll need to change the dropdown at the top from 'Stable' to 'Include Prerelease' and ensure that both the select packages are added. If you're sticking with the 'Stable' release then leave the dropdown list on 'Stable' and you'll only have the option of installing the 'Windows Azure Mobile Services' package.

At present (and indeed for quite some time now) the NuGet packages for the Xamarin.iOS and Xamarin.Android projects require a small tidy up before they'll work. If you build the projects now you'll get some duplicate reference errors, complaining about:

  • System.IO
  • System.Runtime
  • System.Threading.Tasks

You'll need to manually remove these from these two projects in order to get them to compile.

Next we have to add some initialisation code to prevent the references we've just added from being stripped out at compile time. This is the only bit of platform specific code which I'm putting in this example.

In the iOS project, an AppDelegate.cs you'll need to add two lines to FinishedLaunching, after the Forms.Init() line:


        public override bool FinishedLaunching(UIApplication app, NSDictionary options)

        {

            Forms.Init();

            Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();

            SQLitePCL.CurrentPlatform.Init();

 

            window = new UIWindow(UIScreen.MainScreen.Bounds);

...

These two lines perform the necessary initialisation for Azure Mobile Sevices and SQLite respectively.

In the Android project we'll add the line to initialise azure Mobile Services into MainActivity.cs:


        protected override void OnCreate(Bundle bundle)

        {

            base.OnCreate(bundle);

 

            Xamarin.Forms.Forms.Init(this, bundle);

            Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();

 

            SetPage(App.GetMainPage());

        }


To get all of this to work on Windows Phone 8 you'll need to install SQLite for Windows Phone. In Visual Studio select Extensions and Updates from the Tools menu, find "SQLite for Windows Phone" and install it.


Next we'll set up folders for using MVVM, so add the following folders to the Portable proj

ect:
  • Services
  • Models
  • ViewModels
  • Views

That's right - the Views folder now sits in the PCL, thanks to Xamarin Forms. Inside the Models folder create a Contact class as follows:


namespace AzureOfflineSyncXF.Models

{

    public class Contact

    {

        public string Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Email { get; set; }

        public string PhoneNumber { get; set; }

        public string ImageUrl { get; set; }

        public string Version { get; set; }

    }

}

This should look familiar if you went through my previous post. The one change to highlight is the addition of the Version property. This is required by the sync handler.

The next thing to do is add a DataService class in the Services folder. In there we'll need to define the mobile service like this:

private readonly MobileServiceClient MobileService = new MobileServiceClient("https://[yourservice].azure-mobile.net/", "[yourkey]");


Next we'll add a generic GetAll method which will just return the entire contents of the Contacts table.

public async Task<ObservableCollection<T>> GetAll<T>()

{

    ObservableCollection<T> theCollection = new ObservableCollection<T>();

    try

    {

        //var theTable = MobileService.GetTable<T>();

        var theTable = MobileService.GetSyncTable<T>();

        theCollection = await theTable.ToCollectionAsync<T>();

    }

    catch (Exception ex)

    {

        theCollection = null;

        ReportError(ex);

    }

 

    return theCollection;

}


We'll also put in a generic Save method.

public async Task Save<T>(T pEntity)

{

    try

    {

        //var theTable = MobileService.GetTable<T>();

        var theTable = MobileService.GetSyncTable<T>();

        await theTable.InsertAsync(pEntity);

    }

    catch (Exception ex)

    {

        ReportError(ex);

    }

}

Note the commented out line calling MobileService.GetTable<T>() in both these methods. This is what you will need to use if you're using a version of the Azure Mobile Services components which doesn't have offline sync capability (i.e. pre 1.3). The line beneath uses GetSyncTable<T>() instead.

Next we'll add a generic Pull method (you won't need this if you're using < version 1.3).

public async Task Pull<T>()

{

    try

    {

        var theTable = MobileService.GetSyncTable<T>();

        await theTable.PullAsync();

    }

    catch(Exception ex)

    {

        ReportError(ex);

    }

}

As an example of using this we'll put code into the GetAll method to pull the data down from the mobile service into the local DB before reading it from the local DB and returning it. In practice you'd probably want to get a bit cleverer than this. Add this line to the GetAll method:

await Pull<AzureOfflineSyncXF.Models.Contact>();

Now we need to do some initialisation in the constructor of the DataService class.


public DataService()

{

    Initialise();

}

private async void Initialise()

{

    if (!MobileService.SyncContext.IsInitialized)

    {

        var store = new MobileServiceSQLiteStore("local.db");

        store.DefineTable<AMS.Offline.XF.Models.Contact>();

        await MobileService.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

    }

}


You'll need the following using statements to resolve this code:

using Microsoft.WindowsAzure.MobileServices;

using Microsoft.WindowsAzure.MobileServices.SQLiteStore;

using Microsoft.WindowsAzure.MobileServices.Sync;


The last thing to do in here is add a method which will initially populate the Azure table for us.


        public async Task LoadContacts()

        {

            Collection<Contact> theList = new Collection<Contact>();

 

            theList.Add(new Contact() { FirstName = "George", LastName = "Washington", Email = "George@fake.com", PhoneNumber = "02 555 1111" });

            theList.Add(new Contact() { FirstName = "John", LastName = "Adams", Email = "John@fake.com", PhoneNumber = "02 555 1112" });

            theList.Add(new Contact() { FirstName = "Thomas", LastName = "Jefferson", Email = "Thomas@fake.com", PhoneNumber = "02 555 1113" });

            theList.Add(new Contact() { FirstName = "James", LastName = "Madison", Email = "James@fake.com", PhoneNumber = "02 555 1114" });

            theList.Add(new Contact() { FirstName = "James", LastName = "Monroe", Email = "James@fake.com", PhoneNumber = "02 555 1115" });

            theList.Add(new Contact() { FirstName = "John Quincy", LastName = "Adams", Email = "John@fake.com", PhoneNumber = "02 555 1116" });

            theList.Add(new Contact() { FirstName = "Andrew", LastName = "Jackson", Email = "Andrew@fake.com", PhoneNumber = "02 555 1117" });

            theList.Add(new Contact() { FirstName = "Martin", LastName = "van Buren", Email = "Martin@fake.com", PhoneNumber = "02 555 1118" });

            theList.Add(new Contact() { FirstName = "William Henry", LastName = "Harrison", Email = "William@fake.com", PhoneNumber = "02 555 1119" });

            theList.Add(new Contact() { FirstName = "John", LastName = "Tyler", Email = "John@fake.com", PhoneNumber = "02 555 1120" });

            theList.Add(new Contact() { FirstName = "James K.", LastName = "Polk", Email = "James@fake.com", PhoneNumber = "02 555 1121" });

            theList.Add(new Contact() { FirstName = "Zachary", LastName = "Taylor", Email = "Zachary@fake.com", PhoneNumber = "02 555 1122" });

            theList.Add(new Contact() { FirstName = "Millard", LastName = "Filmore", Email = "Millard@fake.com", PhoneNumber = "02 555 1123" });

            theList.Add(new Contact() { FirstName = "Franklin", LastName = "Pierce", Email = "Franklin@fake.com", PhoneNumber = "02 555 1124" });

            theList.Add(new Contact() { FirstName = "James", LastName = "Buchanan", Email = "James@fake.com", PhoneNumber = "02 555 1125" });

            theList.Add(new Contact() { FirstName = "Abraham", LastName = "Lincoln", Email = "Abraham@fake.com", PhoneNumber = "02 555 1126" });

            theList.Add(new Contact() { FirstName = "Andrew", LastName = "Johnson", Email = "Andrew@fake.com", PhoneNumber = "02 555 1127" });

            theList.Add(new Contact() { FirstName = "Ulysees S.", LastName = "Grant", Email = "Ulysees@fake.com", PhoneNumber = "02 555 1128" });

            theList.Add(new Contact() { FirstName = "Rutherford B.", LastName = "Hayes", Email = "Rutherford@fake.com", PhoneNumber = "02 555 1129" });

            theList.Add(new Contact() { FirstName = "James A.", LastName = "Garield", Email = "James@fake.com", PhoneNumber = "02 555 1130" });

            theList.Add(new Contact() { FirstName = "Chester A.", LastName = "Arthur", Email = "Chester@fake.com", PhoneNumber = "02 555 1131" });

            theList.Add(new Contact() { FirstName = "Grover", LastName = "Cleveland", Email = "Grover@fake.com", PhoneNumber = "02 555 1132" });

            theList.Add(new Contact() { FirstName = "Benjamin", LastName = "Harrison", Email = "Benjamin@fake.com", PhoneNumber = "02 555 1133" });

            theList.Add(new Contact() { FirstName = "Grover", LastName = "Cleveland", Email = "Grover@fake.com", PhoneNumber = "02 555 1134" });

            theList.Add(new Contact() { FirstName = "William", LastName = "McKinley", Email = "William@fake.com", PhoneNumber = "02 555 1135" });

            theList.Add(new Contact() { FirstName = "Theodore", LastName = "Roosevelt", Email = "Theodore@fake.com", PhoneNumber = "02 555 1136" });

            theList.Add(new Contact() { FirstName = "William Howard", LastName = "Taft", Email = "William@fake.com", PhoneNumber = "02 555 1137" });

            theList.Add(new Contact() { FirstName = "Woodrow", LastName = "Wilson", Email = "Woodrow@fake.com", PhoneNumber = "02 555 1138" });

            theList.Add(new Contact() { FirstName = "Warren G.", LastName = "Harding", Email = "Warren@fake.com", PhoneNumber = "02 555 1139" });

            theList.Add(new Contact() { FirstName = "Calvin", LastName = "Coolidge", Email = "Calvin@fake.com", PhoneNumber = "02 555 1140" });

            theList.Add(new Contact() { FirstName = "Herbert", LastName = "Hoover", Email = "Herbert@fake.com", PhoneNumber = "02 555 1141" });

            theList.Add(new Contact() { FirstName = "Franklin D.", LastName = "Roosevelt", Email = "Franklin@fake.com", PhoneNumber = "02 555 1142" });

            theList.Add(new Contact() { FirstName = "Calvin", LastName = "Coolidge", Email = "Calvin@fake.com", PhoneNumber = "02 555 1143" });

            theList.Add(new Contact() { FirstName = "Harry S.", LastName = "Truman", Email = "Harry@fake.com", PhoneNumber = "02 555 1144" });

            theList.Add(new Contact() { FirstName = "Dwight D.", LastName = "Eisenhower", Email = "Dwight@fake.com", PhoneNumber = "02 555 1145" });

            theList.Add(new Contact() { FirstName = "John F.", LastName = "Kennedy", Email = "John@fake.com", PhoneNumber = "02 555 1146" });

            theList.Add(new Contact() { FirstName = "Lyndon B.", LastName = "Johnson", Email = "Lyndon@fake.com", PhoneNumber = "02 555 1147" });

            theList.Add(new Contact() { FirstName = "Richard", LastName = "Nixon", Email = "Richard@fake.com", PhoneNumber = "02 555 1148" });

            theList.Add(new Contact() { FirstName = "Gerald", LastName = "Ford", Email = "Gerald@fake.com", PhoneNumber = "02 555 1149" });

            theList.Add(new Contact() { FirstName = "Jimmy", LastName = "Carter", Email = "Jimmy@fake.com", PhoneNumber = "02 555 1150" });

            theList.Add(new Contact() { FirstName = "Ronald", LastName = "Reagan", Email = "Ronald@fake.com", PhoneNumber = "02 555 1151" });

            theList.Add(new Contact() { FirstName = "George H.W.", LastName = "Bush", Email = "George@fake.com", PhoneNumber = "02 555 1152" });

            theList.Add(new Contact() { FirstName = "Bill", LastName = "Clinton", Email = "Bill@fake.com", PhoneNumber = "02 555 1153" });

            theList.Add(new Contact() { FirstName = "George W.", LastName = "Bush", Email = "George@fake.com", PhoneNumber = "02 555 1154" });

            theList.Add(new Contact() { FirstName = "Barack", LastName = "Obama", Email = "Barack@fake.com", PhoneNumber = "02 555 1155" });

 

            foreach(Contact one in theList)

            {

                await this.Save<Contact>(one);

            }

        }


Now that the DataService has been written let's extract an interface by right clicking on 'DataService' in the class declaration and selecting 'Refactor', then 'Extract Interface'.

Make the resulting interface public, and save everything.

namespace AzureOfflineSyncXF.Services

{

    public interface IDataService

    {

        System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<T>> GetAll<T>();

        System.Threading.Tasks.Task Pull<T>();

        System.Threading.Tasks.Task Save<T>(T pEntity);

    }

}


The last thing we'll do in the Services folder is to add a simple ServiceLocator class like this:

namespace AzureOfflineSyncXF.Services

{

    public static class ServiceLocator

    {

        public static IDataService DataService { get; set; }

    }

}


Next, add a similar ViewModelLocator into the ViewModels folder.


namespace AzureOfflineSyncXF.ViewModels

{

    public static class ViewModelLocator

    {

        public static  ContactListViewModel ContactListViewModel { get; set; }

    }

}



Now we can move on to the viewmodel. First, add a BaseViewModel class to the ViewModels folder.

namespace AzureOfflineSyncXF.ViewModels

{

    public class BaseViewModel : INotifyPropertyChanged

    {

        #region Property change notification stuff

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")

        {

            RaisePropertyChangedExplicit(propertyName);

        }

        protected void RaisePropertyChanged<TProperty>(Expression<Func<TProperty>> projection)

        {

            var memberExpression = (MemberExpression)projection.Body;

            RaisePropertyChangedExplicit(memberExpression.Member.Name);

        }

        void RaisePropertyChangedExplicit(string propertyName)

        {

            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)

            {

                var e = new PropertyChangedEventArgs(propertyName);

                handler(this, e);

            }

        }

        #endregion

    }

}


You'll see I like to use regions (yes - I'm the one!), but sparingly. Now we can add the ContactListViewModel to the ViewModels folder.


namespace AzureOfflineSyncXF.ViewModels

{

    public class ContactListViewModel : BaseViewModel

    {

        private readonly IDataService _dataService;

 

        public ContactListViewModel()

        {

            _dataService = ServiceLocator.DataService;

            _constructor();

        }

        public ContactListViewModel(IDataService pDataService)

        {

            // Shown to demo injection support

            _dataService = pDataService;

            _constructor();

        }

        private async void _constructor()

        {

            this.Contacts = await LoadContacts();

        }

 

        private ObservableCollection<Contact> _contacts;

        public ObservableCollection<Contact> Contacts

        {

            get { return _contacts; }

            set { if (_contacts != value) { _contacts = value; RaisePropertyChanged(() => Contacts); } }

        }

 

        private async Task<ObservableCollection<Contact>> LoadContacts()

        {

            ObservableCollection<Contact> theCollection = new ObservableCollection<Contact>();

 

            try

            {

                theCollection = await _dataService.GetAll<Contact>();

            }

            catch(Exception ex)

            {

                theCollection = null;

 

                // Do something with the exception

            }

 

            return theCollection;

        }

    }

}


I've put in a parameterless constructor, which is what we'll be using. This will make use of the static ServiceLocator class to find the data service. However, I've also added a constructor which takes the service as a parameter, in case I get a bit cleverer one day and set up some dependency injection. Other than this it's a very straightforward viewmodel - there's one ObservableCollection property which we'll bind to a list on screen, and there's a method to populate it by making an asynchronous call to the data service.

Now for the Xamarin Forms magic. Add a Forms Xaml Page to the Views folder and call it ContactsView.

This will give you ContactsView.xaml and ContactsView.xaml.cs, just like you'd expect if you've done Windows Phone dev (or WPF or Silverlight).

Open up the xaml and change it to look like this:


<?xml version="1.0" encoding="utf-8" ?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

                                     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

                                     x:Class="AzureOfflineSyncXF.Views.ContactListView">

 

  <StackLayout>

    <Label Text="contacts" />


    <ListView ItemsSource="{Binding Contacts}" x:Name="listCategories">

      <ListView.ItemTemplate>

        <DataTemplate>

          <TextCell Text="{Binding FirstName}" Detail="{Binding LastName}" />

        </DataTemplate>

      </ListView.ItemTemplate>

    </ListView>

  </StackLayout>

 

</ContentPage>


This binds the list to the Contacts property in the view model, and defines a template to use for each cell in the list with bindings on two of the contact's properties.

Now we need to put some code behind this. Remember we're not using MvvmCross this time around (or any other Mvvm framework) so we need to wire up the viewmodel manually.


namespace AzureOfflineSyncXF.Views

{

    public partial class ContactListView

    {

        public ContactListView()

        {

            InitializeComponent();

            this.BindingContext = ViewModelLocator.ContactListViewModel;

        }

    }

}


That's the view defined. Now to App.cs to indicate that this view is to be displayed on startup.


namespace AzureOfflineSyncXF

{

    public class App

    {

        public static Page GetMainPage()

        {

            // Initial, once off data load

            LoadData();

 

            NavigationPage theNavigationPage = null;

            ContentPage theContentPage = null;

 

            try

            {

                theContentPage = new ContactListView();

                theNavigationPage = new NavigationPage(theContentPage);

            }

            catch(Exception ex)

            {

                // Do something with the exception

            }

 

            return theNavigationPage;

        }

 

        private static async void LoadData()

        {

            await ServiceLocator.DataService.LoadContacts();

        }

    }

}


There's one last gotcha in the Windows Phone project. This may well be fixed by the time you read this, but I'm currently getting the following exception when building:

The 'ProductID' attribute is invalid

This looks like a bug in the Xamarin Forms project template for Windows Phone. It's caused by the WMAppManifest.xml file. You'll need to open this and fix it up. Double click that file in Visual Studio and you'll get this:

This is caused by the same problem. Click the link to open it up in the XML editor, and find this line:

  <App xmlns="" ProductID="aaaaaaaa-1111-aaaa-1111-aaaa1111aaaa" Title="AzureOfflineSyncXF.WinPhone" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal"  Author="AzureOfflineSyncXF.WinPhone author" Description="Sample description" Publisher="AzureOfflineSyncXF.WinPhone" PublisherID="bbbbbbbb-2222-bbbb-2222-bbbb2222bbbb">


The ProductID and the PublisherID should both contain strings between {curly parentheses}, so change it to look like this:

  <App xmlns="" ProductID="{aaaaaaaa-1111-aaaa-1111-aaaa1111aaaa}" Title="AzureOfflineSyncXF.WinPhone" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal"  Author="AzureOfflineSyncXF.WinPhone author" Description="Sample description" Publisher="AzureOfflineSyncXF.WinPhone" PublisherID="{bbbbbbbb-2222-bbbb-2222-bbbb2222bbbb}">

Save and close the file. You should now be able to double click it to open it, and you should be able to build and run successfully.


Further reading:

For details on how to handle sync conflicts take a look here:

http://azure.microsoft.com/en-us/documentation/articles/mobile-services-windows-store-dotnet-handling-conflicts-offline-data/

This page is also worth a look, and it has some useful links too:

http://msopentech.com/blog/2014/06/09/azure-mobile-services-offline-adds-xamarin-support-using-sqlitepcl/

Feedback:

Please feel free to comment / criticise / question. I'll commit to deleting anything which isn't complimentary :)


August 01, 2014 12:40 GMT

Gesture Recognizers with Xamarin.Forms

iOS and Android apps both provide a way to wire up a UI control to listen for specific touch events. These events are called gestures. Typically, we would use this to listen for a tap (click) gesture, or maybe a swipe or fling gesture.

In a native Xamarin.iOS or Xamarin.Android app, wiring up these events is fairly straight forward. As of this writing though (July, 2014), Xamarin.Forms only has cross platform support for the tap gesture. Just because all of the gesture recognizers aren't wrapped for Xamarin.Forms does not mean that we can not use them though. By using custom renderers, we are able to get access to the native controls and wire up our gesture recognizer just as we would in a native Xamarin app.

I have created a sample app in my Github repo to demonstrate how we can use the simplicity of Xamarin.Forms and still have the power of built in gesture recognizers.

Sample App

We'll start with a new Xamarin.Forms app. This can be a Shared Project or a Portable project (the sample app is a Shared Project). For this sample, we're going to wire up a Label control to listen for the touch events.

To be able to use a custom renderer, we'll need to subclass Label in our shared code.

using Xamarin.Forms;

namespace XamarinFormsGestureRecognizers  
{
    public class FancyLabel : Label {}
}

In our App.cs we'll set the Content of our Page to a new FancyLabel. Since the TapGestureRecognizer is already built in to Xamarin.Forms, we'll wire that one up here in our shared code.

using Xamarin.Forms;  
using System;

namespace XamarinFormsGestureRecognizers  
{
    public static class App
    {
        public static Page GetMainPage ()
        {   
            var fancyLabel = new FancyLabel {
                Text = "Hello, Forms!",
                VerticalOptions = LayoutOptions.CenterAndExpand,
                HorizontalOptions = LayoutOptions.CenterAndExpand,
            };

            var tapGestureRecognizer = new TapGestureRecognizer ();
            tapGestureRecognizer.Tapped += (sender, e) => Console.WriteLine ("Tapped");
            fancyLabel.GestureRecognizers.Add (tapGestureRecognizer);

            return new ContentPage { 
                Content = fancyLabel
            };
        }
    }
}

Now we need to implement our custom renderers for each platform.

iOS

We'll add a new file named FancyIosLabelRenderer.cs to the iOS project and add a class derived from Xamarin.Forms' LabelRenderer.

using Xamarin.Forms;  
using Xamarin.Forms.Platform.iOS;  
using MonoTouch.UIKit;  
using System;  
using XamarinFormsGestureRecognizers;  
using XamarinFormsGestureRecognizers.iOS;

namespace XamarinFormsGestureRecognizers.iOS  
{
    public class FancyIosLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged (e);
        }
    }
}

The renderer class itself is a view that wraps the native control. While we could wire up the recognizer to the control itself, it's better to simply wire it up to the renderer's view. Since the renderers can be reused, we also need to be sure to only create the gesture recognizers if the OldElement is null (when we're not reusing the control).

public class FancyIosLabelRenderer : LabelRenderer  
    {
        UILongPressGestureRecognizer longPressGestureRecognizer;
        UIPinchGestureRecognizer pinchGestureRecognizer;
        UIPanGestureRecognizer panGestureRecognizer;
        UISwipeGestureRecognizer swipeGestureRecognizer;
        UIRotationGestureRecognizer rotationGestureRecognizer;

        protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged (e);

            longPressGestureRecognizer = new UILongPressGestureRecognizer (() => Console.WriteLine ("Long Press"));
            pinchGestureRecognizer = new UIPinchGestureRecognizer (() => Console.WriteLine ("Pinch"));
            panGestureRecognizer = new UIPanGestureRecognizer (() => Console.WriteLine ("Pan"));
            swipeGestureRecognizer = new UISwipeGestureRecognizer (() => Console.WriteLine ("Swipe"));
            rotationGestureRecognizer = new UIRotationGestureRecognizer (() => Console.WriteLine ("Rotation"));

            if (e.NewElement == null) {
                if (longPressGestureRecognizer != null) {
                    this.RemoveGestureRecognizer (longPressGestureRecognizer);
                }
                if (pinchGestureRecognizer != null) {
                    this.RemoveGestureRecognizer (pinchGestureRecognizer);
                }
                if (panGestureRecognizer != null) {
                    this.RemoveGestureRecognizer (panGestureRecognizer);
                }
                if (swipeGestureRecognizer != null) {
                    this.RemoveGestureRecognizer (swipeGestureRecognizer);
                }
                if (rotationGestureRecognizer != null) {
                    this.RemoveGestureRecognizer (rotationGestureRecognizer);
                }
            }

            if (e.OldElement == null) {
                this.AddGestureRecognizer (longPressGestureRecognizer);
                this.AddGestureRecognizer (pinchGestureRecognizer);
                this.AddGestureRecognizer (panGestureRecognizer);
                this.AddGestureRecognizer (swipeGestureRecognizer);
                this.AddGestureRecognizer (rotationGestureRecognizer);
            }
        }
    }

Lastly, we need to be sure that we wire up the custom renderer to look for instances of the FancyLabel class.

[assembly: ExportRenderer (typeof(FancyLabel), typeof(FancyIosLabelRenderer))]

Android

Using the gesture recognizers in Android will be similar, but with a bit more work. Xamarin's documentation explains how to use a GestureDetector in an Android app, which is what we'll do here.

Once again, we'll add a new file called FancyAndroidLabelRenderer.cs to hold our custom renderer.

using Xamarin.Forms.Platform.Android;  
using Xamarin.Forms;  
using XamarinFormsGestureRecognizers;  
using XamarinFormsGestureRecognizers.Droid;  
using Android.Views;

namespace XamarinFormsGestureRecognizers.Droid  
{
    public class FancyAndroidLabelRenderer : LabelRenderer
    {
        public FancyAndroidLabelRenderer ()
        {
        }

        protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged (e);
        }
    }
}

We'll also add a class named FancyGestureListener.cs and we'll add gesture listener. Here we'll subclass the built in SimpleOnGestureListener to provide most of the functionality.

using Android.Views;  
using System;

namespace XamarinFormsGestureRecognizers.Droid  
{
    public class FancyGestureListener : GestureDetector.SimpleOnGestureListener
    {
        public override void OnLongPress (MotionEvent e)
        {
            Console.WriteLine ("OnLongPress");
            base.OnLongPress (e);
        }

        public override bool OnDoubleTap (MotionEvent e)
        {
            Console.WriteLine ("OnDoubleTap");
            return base.OnDoubleTap (e);
        }

        public override bool OnDoubleTapEvent (MotionEvent e)
        {
            Console.WriteLine ("OnDoubleTapEvent");
            return base.OnDoubleTapEvent (e);
        }

        public override bool OnSingleTapUp (MotionEvent e)
        {
            Console.WriteLine ("OnSingleTapUp");
            return base.OnSingleTapUp (e);
        }

        public override bool OnDown (MotionEvent e)
        {
            Console.WriteLine ("OnDown");
            return base.OnDown (e);
        }

        public override bool OnFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
        {
            Console.WriteLine ("OnFling");
            return base.OnFling (e1, e2, velocityX, velocityY);
        }

        public override bool OnScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
        {
            Console.WriteLine ("OnScroll");
            return base.OnScroll (e1, e2, distanceX, distanceY);
        }

        public override void OnShowPress (MotionEvent e)
        {
            Console.WriteLine ("OnShowPress");
            base.OnShowPress (e);
        }

        public override bool OnSingleTapConfirmed (MotionEvent e)
        {
            Console.WriteLine ("OnSingleTapConfirmed");
            return base.OnSingleTapConfirmed (e);
        }
    }
}

Then, we need to wire up this listener to our renderer, and include the ExportRenderer attribute.

using Xamarin.Forms.Platform.Android;  
using Xamarin.Forms;  
using XamarinFormsGestureRecognizers;  
using XamarinFormsGestureRecognizers.Droid;  
using Android.Views;

[assembly: ExportRenderer (typeof(FancyLabel), typeof(FancyAndroidLabelRenderer))]

namespace XamarinFormsGestureRecognizers.Droid  
{
    public class FancyAndroidLabelRenderer : LabelRenderer
    {
        private readonly FancyGestureListener _listener;
        private readonly GestureDetector _detector;

        public FancyAndroidLabelRenderer ()
        {
            _listener = new FancyGestureListener ();
            _detector = new GestureDetector (_listener);

        }

        protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged (e);

            if (e.NewElement == null) {
                if (this.GenericMotion != null) {
                    this.GenericMotion -= HandleGenericMotion;
                }
                if (this.Touch != null) {
                    this.Touch -= HandleTouch;
                }
            }

            if (e.OldElement == null) {
                this.GenericMotion += HandleGenericMotion;
                this.Touch += HandleTouch;
            }
        }

        void HandleTouch (object sender, TouchEventArgs e)
        {
            _detector.OnTouchEvent (e.Event);
        }

        void HandleGenericMotion (object sender, GenericMotionEventArgs e)
        {
            _detector.OnTouchEvent (e.Event);
        }
    }   
}

Checkout the sample app on my Github repo to get started with Xamarin.Forms and gestures.

July 31, 2014 9:01 GMT

Cross Platform Mobile With C# WhitePaper presented by Visual Studio Magazine

My white paper on Visual Studio Magazine is now available.  This whitepaper will discuss the details for developing cross platform applications with C#.

 "As a Microsoft-centric developer, you have great tools in the Microsoft .NET Framework and C# Language, but you're faced with a challenge when it comes to building apps for the exploding world of mobile devices: Learning new languages and platforms can be incredibly time-consuming.  Wouldn't it be better to use the skills you already posses?  In this paper, you'll learn how to use the interoperable technologies of Xamarin to do just that.

Url:http://visualstudiomagazine.com/whitepapers/2014/07/xamarin-cross-platform-mobile-with-c.aspx?tc=page0

July 30, 2014 6:31 GMT

Be More Social: oAuth, Facebook and Xamarin

It isn't breaking news that social networks are a big deal to your users. But what's the best way to add that functionality in the cross-platform development world? One of the best ways is through Xamarin, which provides a set of components that allows developers to concentrate on high-level programming and solving user problems. This article will look at some technologies available in Android -- as well as the iPhone -- to add social features to applications. It serves as a companion to my April article that covered oAuth, Twitter and the Linq to Twitter library.

Url: http://visualstudiomagazine.com/articles/2014/07/01/be-more-social.aspx

July 30, 2014 2:40 GMT

Sharing Data With Handoff in iOS 8 and Xamarin

Handoff is a feature in iOS 8 that really gets me excited, it is a feature that gives a user the feeling that something magical just happened. Without any effort on the users part state is passed from one device to another enabling them to carry on where they left off. If i did not know any better i would honestly believe this could only be attributed to pure magic. Well, we do know better so let’s get onto how we build this into our own Xamarin apps.

Project Setup

To begin we need to add a new entry into the info.plist, they key is NSUserActivityTypes with and array as the value. you can the add a reverse domain url for each activity type you wish to be shared between apps.

Info Plist

Sharing Data

In our view controller we are now able to setup our state data which can be shared to other devices when in range. To do this we use the NSUserActivity class which is available through the UserActivity property on all UIResponder elements which most things in your view hierarchy derive from. We create the UserActivity we instantiate it by passing in the activity type like so:

public override void ViewDidLoad ()
{
   base.ViewDidLoad ();
			
   this.UserActivity = new NSUserActivity ("com.handOff.sample.text");
   this.UserActivity.Title = "Sample Text HandOff";

}

To set the state we wish to share we only have to override the UpdateUserActivityState method which again resides on UIResponder. This method is called periodically by the OS but can be requested by setting the NeedsSave flag to true on the UserActivity object. Ideally we should only update the state in this method as prior to being called the OS will clean out the UserInfo dictionary;

[Export ("textFieldDidEndEditing:")]
public void EditingEnded (MonoTouch.UIKit.UITextField textField)
{
   this.UserActivity.NeedsSave = true;
}

public override void UpdateUserActivityState (NSUserActivity activity)
{
   base.UpdateUserActivityState (activity);
   this.UserActivity.AddUserInfoEntries(new NSDictionary (new NSString("SharedText"), new NSString(this.SharedTextField.Text)));
}

Continuing An Activiy

In our AppDelegate we have two touch points to consider, overriding WillContinueUserActivity gives us the chance to decide if we are able to continue the incoming activity. If this is something the app can handle we can show the user a loading spinner while the activity is populated.

Secondly we must override ContinueUserActiviy, this gives us access to the fully populated user activity object and a completion handler which accepts an array of NSObject. We use this completion handler to pass in all of the UI elements or view controllers wish to handle the activity which has been passed. These will then have RestoreUserActivityState called on them.

AppDelegate

public override bool WillContinueUserActivity (UIApplication application, string userActivityType)
{
   //Decide if we can handle the activity type
   //Show the user a loading spinner
   return true;
}

public override bool ContinueUserActivity (UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
{
   completionHandler (new [] { this.Window.RootViewController });
   return true;
}

ViewController

public override void RestoreUserActivityState (NSUserActivity activity)
{
   base.RestoreUserActivityState (activity);
   this.SharedTextField.Text = ((NSString)activity.UserInfo ["SharedText"]);
}

As usual you can pick up the sample code on GitHub.

Have fun!


July 29, 2014 9:41 GMT

Xamarin at Successful Tampa Code Camp! Recap

I had the great pleasure presenting Xamarin Forms at the recent Tampa Code Camp. This event was resurrected from a one year hiatus and a welcome site to the Tampa Developer Community. Many are looking forward to a bigger and better code camp as part of a very engaged developer community here in Tampa next year.

Personally, this was a huge moment in the next chapter of my career as well. I delivered my first Xamarin Session, concluding with three weeks of intense training and setup. It was a culture shock, of sorts, for me to present on a Mac and I joked about it that it was more of a challenge for me to learn a Mac than learn Xamarin! The Mac is a better presenting machine in that there are fewer moving parts to demonstrate iOS development. I still use my Windows machine to develop on. Anyway, it all turned out good as about 60 in my session learned about the Xamarin Platform and Xamarin Forms.  For most of the audience, it was their first exposure to Xamarin.

Here are is PowerPoint for the session: http://1drv.ms/1AbKxPp

C__Data_Users_DefApps_AppData_INTERNETEXPLORER_Temp_Saved Images_Bs6evL0CAAIJAwE

First photo of Russ as a Xamarin Developer Evangelist in Action! (Thanks Scott Dorman!)

V__C53D

It was a packed house! Greg Leonardo was working on my AV here.   It is funny, I once did that for him a few years back at one of his sessions. Full circle, huh?

V__29ED

First Demo, Xamarin Forms Hello World in iOS, Android, and Windows Phone. This got a big warm round of applause!

V__FFA1

Russ with Greg Leonardo, Head organizer of Tampa Code Camp.

Fox News has a great piece on the code camp: http://www.myfoxtampabay.com/story/26016891/code-camp-brings-developers-together

Download Xamarin today at www.xamarin.com

Follow my new Twitter @RussFustino

and follow @XamarinHQ

July 28, 2014 10:07 GMT

Three (hopefully) interesting things

"Interesting" is, of course, relative.

Like a lot of people, I've moved to a standing desk.

After 3 weeks, it's going well. I had the usual sore legs and feet for the first week (softer shoes helped, but I can go back to my normal Camper shoes now), and the week I spent at home, not standing, was filled with leg cramps and pain.

Working at home, however, is good for other reasons:

But in general, it's great. I've had zero neck, leg, back or head pain since I started doing this. No idea if I've upped my calorie burn, but that wasn't the point. One of the keys for me was getting the keyboard and mouse height correct. The standard desks here are just too low for me (I'm 175cm / 5foot8), so a ream of photocopy paper fixed that. There is a Magic Trackpad floating around the office, so I might give that a go, too.

Recommended if you can try it. Give it two weeks if you can.


I generally find Sam Harris' writing interesting. This wasn't an exception.

I must admit, I know very little about the Israel / Palestine situation, and there is so much disinformation on both sides. But he makes a good case:

What would the Jews do to the Palestinians if they could do anything they wanted? Well, we know the answer to that question, because they can do more or less anything they want. The Israeli army could kill everyone in Gaza tomorrow. So what does that mean?

....

What do we know of the Palestinians? What would the Palestinians do to the Jews in Israel if the power imbalance were reversed? Well, they have told us what they would do.

Makes a good read, unless you are already convinced on one side or the other, in which case I suspect nothing will change your mind (like the Xcode bit below). Chances of a resolution is, I think, sadly pretty much zero.


I'm still trying to like Xcode. But it's not helping.

I use, on a daily basis:

  • Xcode 5.1.1 (6.0 too, but not daily)
  • Eclipse
  • TextMate
  • AppCode
  • Xamarin Studio

That would be the reverse order of what I enjoy using, and what I'm productive in - independent of language used. Also from least to most stable. Clearly, Xcode is a mindset, one which I don't "get". Aside from Swift support, its not one I have to get, which I'm quite grateful for. I just need to work out how to switch from Eclipse to IntelliJ/Android Studio - without messing up the rest of the team.


There is always a 4th thing.

Jared Sinclair posted about the 12 months of Unread in the AppStore. Very interesting reading and pretty much confirms that indy iOS developers - with a few exceptions - are stuffed. It's now big companies who can make the dev cost back some other way, or hobbiests who don't need to make a living on it.

And thats sad. Some of the best apps out there came from indys.

Justin said he's looking at posting numbers for Glassboard, which will be interesting. I'd love to see some numbers from the likes of Vesper or Overcast, tho it's a bit early for that.

I still look at my apps - which net around $7000 USD a year, mostly from mobileAgent - as a way to fund devices and Xamarin licenses - and a way to provide a concrete example of what I can do. So far, thats worked. (not to mention it's fun!)

I wonder if some peoples view of "oh, app developers are rolling in money so they should just charge 99c or make it free" is rooted in the old days when you could make $100k/year off a 99c app. Times, however, have changed since then.

July 28, 2014 4:12 GMT

My first public presentation about Xamarin : SqlSaturday #341 Oporto

It’s with great excitement that i announce  i m going  to be making my first presentation on a public event.
Earlier this month i was invited to submit a session for the Programming track of the SQLSaturday #341 event taking place in Oporto on the 18th October. The session was chosen by the community to be featured on the event :)

I will be presenting Build mobile applications with Xamarin Forms” , it will be a light talk where i will introduce Xamarin and talk a little more about a new xamarin prodcut suite called Xamarin Forms followed up by a short demo.

The event is taking place at ISEP, and i m still to sure it will be streamed or recorded.


SQLSaturday is a training event for SQL Server professionals and those wanting to learn about SQL Server. This event will be held Oct 18 2014 at Rua Dr. António Bernardino de Almeida, 431 , Porto, 4200-072, Portugal. Admittance to this event is free, all costs are covered by donations and sponsorships. Please register soon as seating is limited, and let friends and colleagues know about the event.

Make sure to register for the event here. Hope to see you there.