Xamarin: Join Xamarin at Oracle OpenWorld 2015

We’re celebrating our strategic partnership with Oracle by joining them at Oracle OpenWorld, their marquee annual conference, to showcase how Xamarin and Oracle help organizations build better enterprise apps. With Oracle and Xamarin, developers can easily and securely connect native Xamarin apps to Oracle Mobile Cloud Service for robust backend access, making enterprise development fast, […]

The post Join Xamarin at Oracle OpenWorld 2015 appeared first on Xamarin Blog.

Michael Ridland: Creating a Native View from a Xamarin.Forms View

WARNING: this is a expert level technique and isn’t officially supported by Xamarin. Personally I feel like this is the holy grail of Xamarin.Forms development, having the ability to jump between both Xamarin.Forms Views and Native Views. I’ve used this technique multiple times in Xamarin.Forms apps. It’s primarily used when you’ve created a custom renderer […]

The post Creating a Native View from a Xamarin.Forms View appeared first on Michael Ridland.

Xamarin: Fall into New Xamarin Events in October!

Dive into Xamarin this month with new events, seminars, Dev Days, user groups, and conferences happening in all corners of the globe! Find out what’s new with Xamarin in like-minded communities near you: XLSOFT Japan Tokyo, Japan: October 3rd 6th Japan Xamarin User Group Conference Xamarin Dev Days – Portland Portland, OR: October 3rd Come […]

The post Fall into New Xamarin Events in October! appeared first on Xamarin Blog.

Craig Dunn: iOS 9-ify your Xamarin.Forms App

It’s not just regular Xamarin.iOS apps that can implement fancy iOS 9 features 🙂 Check out the quick hacks I did to this Restaurant Guide Xamarin.Forms sample to add iOS 9 features:

Mostly using the magic of Dependency Service I added:

No special work was required to get the app running with iPad Multitasking, other than to ensure there was a Storyboard (or XIB) Launchscreen.
Finally, I added the Application Transport Security “opt-out” tags to the Info.plist file, so that the links to all the different restaurants would work in the WebView control.
Download the code from github to try for yourself!
p.s. Ignore the fact that this sample uses Razor templates to generate the restaurant detail view. That is merely a coincidence – this existing Xamarin.Forms sample was the most appropriate to add iOS 9 features to. iOS 9 features can be added to any Xamarin.Forms app, whether it displays data with XAML, C#, or in a Razor HTML template 😉

Xamarin: Xamarin & Azure Apps Everywhere at AzureCon

We love the cloud and so do our developers. Xamarin developers have the ability to pick and choose a backend that fits their needs best and build out native cross-platform mobile apps on top of them, and Microsoft Azure offers a variety of services and integrations that make it easy to add a backend to […]

The post Xamarin & Azure Apps Everywhere at AzureCon appeared first on Xamarin Blog.

Greg Shackles: Getting Started with Estimote Nearables and Xamarin

I’ve been a big fan of Estimote (and beacons in general) for awhile now, but only just recently had a chance to finally play around with their nearables, dubbed Estimote Stickers. These stickers are similar to beacons, except that their primary purpose is to be attached to physical objects, and in addition to proximity also broadcast more contextual information about the object. This extra information contains a bunch of interesting details such as temperature, orientation, and motion in three dimensions.

Getting Started

With these stickers in my possession, the first step was seeing what was involved in getting set up with Estimote’s SDK for interacting with the stickers. Thankfully this is as trivial as it gets. Simply head over to the Xamarin Component Store, grab the components for iOS and Android, and you’re good to go!

iOS

With that installed, it’s just as easy to start detecting nearables:

var manager = new NearableManager();

manager.RangedNearables += (sender, e) =>  
{
    foreach (var nearable in e.Nearables ?? Enumerable.Empty<Nearable>())
        Console.WriteLine(nearable);
};
manager.StartRangingForType(NearableType.All);  

On iOS8+ you also need to specify a value for NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription in your Info.plist file in order to get access to the iOS location APIs, which Estimote sits on top of.

If you’re only looking for a specific nearable type you can alternatively specify that in the call to StartRangingForType(), instead of always scanning for all types. Other types available as of right now include Dog, Fridge, Door, Generic, and more. That’s all you need to initiate basic scanning for nearables, and you will get access to all the discovered nearables in the RangedNearables callback.

Android

The Android SDK is also easy to get up and running with, though I do find it a bit lacking compared to the iOS one (more on that later). Here is an activity that starts scanning for nearables when it loads up:

