November 21, 2014

Get Started with Xamarin.Forms via the Evolve Mini-Hack

By

As part of the Evolve Darwin Lounge, we had a bunch of small coding exercises for a variety of topics that attendees could complete to win a prize. One of the mini-hacks from Evolve 2014 involved creating a simple application with Xamarin.Forms. This is a nice example to try out Xamarin.Forms yourself.

Let’s take look at how to do this mini-hack. We’ll be creating the Magic 8 ball application shown below:

app screenshot

1. Create a new Xamarin.Forms solution called MagicBall (I’m using the PCL project here):

new solution

2. Add a ContentPage named BallPage to the shared project:

content page

3. Edit BallPage.xaml to contain a StackLayout with an Image, Label and Button respectively. Also add some padding to the top of the page:

<?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="MagicBall.BallPage"
  Padding="0, 30, 0, 0">
  <ContentPage.Content>
    <StackLayout>
      <Image Source="ball.png"></Image>
      <Label x:Name="label" Text="Magic 8 Ball" Font="Large"
        HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
      <Button x:Name="button" Text="Tell Me!" HorizontalOptions="Center"
        VerticalOptions="CenterAndExpand" Clicked="ButtonClicked" />
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

4. Add code to BallPage.xaml.cs to update the label randomly from an array of strings when the button is clicked:

public partial class BallPage : ContentPage
{
  string[] options = {" It is certain"
        , " It is decidedly so"
        , " Without a doubt"
        , " Yes definitely"
        , " You may rely on it"
        , " As I see it, yes"
        , " Most likely"
        , " Outlook good"
        , " Yes"
        , " Signs point to yes"
        , " Reply hazy try again"
        , " Ask again later"
        , " Better not tell you now"
        , " Cannot predict now"
        , " Concentrate and ask again"
        , " Don't count on it"
        , " My reply is no"
        , " My sources say no"
        , " Outlook not so good"
        , " Very doubtful "
  };
  public BallPage ()
  {
    InitializeComponent ();
  }
  void ButtonClicked (object sender, EventArgs args)
  {
    label.Text = options [new Random ().Next (options.Length - 1)];
  }
}

5. Update App.cs to return a BallPage:

public class App
{
  public static Page GetMainPage ()
  {
    return new BallPage ();
  }
}

6. Add the ball.png image to the Resources folder on iOS and Resources/drawable on Android.

7. Run the application and ask the 8 ball for advice.

The code for this mini-hack is available here: https://github.com/xamarin/mini-hacks/tree/master/Xamarin.Forms/solution/MagicBall

Update:
Craig Dunn has a solution in his repo that includes a Windows Phone project as well.

TwitterFacebookGoogle+LinkedInEmail
November 20, 2014

Real-Time Code Iteration with Sketches

By

Sketches are a powerful new feature that we announced as a preview release at Xamarin Evolve in October. With Sketches, developers can iterate on code within Xamarin Studio and immediately see the results, without having to go through a full build and deploy cycle.

Sketches

A sketch is a file that stands alone or can be contained in a project, making it easy to move experimental code from a sketch into a code base. In some ways, it’s the immediate window on steroids.

For example, say you want to inspect the result of some code such as :

var x = 1;
var y = 2;
var z = x + y;

Sketches use a REPL (read–eval–print loop) that evaluates the code and displays the results:

sketch results

Viewing Output

There are visualizers for the output built in, too. For instance, a color is displayed as shown below:

color visualizer

You can even pin the results to the output area:

color output

Additionally, the output can display graphs of data:

output graph

Visualizing Images

The visualizer can display other types of data, too, such as images:

image visualization

Graphics Code

Having image support is nice, because it allows you to write arbitrary graphics code in a sketch and render it to an image. For example, here’s a code snippet from a blog post I wrote a while back, showing the rendering of some Core Graphics drawing code (updated for the unified API) in an iOS sketch:

// Sketch your next great idea!
using UIKit;
using Foundation;
using CoreGraphics;
//
UIGraphics.BeginImageContext (new CGSize (320.0f, 300.0f));
using (var gctx = UIGraphics.GetCurrentContext ()){
  gctx.SetLineWidth(4);
  UIColor.Purple.SetFill ();
  UIColor.Black.SetStroke ();
  var path = new CGPath ();
  path.AddLines(new CGPoint[]{
    new CGPoint(100,200),
    new CGPoint(160,100),
    new CGPoint(220,200)});
  path.CloseSubpath();
  gctx.AddPath(path);
  gctx.DrawPath(CGPathDrawingMode.FillStroke);
}
var image = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();

This renders a triangle in the sketch, as shown below:

Core Graphics sketch

Visualizing Views

Visualizers aren’t limited to just images. You can display views as well, such as a UIView on iOS or an NSView on OS X. For example, here is an NSBox with a border:

view visualization

Where sketches start getting even more compelling is when you start using them to modify code running in the iOS simulator and the Xamarin Android Player. For example, here is some Xamarin.Forms code created on the fly in a sketch, running in the Android Player:

forms sketch

To learn more about Sketches, check out the documentation in our developer center and the Sketches’ samples. Also see Aaron Bockover‘s great talk from Evolve.

TwitterFacebookGoogle+LinkedInEmail
November 19, 2014

Help Test the Future of Xamarin.Mac

By

Xamarin.Mac and Xamarin.iOS have always been close sister projects, sharing much of their underlying tooling and infrastructure. One of the features in the upcoming version of Xamarin.Mac that we are very excited about is the runtime unification.

Underlying any application that uses Xamarin.Mac (or Xamarin.iOS) is a runtime that manages interactions with the objective-c runtime. It handles exposing your C# objects to objective-c and your calls into various Apple APIs. Up until now we had two separate runtimes, one for iOS and one for OS X.

The runtime unification effort changes that, we now have the same runtime powering our Mac and iOS products. This will bring bug fixes and performance work done on iOS to OS X and enable many of the features that were pioneered in iOS to come to the Mac platform,  such as the new refcount system.

While we have worked hard to test these runtime changes internally, such a far reaching change has the potential to introduce bugs in many places.

We are releasing a preview version of the upcoming Xamarin.Mac to the alpha channel for an extended period of time for testing.

While the runtime unification work is the major feature of this preview release, this alpha also adds support for these 64-bit frameworks:

  • Accounts
  • GameController
  • EventKit
  • MapKit
  • MediaAccessibility

in addition to the frameworks provided in the previous alphas:

  • CloudKit
  • GLKit
  • JavaScriptCore
  • LocalAuthentication
  • SpriteKit

We are asking you to test your applications with it and report any issues you might find.

TwitterFacebookGoogle+LinkedInEmail

Xamarin Insights and the Azure Outage

By

On November 18, 2014 at about 5:00PM PST, Xamarin Insights experienced a service disruption due to a worldwide outage of Microsoft Azure. In addition, we had been experiencing partial outages at least 5 hours prior to this.

Even though Azure suffered a catastrophic storage failure, our event collection API – the web service that receives telemetry from every mobile app that has the Insights client library running – was able to receive and store reports during the entire outage. This means that we experienced zero data loss during this down time.

Even if our event collection API had been overwhelmed or inoperative, the Xamarin Insights client library has a smart queueing system which queues reports locally on end-user devices, and sends them once service is restored.

Our services that process the telemetry data have fully caught up on the backlog of data that was collected during the Azure outage. The aggregate statistics displayed in the graphs and various “counts” are lagging about an hour behind, but will continue to catch up throughout the rest of the day.

Insights - Azure

A graph showing the backlog of telemetry data. Notice the 3 minor hiccups before the outage.

Our goal with Xamarin Insights is to provide a real-time, comprehensive app monitoring service that helps you understand exactly how well your app is performing. We are gratified that the architectural decisions we’ve made so far have paid off in challenging circumstances, and we’ve learned a lot from this outage about how we can improve Insights in the future.

To learn more about Xamarin Insights to add real-time monitoring to your mobile applications check out xamarin.com/insights.

TwitterFacebookGoogle+LinkedInEmail

Live Webinar: Mobile Enterprise Success with Xamarin and IBM

By

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

IBM and Xamarin Logos

Join IBM and Xamarin technical executives on Thursday, December 11 at 8 am PST/ 11 am EST/ 5 pm GMT for a live webinar as they discuss the IBM and Xamarin partnership, demo the IBM MobileFirst SDK for Xamarin, walkthrough the IBM Worklight platform and answer any developer questions.

Ken ParmeleeKen Parmelee
IBM Business Development Executive & Program Director, MobileFirst

Dustin AmrheinDustin Amrhein
IBM Mobile Technical Leader, MobileFirst


Steve HallSteve Hall
Xamarin Director of Enterprise Mobility


We’ll send a recording after the webinar, so we encourage you to register even if you’re unable to attend.