[Activity(Label = "Nearables!", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity, BeaconManager.IServiceReadyCallback  
{
    private BeaconManager _beaconManager;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        _beaconManager = new BeaconManager(this);
        _beaconManager.Nearable += (sender, e) =>
        {
            foreach (var nearable in e.Nearables ?? Enumerable.Empty<Nearable>())
                Console.WriteLine(nearable);
        };

        _beaconManager.Connect(this);
    }

    public void OnServiceReady()
    {
        _beaconManager.StartNearableDiscovery();
    }
}

Easy enough. Where on iOS we were able to limit scanning by nearable type, that doesn’t seem to be exposed in the Android SDK. In Fact, despite there being a NearableType enum in the SDK, that doesn’t even seem to be exposed as a property on a Nearable object.

Triggers

One of the other nice things about the iOS SDK that is not currently available in the Android SDK is the ability to specify rules and triggers for when you get a callback from a nearable. While it’s not the end of the world to have to compose these things by hand, this makes it trivial to define the scenarios you care about in your apps.

For example, let’s say you attached the Dog sticker to your dog and wanted to detect when the dog rolled over. All you need to do is define an orientation rule for that nearable type and create a trigger based on it:

var triggerManager = new TriggerManager();

var dogRollsOverRule = OrientationRule.OrientationEquals(NearableOrientation.HorizontalUpsideDown, NearableType.Dog);  
var dogRollsOverTrigger = new Trigger(new [] { dogRollsOverRule }, "dog rolls over");

triggerManager.ChangedState += (sender, e) =>  
{
    if (!e.Trigger.State)
        return;

    if (e.Trigger.Identifier == dogRollsOverTrigger.Identifier)
        new UIAlertView(null, "dog rolled over", null, "Ok", null).Show();
};

triggerManager.StartMonitoringForTrigger(dogRollsOverTrigger);  

In the ChangedState callback, e.Trigger.State indicates whether the trigger is currently active.

In addition to OrientationRule there are several other built-in rules you can use, such as DateRule, ProximityRule, TemperatureRule, and MotionRule. You can also define your own rule classes that create any scenarios you’d like.

Composing Rules

You’re also not limited to a single rule for a trigger, so you can compose multiple rules together to form a more interesting scenario. Let’s say that you attached a sticker to your refrigerator and want to detect when it opens late at night to cut back on late night snacking. With Estimote’s trigger API this is trivial:

var fridgeDoorMovesRule = MotionRule.MotionStateEquals(true, NearableType.Fridge);  
var afterMidnightRule = DateRule.HourBetween(0, 5);  
var lateNightSnackingTrigger = new Trigger(new Rule[] { fridgeDoorMovesRule, afterMidnightRule }, "fridge door moves after midnight");

triggerManager.ChangedState += (sender, e) =>  
{
    if (!e.Trigger.State)
        return;

    if (e.Trigger.Identifier == lateNightSnackingTrigger.Identifier)
        new UIAlertView(null, "late night snacking!", null, "Ok", null).Show();
};

triggerManager.StartMonitoringForTrigger(lateNightSnackingTrigger);  

Simply compose a DateRule with a MotionRule and you’re done!

Summary

Obviously this just scratches the surface of what you can do with nearables, but the exciting part to me is how easy it is to build smart, contextual experiences. Estimote is an awesome company as well, so I suspect they will close the SDK gaps between iOS in Android over time to make things easy across the board.

Johan Karlsson: FontAwesome using Xamarin Forms and Android

FontAwesome is, well, awesome… And be warned, this is kind of a hack.

On Android, it’s a bit of a hassle use FontAwesome. This blog post is about how to use Font Awesome in the simplest way possible. It’s as easy as using a Label once set up.

The hack is simple. We use a custom renderer that looks at the Label in question, determines if there is one character in the text field and if that character has the value of 0xf000 or higher. If so, we replace the font with FontAwesome.

Since the icons all begin at 0xf000 or higher, the custom renderer will make sure that the correct font is used.

The first label in the example below will simply print out the text. The second label will show a map marker icon using a single unicode character and the third references a local static object that maps all the icons to a friendly name. The static object is in the sample project.

            <!– Business as usual –>
            <Label Text=Just Normal Text />

            <!– A Map marker using a single character –>
            <Label Text=&#xf041; FontSize=40 />

            <!– Using a resource –>
            <Label Text={x:Static local:FontAwesome.FAPhone} FontSize=40 />

This will result in the following screen.

Here’s how you do it.

Download the font

Download the FontAwesome font and drop it in your Asset folder for the Droid project. Don’t forget to check that the build type is set to AndroidAsset.

Create a custom renderer

The magic goes here. In the Droid project, create a custom renderer that looks like this.
[assembly: ExportRenderer(typeof(Label), typeof(AwesomeRenderer))]

namespace Awesome.Droid
{
    public class AwesomeRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var label = (TextView)Control;

            var text = label.Text;
            if(text.Length > 1 || text[0] < 0xf000)
            {
                return;
            }

            var font = Typeface.CreateFromAsset(Xamarin.Forms.Forms.Context.ApplicationContext.Assets, fontawesome.ttf);
            label.Typeface = font;
        }
    }
}


Summary

Greg Shackles: Testing Xamarin Apps: Lowering Unit Testing Friction

In my my last post I showed how to set up unit tests that can easily be run against .NET/Mono, iOS, and Android. As a followup to that, I want to outline a few tips and tricks for lowering the friction to running these tests. The easier you can make it to add new tests and run them the more value you’ll get out of testing. In fact, these tips apply to testing on any platform, so they are not limited to just Xamarin apps.

Code Templates

I’m always surprised to find out how many people don’t take advantage of code templates in their IDEs, or even know they exist in the first place. Code templates allow you to define shortcuts for quickly scaffolding out predictable blocks of code so you don’t have to type it all out manually. By default in Xamarin Studio and Visual Studio a lot of these are defined for you out of the box for C# code, such as prop for creating a property, or ctor for creating a constructor.

You can also go ahead and define your own, so one of the first things I do in any fresh install is add a template for tests. I tend to stick to a naming convention in my tests of MethodUnderTest_Scenario_ExpectedResult, which is very useful when reading a set of test results to understand what is working and what is not.

You can find code templates in Xamarin Studio’s preferences under Text Editor > Code Templates:

Preferences

From there we can go ahead and add a new template for fact:

Fact template

The code for that template is:

[Fact]
public void $method$_$scenario$_$expected$()  
{
    $end$
}

Each of the variables in the template – method, scenario, expected – should be editable. With this defined, in a C# code file if you type fact and hit tab twice you will see the template entered where your cursor is, and you’ll be editing the first variable. You can continue hitting tab to cycle through the variables to rename them as needed. Hitting enter will take you to the body of the new method, as defined by the placement of $end$ in the template. Now you can add new tests to your suite in seconds!

Code templates are also available in Visual Studio, so you can set this up easily there as well if that’s your preferred environment.

Shortcuts

There’s not much to really write about this one, but it’s worth calling out nonetheless. If your IDE has any shortcuts for running tests, make sure to learn and use them. For example, Visual Studio has a shortcut of Ctrl+R, A for running all tests in its runner. If you use ReSharper’s runner there are a bunch of shortcuts depending on the type of run you want to do. Alt+R, U, N is one that’s easy to remember, and will create a new session and run all the tests in ReSharper’s runner.

Shortcuts will allow you to quickly trigger your tests without taking you out of the flow you’re already in, keeping you both informed and productive.

Automatically Running Tests

Taking that even further, another great option is to just have your tests run automatically each time you build your solution. There are many solutions out there that can help you set this up, such as AutoTest.NET, but it’s also easy to set up something basic by hand as well. To do this I’ll make use of fswatch, which you can easily install via Homebrew:

brew install fswatch  

With that in place let’s create a script named monitor-tests.sh and set it up to monitor some tests, using the same example as the last post:

#!/bin/bash

XUNIT_PATH="packages/xunit.runner.console.2.1.0-rc2-build3176/tools/xunit.console.exe"  
TESTS_PATH="bin/Debug/TestDemo.dll"

fswatch -0 $TESTS_PATH | xargs -0 -n 1 -I {} mono $XUNIT_PATH $TESTS_PATH  

Each time the DLL file is changed, which will happen as part of building the project, fswatch will trigger the xUnit console runner to re-run against the updated test assembly. You can just leave this running off to the side and always be informed about the latest state of your test results.

Summary

These are just a few examples of easy ways to lower the friction to writing and running tests. Like with most things, if writing and running tests in your solution is too complicated or time consuming, you’re ultimately going to stop using it. Make it easy on yourself to take advantage of these practices without sacrificing your time or productivity.

Craig Dunn: iOS 9-ify your Xamarin App

With the iPhone 6s models now available, it’s possible to build and test all the great new features of iOS 9 with Xamarin. To demonstrate, I’ve tried to squeeze as many iOS 9 features as possible into one sample: To9o app (that’s “Todo” but with a “9” 🙂 The c# code is on github and screenshots of each iOS 9 feature are shown below.

3D Touch

3D Touch can used a few different ways, but requires an iPhone 6s to test (the Simulator doesn’t support 3D Touch). I started by adding these two:

Multitasking for iPad

If the app can resize its UI appropriately, it should work fine for multi-tasking!

ContactsUI

The “Todo” app doesn’t traditionally need an interface to the Contacts list, but I added it just to give this new API a try 🙂

New Search APIs

The new search APIs let you expose content to search and Siri. I’ve added both:

Notice the Back to Search button in the navigation bar.

    UIStackView

    This new layout option makes it much easier to build screens that ‘scale’, and also makes it even easier to support RTL languages (see below).

    * Note: currently UIStackViews must be drawn using Xamarin’s Xcode integration, but the built-in Xamarin iOS Designer will support them soon!

    Collection View Changes

    The main Todo list is a UICollectionView rather than a table, so it can demonstrate how easy it now is to re-order items with two simple methods added in code.

    Right-to-Left Language Support

    The entire app can now automatically flip (including UINavigationController animations) when displaying RTL languages like Arabic and Hebrew (note: machine translation used for example, apologies for any inaccuracies).

    SFSafariViewController

    This new API makes it easy to implement an in-app web browsing experience with a line or two of code. I’ve used it just for an “About” window.

    All these improvements are explained in Xamarin’s iOS 9 docs, and the code is available to review. It is still a work-in-progress so check back for more updates.