Register Now


TwitterFacebookGoogle+LinkedInEmail
November 18, 2014

Getting Started with the Xamarin Android Player

By

Slow emulators and fragmentation xamarin-android-playerare two of the main frustrations for Android developers. Android emulators are slow to boot and perform poorly, but buying multiple devices to debug an application for multiple API levels isn’t an affordable (or scalable) solution. Neither of these scenarios are ideal for real world mobile development.

At Xamarin, our customers told us they were struggling with slow emulators, so we developed the Xamarin Android Player, introduced at Xamarin Evolve 2014. It can be downloaded from its dedicated page.

Blazing Fast Emulator

Xamarin Android Player Pic 2The Xamarin Android Player runs Android x86 virtual machines using hardware accelerated virtualization technology and is available on both Windows and Mac OS X. It supports OpenGL, delivering smooth, fast graphics. With these features, and a boot time of as little 17 seconds, it’s a blazing fast Android emulator. It also tightly integrates with Visual Studio and Xamarin Studio, so that developers can build, deploy, and debug their apps right from their favorite IDE. Additionally, you can run the Xamarin Android Player side-by-side with the Windows Phone Hyper-V emulator without any conflicts for a great development experience on Windows.

Getting Started

After installing Xamarin Android Player you will be able to browse from a selection of Android images featuring different API levels. Once you have an image installed, you are able to start the player directly from Visual Studio or from Xamarin Studio’s debug on device option.

Xamarin Android Player Images

Even More Features

The Android Player can also emulate different properties of devices, including battery percentage, volume levels, GPS location, and screen orientation. This allows you to try your application in different scenarios. You can even take a screenshot of your running application.
Xamarin Android Player - Pic 3

Download Now

The Xamarin Android player is available to all Xamarin users with an active Xamarin.Android trial or full Xamarin subscription, and the Xamarin Android Player documentation and release notes are great places to help you get started with it today!

TwitterFacebookGoogle+LinkedInEmail
November 12, 2014

Microsoft and Xamarin Expand Global Partnership

By

Xamarin CEO Nat Friedman on stage at Microsoft's Visual Studio Connect();

This morning in New York City, Miguel and I joined Microsoft executives on stage at the Connect(); developer event, which outlined what Microsoft has planned for their developer tools and application platforms.

We launched our partnership with Microsoft one year ago, and in that year a lot has happened. We have reached over 20,000 companies and more than 100 members of the Fortune 500 with Xamarin’s platform, rolled out support for Portable Class Libraries and Shared Projects to make it easier to share code, delivered the Xamarin Designer for iOS making it possible to design iOS UIs from within Visual Studio, and shipped Xamarin.UITest, which makes it easy automate mobile app testing in C# and Visual Studio.

Today we’re excited to take the partnership to the next level, by announcing:

  1. Xamarin Templates in Visual Studio 2015 – Today, we released support for the Visual Studio 2015 Preview release, which includes Xamarin templates that make it easier to discover and download Xamarin from within the IDE. And Microsoft is now including templates for building iOS and Android apps with Xamarin directly in Visual Studio 2015.
  2. Free Xamarin Starter Edition for Visual Studio Users – Today, Microsoft announced a new, free edition to Visual Studio—Visual Studio Community. Visual Studio Community contains support for extensions, which means it will be Xamarin compatible with from day one. We want to help make Visual Studio Community a tool for anyone to create native apps for iOS and Android, so we are announcing our plans to enable our freely available Xamarin Starter Edition to work with Visual Studio Community. We are also doubling the size limit on apps that can be created with Xamarin Starter Edition, so that you can build even more capable apps for free. This will be available in the coming weeks.
  3. Special offers for MSDN Subscribers – We’ve worked with Microsoft to create a  20% discount for Visual Studio Premium and Ultimate MSDN subscribers to purchase Xamarin Business or Enterprise Editions, or world-class mobile development training with Xamarin University, available up to 60 days after the Visual Studio Purchase. Claim your MSDN benefits today.

Xamarin CTO Miguel de Icaza on stage at Microsoft's Visual Studio Connect();

We are happy to work closely with Microsoft to make sure that .NET developers can build native apps for every device on the planet.

If you’d like to check out all of the new things we’ve added to our Visual Studio support, but your Xamarin trial has expired, let us know and we’ll give you another 30 days!

TwitterFacebookGoogle+LinkedInEmail
November 10, 2014

App Spotlight: VentusAR’s Augmented Reality Wind Turbines with MonoGame Video

By

George Banfill from Linknode gave us an overview of VentusAR.  Utilizing the Xamarin platform and MonoGame, they have created a unique augmented reality (AR) experience to visualize what wind farms would look from a location.  VentusAR heavily utilizes native features in iPads and Android tablets to access the GPS, accelerometer, compass, and live camera feed to superimpose virtual turbines on the landscape in real-time.

The app provides immediate visualizations of wind-farms to businesses and the public before they’re built, something that would normally take weeks or months.  VentusAR radically reduces that time by loading geographic data models and GPS coordinates of the proposed locations, then going out in the field with the tablet to render 3D turbines aligned on top of a live camera feed.

To really appreciate how innovative this experience is we took this video where George takes us through the problems VentusAR solves and shows us how it works.  Watch it in full-screen to see it in action.

VentusAR opened my eyes about the possibility of using game technology to solve real-world business problems, creating one of the most unique app experiences I’ve ever seen.

Thank you to Linknode for sharing your app with us!

Learn More

Visit VentusAR’s website to learn more.

To get started developing with the Xamarin platform, check out our developer documentation, learn more about MonoGame, and get live online training with Xamarin University.

TwitterFacebookGoogle+LinkedInEmail
November 7, 2014

Programming for Google Cardboard on iOS using F#

By

One of the highlights of Xamarin Evolve is the Darwin Lounge, a hall filled with programmable devices ranging from robots to iBeacons and quadcopters to wearables. One thing that was particularly intriguing this year was a stack of kits from DodoCase, “inspired by Google Cardboard.” Google Cardboard is an inexpensive stereoscope that exploits the ridiculously small pixels of modern phones. Instead of synchronizing two displays, it directs your eyes separately to the two halves of a phone screen in portrait mode.

cardboard

Unfortunately, all of the resources for programming Google Cardboard have been Android only. This is not the Xamarin way and could not stand! Luckily, Joel Martinez had written a 3D demo for our talk, Make Your Apps Awesome With F#, and it was just a matter of a quick hacking session to see our Xamarin.iOS code in glorious stereoscopic 3D.

before_and_after

Functional Refactoring

As Mike Bluestein has written previously, the easiest way to program 3D on iOS is to use Scene Kit, which is what Joel and I had done for our demo. Stereoscopic programming in Scene Kit, as it turns out, is easy!

One great aspect of F# and the functional programming style is that refactoring is often easier than object-oriented refactoring. Instead of creating new objects and data structures, you’re generally focusing on “minimizing the moving parts” and extracting common functionality into reliable functions.

For instance, the first thing we needed to do was switch from a single UIView to two side-by-side views. We refactored this code:

//Configure view
let r = new RectangleF(new PointF(0.0f, 0.0f), new SizeF(UIScreen.MainScreen.Bounds.Size))
let s = new SCNView(r)
configView s scene |> ignore
this.View <- s

into this code:

//Configure views
let outer = new UIView(UIScreen.MainScreen.Bounds)
let ss =
    [
        new RectangleF(new PointF(0.0f, 0.0f), new SizeF(float32 UIScreen.MainScreen.Bounds.Width / 2.0f - 1.0f, UIScreen.MainScreen.Bounds.Height));
        new RectangleF(new PointF(float32 UIScreen.MainScreen.Bounds.Width / 2.0f + 1.0f, 0.0f), new SizeF(UIScreen.MainScreen.Bounds.Width / 2.0f -1.0f, UIScreen.MainScreen.Bounds.Height));
    ]
    |> List.map (fun r -> new SCNView(r))
    |> List.map (fun s -> outer.AddSubview(configView s scene); s)
this.View <- outer

Although you may be more familiar with C# than F#, you should be able to follow what’s going on in the original snippet. We had a RectangleF as big as the entire screen’s Bounds. We created a single SCNView called s. We configured s to show our scene and then, because we don’t need to do any more manipulation on the result of that calculation, we called the ignore function with the result (the |> is F#’s pipe operator, which works just like the familiar pipe operator on the UNIX command-line or PowerShell). Finally, we assigned this single SCNView to be the main View of our controller object.

To refactor, we introduce an outer view that will contain our two eye-specific views. We then use the |> operator again to:

  • Create a 2-element list of RectangleFs, each a half-screen wide
  • Create an SCNView for each one of those
  • Configure each SCNView with the scene
  • Add them to the outer container UIView

Now we have two side-by-side SCNViews, but each is rendering the exact same scene, so there is no 3D effect. Scene Kit is a scene-graph toolkit, and to get a stereoscopic 3D effect, we’re going to need two camera nodes slightly separated in space. That’s easy. We replace:

//Camera!
let camNode = new SCNNode()
camNode.Position <- new SCNVector3(0.0F, 0.0F, 9.0F)
scene.RootNode.AddChildNode camNode

With:

//Cameras!
let camNode = new SCNNode()
let leftCamera = buildCamera camNode (new SCNVector3 (0.0F, 0.0F, 9.0F))
let rightCamera = buildCamera camNode (new SCNVector3 (0.2F, 0.0F, 9.0F))

Note the slight difference in the first argument to the SCNVector3 constructor – this eye-position vector is the “moving part” that we want to isolate. So now our camNode has two subnodes, each containing a node that defines one of our eye positions.

The buildCamera function is:

let buildCamera (parent : SCNNode) loc =
    let c = new SCNNode()
    c.Camera <- new SCNCamera()
    parent.AddChildNode (c)
    c.Position <- loc
    c

It’s worth emphasizing that this function is strongly-typed. Even though it doesn’t explicitly state that loc is an SCNVector or that it returns an SCNNode, F#’s type inference is powerful enough to figure that out and enforce the types at compile-time. (As for programming style: “Is it better to explicitly declare types in the function signature or let them be implicit?” is the type of discussion that happens both in the Darwin Lounge and at Xamarin Evolve parties…)

Now we have two scenes and two camera nodes. To join them together, we use:

//Set PoVs to shifted cameras
ss.Head.PointOfView <- leftCameraNode
ss.Tail.Head.PointOfView <- rightCameraNode

And there you have it! In the following image, you can see the converging perspective of the building climbing into the sky.

living_in_stereo

This might not be ready for the Avatar sequel, but it’s really cool when viewed through Cardboard!

Here’s something James Cameron can’t do, though: exploit the gyroscope and accelerometer on iOS devices. This block of code shifts the orientation of the camNode camera node so that it tracks the direction in which the user is looking:

    let rr = CMAttitudeReferenceFrame.XArbitraryCorrectedZVertical
    this.motion.DeviceMotionUpdateInterval <- float (1.0f / 30.0f)
    this.motion.StartDeviceMotionUpdates (rr,NSOperationQueue.CurrentQueue, (fun d e ->
        let a = this.motion.DeviceMotion.Attitude
        let q = a.Quaternion
        let dq = new SCNQuaternion(float32 q.x, float32 q.y, float32 q.z, float32 q.w)
        let dqm = SCNQuaternion.Multiply (dq, SCNQuaternion.FromAxisAngle(SCNVector3.UnitZ, piover2))
        camNode.Orientation <- dqm
       ()
    ))

Which looks like this in action:

To experiment with stereoscopic 3D in Xamarin and F#, download this Starter-compatible project in Xamarin Studio on Mac or Windows.

TwitterFacebookGoogle+LinkedInEmail
November 6, 2014

Xamarin Test Cloud Video Series: Using C# and UITest to Create Your First Mobile Test

By

Xamarin.UITest is a C#-based testing framework enabling automated UI acceptance tests for iOS and Android applications that can be uploaded to Xamarin Test Cloud to test on over 1,000 real devices. Xamarin.UITest is available as a NuGet package and relies on the popular NUnit testing framework that most C# developers are familiar with.

In this video, Dan Waters shows us the steps to utilize UITest, and also how to use the interactive shell (REPL) included with Xamarin.UITest to explore the views on a screen and to automate interactions with the application. The best thing about Xamarin.UITest is that it tests any mobile app regardless of the platform it’s written in – Objective-C, Java, Xamarin, or 3rd party frameworks.

Each test is a method inside an NUnit Test Fixture class and follows the Arrange-Act-Assert pattern:

  1. Arrange – The test sets up conditions and initializes so that the test can be actioned.
  2. Act – The test interacts with the application, entering text, pushing buttons, tapping, etc.
  3. Assert – The test examines the results of the actions performed in the Act step to determine correctness. For example, the application may verify that a particular error message is displayed.

Watch it in full-screen to see the code and Xamarin.UITest in action.

Learn More & Get Started

To learn more about Xamarin Test Cloud, visit the product page, or check out our developer documentation.

TwitterFacebookGoogle+LinkedInEmail