December 21, 2014 4:06 GMT

Generating App Screenshots Using Xamarin.UITest

With a white label app platform like ours at Olo, generating screenshots for every app we publish can be a real chore. It makes sense for us to use simulators/emulators to do this, given the large number of device sizes we need to generate for, so it's not something we can easily farm out to a non-engineer to do manually without them spending an obscene amount of time on it. If you haven't noticed already, we're big on automation, so I set out to see if we could automate this as well.

Xamarin.UITest is a great library from Xamarin that makes it really easy to write UI tests in C#/F# for your iOS and Android apps. Under the hood, Xamarin.UITest uses Calabash in order to facilitate this functionality. You can run these tests both locally as well as in Test Cloud, which means you can easily take your tests and run them across Test Cloud's large device farm.

For this example I'll focus on iOS, but the same code will also work for Android, minus the iOS-specific parts.

Listing all iOS Simulators

These days it's necessary to submit screenshots for your apps across many different screen sizes for iOS. To start out I wanted to just pull screenshots for every iOS simulator configuration on my system. Eventually I'll probably fine tune this to only pick the ones it absolutely needs. Here's some code in F# that returns a list of all the available iOS simulators:

module SimulatorHelpers

open System.IO  
open System.Xml

let listAvailableSimulators = fun simulatorRoot ->  
    Directory.EnumerateFiles(simulatorRoot, "device.plist", SearchOption.AllDirectories)
    |> Seq.map (fun path ->
        let plistDoc = new XmlDocument()
        plistDoc.LoadXml(File.ReadAllText(path))
        let dictNodes = plistDoc.GetElementsByTagName("dict").Item(0).ChildNodes

        let values = (
            seq { for i in 0..dictNodes.Count - 1 do if i % 2 = 0 then yield i }
            |> Seq.map (fun i -> (dictNodes.Item(i).InnerText, dictNodes.Item(i + 1).InnerText)))
        let getValue = fun(key) -> values |> Seq.pick (fun (k, v) -> if key = k then Some(v) else None)

        (getValue "name", getValue "UDID")
    )

Generating Screenshots

Now that the list of simulators is available, we can pass those to Xamarin.UITest and run our tests. In our system we have classes defined already that represent each screen in our app, in order to make it easy to write UI tests around these screens. For this example, we'll launch the app in each simulator and grab a couple screenshots while tapping through it.

If you've used Test Cloud before you're already familiar with how it takes screenshots every time you call app.Screenshot(), but what you might not have noticed is that the method actually returns a FileInfo object for the locally saved file. All we need to do is copy that file over to wherever we need it, and we have our screenshot!

Here's a console app in F# that ties this all together:

open System  
open System.IO  
open SimulatorHelpers  
open Xamarin.UITest  
open UITests.Core.Screens

[<EntryPoint>]
let main argv =  
    let screenshotFolderPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())
    Directory.CreateDirectory(screenshotFolderPath) |> ignore

    let saveScreenshot deviceFolderPath screenshotNumber (file:FileInfo) =
        let screenshotPath = Path.Combine(deviceFolderPath, (screenshotNumber.ToString() + ".png"))
        file.CopyTo(screenshotPath)

    listAvailableSimulators "/Users/gshackles/Library/Developer/CoreSimulator/Devices" 
    |> Seq.iter (fun (name, udid) ->
        Console.WriteLine("Generating screenshots for " + name)

        let deviceFolderPath = Path.Combine(screenshotFolderPath, name)
        Directory.CreateDirectory(deviceFolderPath) |> ignore

        let app = ConfigureApp
                    .Debug().EnableLocalScreenshots()
                    .iOS
                    .AppBundle("path/to/my.app")
                    .DeviceIdentifier(udid)
                    .StartApp()
        let takeScreenshot number = app.Screenshot(number.ToString()) |> saveScreenshot deviceFolderPath number |> ignore

        let loggedOutHomeScreen = LoggedOutHomeScreen(app)
        loggedOutHomeScreen.WaitUntilLoaded()
        takeScreenshot 1

        let findLocationsScreen = loggedOutHomeScreen.StartNewOrder()
        findLocationsScreen.WaitUntilLoaded()
        takeScreenshot 2
    )

    0

Once this finishes running, the temporary folder created here contains folders for each simulator, and files in each for each screenshot taken.

December 21, 2014 2:17 GMT

Evolve 2014 Summary: Extending Xamarin.Forms with Custom Controls – Jason Smith, Xamarin

I’m going to be doing a series of blog posts on the Xamarin Evolve 2014 Conference, they’ll be detailed summaries of the sessions.

My first one, Extending Xamarin.Forms with custom controls by Jason Smith, was a very very good session. Jason is a lead dev on Xamarin.Forms, this is fairly clear in the session as he goes into great details and his Q&A was amazingly insightful.

Intro

To begin with Jason explains that the amount of APIs on iOS and Android are huge.

  • iOS 33,000 APIs
  • Android 40,000 APIs

He then shows a quote from Albert Einstein.

“Everything should be made as simple as possible, but not simpler” - Albert Einstein

Jason then explains that “Writing code is about managing complexity”,  ”Complexity is what makes your app special, but complexity is also what makes your app hard to develop.”

  • “Complexity is a source of bugs”
  • “Complexity is what makes your app amazing”
  • “Complexity is a necessary evil”

I understand Jason’s point in this, as personally I’ve always thought ‘managing complexity’ was a important part of what software developers do. It’s also very true in Xamarin and Xamarin.Forms as in order to build apps that users love we need to add this complexity.

Custom Renderers

A renderer is what turns a button into a button:

To start off Jason shows a basic framework of an app built with Xamarin.Forms, it’s a very basic app. He then proceeds to tell us how to use the built in styles to do styling for Xamarin.Forms. Once done the app looks nicely styled but Jason then moves on to show us how it can be taken to the next level with custom renderers.

Jason explains that Export Renderer is the bases of Renderers, he also explains that the reason Export Renderer is on the assembly is because it’s more performant to read attributes from the assembly that the classes.

Jason’s first sample of a custom renderer is a CircleImageRenderer that inherits from ImageRenderer. I’ll include some important points that Jason makes.

The OnElementChanged method is the most important method when using custom renderers. It tells you the element your watching has changed, therefore you must adapt and change. It’s possible for a ListView to reuse renderers rather than new up new renderers. You must be aware of this. He describes the best way to handle this, as per the screenshot further down this post.

When handling the OnElementChanged event you initially check if the Control is null, then if the old element is null unhook old events, if the new element is not null then hook the new events.

Jason then demonstrates a loading view custom renderer,  interestingly Jason uses a single ContentPage and fades in the loading view as the content then hides it and swaps the content with the view he actually wants.

Jason claims it’s the coolest loading view of all time and it’s actually fairly impressive, well for geek programmers anyway.

He then continues and explains a bug that we might hit when developing Xamarin.Forms Custom Controls.

OnElementChanged event gets called many times, well as many times as we choose. Sometimes it’s once and sometimes it’s hundreds. But you do need to handle this, as SetNativeControl needs to be set one time.

Bad Code

Screen Shot 2014-12-10 at 8.30.28 am

Better Code

Screen Shot 2014-12-11 at 8.31.59 am

 

The (good) Pattern:

- First check if your control is null, if null create a new control.

- If your old element is not null, then unsubscribe

- If your new element is not null, then subscribe

 

Q & A:

Attendee: Is the only way to set renderers is to export them?

Jason: The answer is yes, renderers are only associated through exporting. Jason also makes a point saying that *dont override the default renderers, make a custom subclass.

The attendee then suggests that you can’t use two renderers for a single control. Jason confirms this is correct.

 

Attendee: An attendee wanted to know about the roadmap in regards to transitions.

Jason: It’s on the radar and it’s something we want to do.

 

Attendee: Is there any plans to swap out the service locator so we could have multiple renderers for a control?

Jason: At the moment it’s not possibly and not exactly on the radar either.

 

Attendee: Mentions that Jason did a great presentation and doesn’t give himself enough credit, as Jason and his team has really built something special.

 

Attendee: What about extending layouts?

Jason: At the moment you can subclass layouts, the Layout is internal but soon it will be exposed to you.

 

Attendee:  So in layouts we can add our own sprite kits etc

Jason:  Yes, this should work and be fairly easy

 

Attendee: Can you explain what’s in 1.3 release

Jason: Styles, Behaviours, Triggers, Dynamic Resources, Styles Based on Dynamic Resources (which is new to the whole world).

 

Attendee: Is there any plans to add more gestures to Xamarin.Forms? What about popups?

Jason: Popups will be added. Generally people want two gestures Long Tap and Swipe. Well we’ve got something better coming context actions, so on your cell you set the context action and easily add mailbox swipe style cells.

*I’ll be very interested in seeing what context actions are, I feel like they could be something amazing.

 

Attendee: Wondering why you created Xamarin.Forms on Android to be a single Activity rather than multiple activity?

Jason: At the time we started fragments weren’t fully back ported. Google was promoting the single activity approach. The navigation in Activities didn’t fully map to the Xamarin.Form navigation.

 

Attendee: We use alot of 3rd party components and many time these 3rd part components require a native View or ViewController. At the moment we use a Custom Renderer as this is the only way to do this right now, will there be better ways in the future, some sort of Native Hookiness?

Jason: Yes there will be some Native Hookiness.

 

Attendee: Is there intention to make some sort of UI Designer, Xamarin.Forms Designer.

Jason: The big question, the elephant in the room. There is an intention is to make something that will really help with designing Xamarin.Forms, will that be a drag and drop designer? Probably not! Why, because it’s actually not that useful in a cross platform scenario, because you want a live preview. What you really want is live Xaml coding and a popup of the stuff on all three platforms. I’m not announcing anything coming at any point other than saying it would be really stupid for us not to do it. That is not a blood contract so please don’t kill me.

 

Attendee: I notice a lot of the support around Xamarin.Forms is centred around phones, do you think Xamarin.Forms will be a good solutions for tablets?

Jason: It means that tablets are supported but it’s not automatically adapted to it. It’s your job to adapt Xamarin.Forms to tablet. Which basically means you need to change your layouts to adapt to the tablet.

*Which is how it always is/was on mobile development.

 

Summary

This was a great video for myself as it was related to the work I do every day, it also provided some great insights into the future of Xamarin.Forms.

Thanks to Jason for the great presentation.

Here’s a link to the video if you want to watch.

Michael

 

 

 

The post Evolve 2014 Summary: Extending Xamarin.Forms with Custom Controls – Jason Smith, Xamarin appeared first on Michael Ridland.

December 20, 2014 8:48 GMT

My Favorite Books of 2014

In 2014 I read (according to GoodReads) 47 Kindle books and (according to Audible) 101 audible books.

This year I read zero books on paper.

Here is my short list of the very best:

  • Far from the Tree
  • Ulysses
  • What If?
  • The Innovators
  • The Sixth Extinction
  • Thirteen Days in October
  • The Most Dangerous Book In the World
  • The GoldFinch (and all of Donna Tartt)

But not necessarily in that order.

Enjoy, and Happy New Year!

Best2014a

book7book6book5book4book1

 

 

 

 

 

 

 

 

 

December 19, 2014 10:17 GMT

Elegant Circle Images in Xamarin.Forms

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

MonkeyCircleImages

Custom Image

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

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

Custom Renderers

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

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

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

iOS Renderer

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

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

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

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

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

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

Android Renderer

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

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

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

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

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

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

Windows Phone Renderer

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

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

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

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

Custom Cell

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

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

CircleImages

See the Code in Action

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

December 18, 2014 5:42 GMT

Holiday Contest: Create a Plugin for Xamarin

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

What is a Plugin?

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

Contest

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

How to Enter

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

Prizes

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

Today’s Plugins

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

Plugin Ideas

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

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

Rules & Regulations

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

Jump Start Development

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

Discuss this blog post in the Xamarin Forums

December 18, 2014 7:40 GMT

Migrating an existing Xamarin.iOS app to Unified API

As of February 1st, Apple will require that "new iOS apps submitted to the App Store must include 64-bit support and be built with the iOS 8 SDK." For Xamarin developers this means a migration from the Classic API to the new Unified API. Xamarin is providing migration tooling to automate the process, but some manual work still needs to be done by the developer.

I'll demonstrate the process by migrating one of our pre-built apps: T-Shirt Store.

The migration tool and Unified project templates will be available in the stable channel on January 5th (what is currently in stable is out-of-date, please don't use it). If you're of an adventurous type, you can switch to the alpha channel right now and give it a whirl.

Grab the app's source code, open the solution in Xamarin Studio, and select Project → Migrate to Xamarin.iOS Unified API.

The migration should fix the bulk of the incompatibilites. However, once you build the project you'll see that there are some issues that will need to be resolved manually.

I'll skip trivial casting errors and those similar to the ones below for brevity's sake.

Error CS0234: The type or namespace name 'UIKit' does not exist in the namespace 'MonoTouch'. Are you missing an assembly reference? (CS0234) (XamarinStore.iOS)

MonoTouch and MonoMac namespaces have been removed to increase code shareability between Apple platforms.

#if __IOS__
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
#endif

#if __IOS__
using UIKit;
using CoreGraphics;
#endif

Error CS0266: Cannot implicitly convert type 'System.nfloat' to 'float'. An explicit conversion exists (are you missing a cast?) (CS0266) (XamarinStore.iOS)

Ints, uints, and floats have been replaced by nints, nuints, and nfloats to accomodate both 32-bit and 64-bit architectures.

float keyboardOffset = 0;
...
keyboardOffset = visible ? frame.Height : 0; 

nfloat keyboardOffset = 0;

Error CS0103: The name 'StringSize' does not exist in the current context (CS0103) (XamarinStore.iOS)

A number of APIs have been removed (see Sebastien's comment below).

numberSize = StringSize (badgeNumber.ToString (), Font);    

// numberSize = UIStringDrawing.StringSize (badgeNumber.ToString (), Font);
numberSize = badgeNumber.StringSize (Font);

Error CS1502: The best overloaded method match for 'CoreGraphics.CGSize.CGSize(System.nfloat, System.nfloat)' has some invalid arguments (CS1502) (XamarinStore.iOS)

Some new types were introduced (search for NMath).

Frame = new CGRect (Frame.Location, new CGSize (Math.Max (numberSize.Width, height), height));

Frame = new CGRect (Frame.Location, new CGSize (NMath.Max (numberSize.Width, height), height));

Error CS0123: A method or delegate 'XamarinStore.JBKenBurnsView.nextImage()' parameters do not match delegate 'System.Action<Foundation.NSTimer>(Foundation.NSTimer)' parameters (CS0123) (XamarinStore.iOS)

In this case, NSTimer's signature has slightly changed. Intellisense is your best friend here.

timer = NSTimer.CreateRepeatingScheduledTimer(ImageDuration, nextImage);
...
void nextImage()

void nextImage(NSTimer tr)

Error CS1502: The best overloaded method match for 'Foundation.NSValue.FromSizeF(System.Drawing.SizeF)' has some invalid arguments (CS1502) (XamarinStore.iOS)

RectangleF, SizeF, PointF have been replaced by CGRect, CGSize, and CGPoint.

growAnimation.To = NSValue.FromSizeF (grow);

growAnimation.To = NSValue.FromCGSize (grow);

Error CS1593: Delegate 'System.Action<Foundation.NSTimer>' does not take '0' arguments (CS1593) (XamarinStore.iOS)

This is related to error CS0123 above, we just need to conform to the new NSTimer signature.

NSTimer.CreateScheduledTimer (.5, () => view.RemoveFromSuperview ());

NSTimer.CreateScheduledTimer (.5, (t) => view.RemoveFromSuperview ());

Error MT0034: Cannot include both 'monotouch.dll' and 'Xamarin.iOS.dll' in the same Xamarin.iOS project - 'Xamarin.iOS.dll' is referenced explicitly, while 'monotouch.dll' is referenced by 'BTProgressHUD, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. (MT0034) (XamarinStore.iOS)

This usually means that a Xamarin Componet or a NuGet in the project is still using the Classic API.

In this case, both Json.NET and BTProgressHUD are causing problems, however, both have been already migrated to the Unified API by their respective authors (see the ios-unified tag in the component details window).

BTProgressHUD is already available as a Unified binary, but it was built against the current stable branch, 8.4, which is not compatible with the new alpha 8.6 API's. So, as I can't (and shouldn't) release an binary built with the alpha channel version of Xamarin.iOS, I've put a one-off build up here. This is the same as what's on the component store right now (v1.14), just built against the 8.6 Unified build. (Nic Wise, author of BTProgressHUD)

Ignore the Component Store version of BTProgressHUD for now and simply add the dll manually. As for Json.NET, grab the NuGet version instead.

Let's build one last time and run the app:

Great success!

It's worth noting that a number of issues have not been reported as errors: mostly ints and floats that need to be converted to nints and nfloats. Search the project and use the following notes as a guide. As a rule of thumb, anything that touches iOS internals needs be converted to the new native types.

You can grab the complete project on GitHub.

Shoutout to my colleague James Clancey for helping with this. Also, thanks to Gerry High for alerting me regarding the BTProgressHUD incompatiblity.

December 17, 2014 2:30 GMT

Webinar Recording: Mobile Enterprise Success with Xamarin and IBM

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

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

View the presentation slides for this webinar here.

Additional Resources

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

December 16, 2014 4:37 GMT

How to Update NuGet Packages for 64-bit

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

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

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

Xamarin iOS, Mac and NuGet

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

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

Getting Ready to Use NuGet Packages with Unified Projects

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

Software needed on Windows

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

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

Extensions and Updates Dialog NuGet Update

Software needed on Mac

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

Creating a NuGet Package for Unified Projects

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

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

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

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

NuGet Unified Lib Directories

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

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

The following PCL lib directory follows the recommendation:

lib\portable-net45+win+wpa81+wp80

Whilst the following PCL lib directory should be avoided:

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

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

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

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

Learn More

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

December 16, 2014 10:36 GMT

Scheduled Notifications in Android using Alarm Manager

Notification-Android-Wear

Few months ago, I wrote an article for DNC Magazine titled “Hello Xamarin.Forms!” which was later republished online on DotnetCurry.com. This article demoed all awesomeness of Xamarin.Forms with a simple Vehicle Service Reminder app as an example. One of the aspects of the app is to remind users when their vehicle was due for service. While I showed how to go about doing that in iOS and Windows Phone, I left the Android part as an action item for the readers. While some of you may have got it already, if you haven’t, here’s how you do it -

In Android, unlike in iOS, local notifications does not take the fireDate as a parameter while configuring Notifications. So we have to split this task into two -

  • Use system alarm services to wake your app up at a specified time (Using Alarm Manager)
  • Write the code to notify users in the “OnReceive()” method of the Broadcast Receiver

Using Alarm Manager

AlarmManager class is used to schedule your application to be run at some point in the future. Create an Alarm Intent, specify the broadcast receiver and finally set the time when you intend to wake your app up.

public void Remind (DateTime dateTime, string title, string message)
{

	Intent alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver));
	alarmIntent.PutExtra ("message", message);
	alarmIntent.PutExtra ("title", title);

	PendingIntent pendingIntent = PendingIntent.GetBroadcast(Forms.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
	AlarmManager alarmManager = (AlarmManager) Forms.Context.GetSystemService(Context.AlarmService);

	//TODO: For demo set after 5 seconds.
	alarmManager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime () + 5 * 1000, pendingIntent);

}

Notifying Users

Now that the AlarmManager will ensure that your app is run at a specified time, you will have to write the code to notify users in the “OnReceive()” method of the Broadcast Receiver. In this case the broadcast receiver is the AlarmReceiver – a custom class subclassed from BroadcastRecevier.

[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
	public override void OnReceive (Context context, Intent intent)
	{

		var message = intent.GetStringExtra ("message");
		var title = intent.GetStringExtra ("title");

		var notIntent = new Intent (context, typeof(MainActivity));
		var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
		var manager = NotificationManagerCompat.From (context);

					var style = new NotificationCompat.BigTextStyle();
					style.BigText(message);

					int resourceId;
					if (App.SelectedModel.VehicleType == "Car")
						resourceId = Resource.Drawable.Car;
					else if (App.SelectedModel.VehicleType == "Bike")
						resourceId = Resource.Drawable.Bike;
					else
						resourceId = Resource.Drawable.Other;

					var wearableExtender = new NotificationCompat.WearableExtender()
			.SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId))
						;

					//Generate a notification with just short text and small icon
		var builder = new NotificationCompat.Builder (context)
						.SetContentIntent (contentIntent)
						.SetSmallIcon (Resource.Drawable.ic_launcher)
						.SetContentTitle(title)
						.SetContentText(message)
						.SetStyle(style)
						.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
						.SetAutoCancel(true)
						.Extend(wearableExtender);

					var notification = builder.Build();
					manager.Notify(0, notification);
	}
}

The code above uses NotificationCompat.Builder and sets the WearableExtender which will ensure the notifications are also sent to the connected Android Wear device. To know more about wearable programming using Xamarin, don’t forget to check out the post on Tips for your First Wear App.

You can download the full source from my GitHub repo.


December 15, 2014 7:12 GMT

Xamarin Android Player Update Brings New Features & Devices

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

Get the Update

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

New Device Images

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

Xamarin Android Player New Devices

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

Naming & Duplicating

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

Duplicate Device Android Player

Learn More

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

December 15, 2014 7:02 GMT

iOS iBeacon Background Region Monitoring

Earlier this year when iOS 8 was released I wrote up a quick blog post on how to ensure you can scan for iBeacons with the new CLLocationManager RequestWhenInUseAuthorization flag. However recently I have received a lot of questions about how to scan for iBeacons when the app is in the background or when it has been dismissed completely. Apple has some amazing docs on how this functionality works, but here are the basics.

Monitoring != Ranging


Don’t be confused by these two words. Ranging usually takes place in the foregrounds and allows you to actively scan for beacons, where Monitoring allows you to get notified when the device your app is running on enters or exits a specified beacon region. Monitoring can take place in the background and even if your application is completely dismissed.

Setup

When we create our CLLocationManager we must ensure that we call RequestAlawaysAuthorization(); since we want to always be monitoring. Also ensure you add NSLocationAlwaysUsageDescription to your Info.plist with a message so your users will be asked permission.

When we create our region we must set 3 important flags: NotifyEntryStateOnDisplay, NotifyOnEntry, NotifyOnExit. You can pick and choose between all these, however I usually just set all of them up. Now to specify the functionality to run when a region is entered simply implement the RegionEntered event on your location manager:

Final Checks

Since I am using a local notification we must also ask for permission in iOS 8 by adding this flag in my FinishedLaunching of the AppDelegate:

var settings = UIUserNotificationSettings.GetSettingsForTypes (UIUserNotificationType.Alert, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings (settings);



It is important to know that iOS gives your app about 10 seconds to run some logic, and if you need more time you will need to spin up a background task, however usually a local notification will work for simple use cases.

Learn More


Be sure to checkout my iBeaconsEverywhere GitHub repository for a full samples and watch my Xamarin Evolve session on using iBeacons on iOS and Android:
December 13, 2014 5:15 GMT

Product Recommendation -SaneBox for Email

I don’t usually write about individual cool products, but if email is making you crazy this is a product you really want to check out. 

It is called SaneBox and it separates your mail for you automagically into inbox, BuilkMail, View Later, and News.  You can then train it which email belongs where, though it generally gets things right without training.

More, you can move email to Next Week or Tomorrow and it leaves your inbox, only to reappear when you said.

Further, you can forward to any arbitrary time/date (e.g., Tuesday.10am@sanebox.com and it will come back then.  Does a whole bunch more, is highly customizable and generally great.

Enjoy, and I think if you sign up we both get a small discount.

December 12, 2014 5:59 GMT

Triggers in Xamarin.Forms 1.3

Yesterday, I wrote about one of the new features in Xamarin.Forms 1.3 (Technology Preview 2), Styles.  Today I’ll take a first look at Triggers.

Triggers

The key idea of Triggers is “When this happens, do that.” More specifically, “When this property has that value, then set this other property to this new value.”  Huh?  Perhaps this is easier to show than to explain.

Let’s suppose we’re building a form and we’d like to enhance the Entry control so that when the user is entering data the text color is blue, but when they are done the text color turns black.

Step one is to create a style in the Resource Dictionary and to give that Style a set of Triggers… Continued here

December 11, 2014 11:22 GMT

Automating Provisioning Profile Refreshes in Xcode

Refreshing provisioning profiles is a pain. Okay, everything about provisioning profiles is a pain. This pain is amplified once you add a continuous integration environment into the mix. When you add to that a white-label platform like ours with a ton of apps building in it, things get very frustrating. For every app we add to the system, not only do we need to provision everything properly in the developer portal, but we also need to have someone remote into the Mac build agent, open Xcode, and refresh the profiles so we can package the new app. This sucks.

Side Note: if you know about a secret command line utility that can do this, please let me know. My efforts to locate one have been unsuccessful thus far.

So, without the ability to hit a command line utility to trigger this refresh I set out to try the next best thing: automate the UI interaction. I'd never actually tried automating any UI in OS X, so I figured it would make for a fun experiment. I wouldn't say the whole process could be classified as "fun" in the end, but at least I get a blog post and some automation out of it.

In Yosemite, Apple introduced the ability to use JavaScript instead of AppleScript, so I gave that a shot. There are a couple ways you can try it out. First, there's the Script Editor app that ships in OS X that you can use to write and run your scripts, as well as export them either as script bundles or even .app files. You can also use the command line REPL by running:

osascript -il JavaScript  

Another essential utility to be aware of is the Accessibility Inspector. It allows you to hover over the UI of any running app and see the view hierarchy, as well as many properties of the elements there:

Accessibility Inspector

Armed with these tools, I was able to hack together the following script. They key word there is hack. This is pretty ugly, and I'd love to know cleaner ways to get at some of these elements, but for the time being at least it works!

Application("Xcode").activate();

delay(2);

var system = Application("System Events"),  
    xcode = system.processes["Xcode"];

// open preferences
system.keystroke(",", { "using": "command down" });

// click on Accounts tab
xcode.windows[0].toolbars[0].uiElements[1].click();

var accountRows = xcode.windows[0].scrollAreas[0].tables[0].rows,  
    currentRow,
    rowName;

for (var accountIndex = 1; accountIndex < accountRows.length; accountIndex++) {  
    currentRow = accountRows[accountIndex];
    rowName = currentRow.uiElements()[0].name();

    if (rowName === "Repositories") {
        break;
    }

    currentRow.select();
    delay(1);

    // click "View Details"
    xcode.windows[0].groups[0].buttons[0].click();
    delay(1);

    // click "Refresh"
    xcode.windows[0].sheets[0].buttons[1].click();
    delay(5);

    // click "Done"
    xcode.windows[0].sheets[0].buttons[0].click();
    delay(1);
}

A bit ugly, and undoubtedly brittle, but not much code in the end. I put some artificial delays in there to allow the UI time to catch up, and in future versions I'd love to figure out how to check the status of the progress indicator rather than just pausing for 5-10 seconds and then assuming it completed.

Instead of exporting it as a .app file and running it that way, I decided to just execute the script file directly using the same utility mentioned earlier for the REPL:

osascript -l JavaScript RefreshXcodeProfiles.scpt  

Since this can be invoked from the command line, it was trivial to incorporate it into our FAKE scripts:

Refreshing in action

Automate all the things!

December 11, 2014 8:07 GMT

Xamarin.Forms: Styles

Xamarin.Forms 1.3 is now available in Community Preview 2 (the finalInherited Styles community preview before release).  While this is not a release version, it is close and worth taking a look at.  It offers three new killer features:

  • Styles
  • Triggers
  • Behaviors

In this post, I will look at Styles.  Continued…

December 11, 2014 7:31 GMT

BTProgressHUD: Update for X.iOS 8.6 Unified API

Xamarin have released information about how and when to upgrade to the new Unified 32/64 bit API's. Thanks to @redth, BTProgressHUD is already available as a Unified binary, but it was built against the current stable branch, 8.4, which is not compatible with the new alpha 8.6 API's.

So, as I can't (and shouldn't) release an binary built with the alpha channel version of Xamarin.iOS, I've put a one-off build up here. This is the same as what's on the component store right now (v1.14), just built against the 8.6 Unified build.

As always, you can get the component from GitHub and build it yourself.

If you are still using the classic (old/normal) APIs, you don't need to do anything - well, you do, you need to port to Unified before 1 Feb 2015, but Xamarin has your back for that. This build is just for people using the Alpha channel who have got X.iOS 8.6 recently.

To use it, just remove BTProgressHUD's component from your project, and add this DLL in. Thats it. Once the proper component comes out, just remove the DLL and add the component back in.

Happy HUDing, and thanks to Gerry High for pointing this out to me.

December 11, 2014 4:23 GMT

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

In October, Apple announced that starting in February, submissions to the App Store must be built against the iOS 8 SDK and must include 64-bit support. While there has not been a definitive statement about whether this deadline applies only to new app submissions, or if it includes updates to existing apps, it is our recommendation that developers submitting new app submissions OR app updates adhere to the 64-bit requirement by the February 1st deadline.

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

What you need to know:

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

ios and osx logos

What To Do Today:

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

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

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

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

Installation

Additionally, Windows users with Visual Studio should:

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

December 10, 2014 10:38 GMT

Sketches in Xamarin Studio Alpha

A new version of Sketches just landed in the latest Xamarin Studio alpha. Let’s take a look at a couple new things that have been added.

In the previous version, images could be loaded in a sketch given the path on disk. Now, you can add a .Resources folder next to the sketch file, with the naming convention of sketchname.sketchcs.Resources.

For example, with a sketch named Sample.sketchcs, I created a folder named Sample.sketchcs.Resources at the same location as the sketch file, and added a file named hockey.png in the folder. WIth this I can write code like the following in the sketch:

using AppKit;

var image = NSImage.ImageNamed ("hockey");

Then I can visualize the image in the sketch:

sketch resources

Speaking of visualizers, they have been greatly enhanced in the latest version. For example, one of the many visualizers that has been added is for a CIImage. Therefore you can quickly iterate and test the results of different Core Image filters without needing to deploy an app!

For example, here’s some code to apply a noir effect to the above photo:

var noir = new CIPhotoEffectNoir {
    Image = new CIImage(image.CGImage)
};
		
var output = noir.OutputImage;

This result is immediately available to view as shown below:

CIImage visualizer

There are 41 filters in total now, including NSAttributedString, NSBezierPath and CGPath to name a few.

See the Xamarin Studio release notes for the complete list, as well as all the other features that have been added.


December 09, 2014 10:30 GMT

CBPeripheralManager for iBeacons in iOS 8

I recently ran into an interesting issue with the code for the FindTheMonkey iBeacon app. Previously I had the code for the app to act as an iBeacon using a CBPeripheralManager, which I created in the ViewDidLoad method. This previously worked fine but someone ran into an issue where ranging for the beacon never discovered it. To resolve this involved a couple small changes:

  1. Move the creation of the CBPeriheralManager into the constructor.
  2. peripheralDelegate = new BTPeripheralDelegate ();
    
    peripheralMgr = new CBPeripheralManager (
      peripheralDelegate, 
      DispatchQueue.DefaultGlobalQueue);
    
  3. Call the StartAdvertising method in ViewDidAppear.
  4. public override void ViewDidAppear (bool animated)
    {
      base.ViewDidAppear (animated);
    
      var power = new NSNumber (-59);
      peripheralData = beaconRegion.GetPeripheralData (power);
      peripheralMgr.StartAdvertising (peripheralData);
    } 
    

With these changes in place, ranging for the beacon discovers it as it had before:

iBeacon FindTheMonkey


December 09, 2014 3:31 GMT

Solving a Stuck Automated UI Test on iOS

We've been using Xamarin's UITest framework quite a bit, both for standard test automation as well as some other tasks (more on that to come). Things had been working great, but after some recent upgrades to the latest versions of Xcode and the iOS tools, we were seeing our automated tests get stuck in one specific spot in the app's flow. Nothing particularly interesting was happening in this spot: it was making a network call out to our API, which was working, but the app would never actually proceed with the response it got. This only happened during test runs, so it was a scenario only triggered by the app being started by UIAutomation.

Thanks to the help of Rasmus Kromann-Larsen and Karl Krukow, I was able to get to the bottom of what was going on. As it turns out, there seems to be a bug in UIAutomation itself related to large amounts of text being output to the console. For debug builds of our app we're outputting quite a bit of diagnostic info at times that's very useful during development but never ships in production builds, and that was making UIAutomation quite unhappy. Of all the things I'd considered as possible suspects when trying to troubleshoot this issue, the console output was nowhere near the top of my list.

This output isn't really important during test runs, so we decided to just suppress all console output for them. We already had some bootstrapping code to clear out data in the app to make sure all tests start from a clean slate, so we just needed to add a couple steps to that. First, we created a TextWriter implementation that just ignores everything sent to it:

class SuppressingWriter : TextWriter  
{
    public override Encoding Encoding { get { return Encoding.Unicode; } }
    public override void Write(string value) { }
    public override void Write(bool value) { }
    public override void WriteLine() { }
    public override void Write(int value) { }
    public override void Write(char value) { }
    public override void Write(char[] buffer) { }
    public override void Write(char[] buffer, int index, int count) { }
    public override void Write(decimal value) { }
    public override void Write(double value) { }
    public override void Write(float value) { }
    public override void Write(long value) { }
    public override void Write(object value) { }
    public override void Write(string format, object arg0) { }
    public override void Write(string format, object arg0, object arg1) { }
    public override void Write(string format, object arg0, object arg1, object arg2) { }
    public override void Write(string format, params object[] arg) { }
    public override void Write(uint value) { }
    public override void Write(ulong value) { }
}

Then we just needed to redirect console output to that writer, and remove all debug output listeners:

System.Diagnostics.Debug.Listeners.Clear();  
Console.SetOut(new SuppressingWriter());  

Problem solved! This is certainly a bigger hammer than necessary to solve the immediate problem in our apps, but it did the trick and our tests are green again.

December 08, 2014 7:27 GMT

Text To Speech Plugin for Xamarin and Windows

You may have noticed that I am on a big Plugins for Xamarin kick currently. I have always had my Settings Plugin that I have updated over time, but then I blogged about creating plugins for Xamarin.Forms, released a Vibrate Plugin, and then discussed exactly what a Plugin for Xamarin is. I love plugins as they can abstract away features common on platforms into a simple API so you never have to write the same code twice. Today, I am please to announce and release my latest plugin, text to speech.

I have seen Nick Landry's session on implementing Text to Speech with Cortana and how you can add this small feature to your applications to add some really unique functionality. The issue of course is that each platform handles Text to Speech completely different. I have create a very simple yet flexible API allowing you to add Text to Speech functionality to: Xamarin.iOS, Xamarin.Android, Windows Phone, and Windows Store.

GetInstalledLanguages

This was bonus perk really to add, which was the ability to gather all of the installed languages that are compatible with the Text To Speech engine on the platform. This allows you to manually set or allow your user to pick what language they want to speak back with. On Android this even takes advantage of the new Lollipop APIs!

Speak

My speak API allows you to simply pass in some text to speak back with all defaults, or really go to down and completely customize how the TTS engine plays back the sound. Here is what it looks like:

As you can see you have complete control over pitch, speak rate, locale, and even if you want to queue up the TTS engine or stop it completely. I am really proud to say that on Windows Phone/Store I use the complete Ssml engine to handle the advanced functionality, which is pretty slick.

Get It Today

The full source code is available today on GitHub along with full API documentation. Of course you can grab the NuGet as well and install it from Xamarin Studio or Visual Studio in a Xamarin or Xamarin.Forms project.
December 08, 2014 1:00 GMT

Xamarin Forms Maps Recipe

Adding maps and location to a Xamarin Forms mobile app couldn’t be easier. The developers and folks at Xamarin really out did themselves with the Xamarin Forms Map View. With the Xamarin Forms Maps Nuget package and a couple of lines of code, your app could have a fully functioning map with location integration.

Xamarin Forms Maps Nuget

Xamarin Forms Maps Nuget

Xamarin Forms Maps iOS

For your iOS 7 app, once you add the Xamarin Forms Maps package to your project and initialize, you’re ready to go. On iOS 8 your going to need to add a few entries to your info.plist. Just open up the file and view its source to add these two entries.

XamarinFormsMaps iOSQuestions

The text of these two strings will be used when interacting with the user while asking for permission to use the phones location. You should customize the string to match how and why your app is using the phones location.

Xamarin Forms Maps Android

For Android it is a little more complicated. To use maps on Android your application needs to be signed with a Google Maps API v2  key. I’ve done this for My GCU Maps app and it’s no big deal, just a hassel. Take a look at Xamarin’s instruction here to get your maps up and running in Android.

Besides the API key and signing the app package you’re going to need permissions. To get permission select the INTERNET and ACCESS_NETWORK_STATE permissions in the apps “Required Permission” list.

Location Location Location

To use maps in your application you’re going to need to geocode your locations. For my apps, I’ve been having success with using the GPS Visualizer. This site will help you geocode your locations into latitude and longitude. Most of these sites use Google on the backend to translate your addresses to GPS coordinates.

To The Code

To show you how easy it is to get this working here is all the code needed for maps in a Xamarin Forms iOS project.

MapPage

public class MapPage : ContentPage
{
  public MapPage ()
  {

    var span = MapSpan.FromCenterAndRadius (
                 new Position (33.44834, -112.0741), Distance.FromMiles (0.4));

    var map = new Xamarin.Forms.Maps.Map (span) {
      VerticalOptions = LayoutOptions.FillAndExpand
    };

    var stack = new StackLayout { 
      Spacing = 0, 
      Children = { map } 
    };

    Content = stack;
  }
}

 App Delegate

I have included the whole app delegate for your convenience. The only addition needed for maps was the Xamarin Forms Maps namespace and the FormsMaps init call. I’ve also added a call to the above MapPage as the root controller.

[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
	UIWindow window;

	public override bool FinishedLaunching (UIApplication app, NSDictionary options)
	{
		Forms.Init ();
		FormsMaps.Init ();

		window = new UIWindow (UIScreen.MainScreen.Bounds);
		
		window.RootViewController = new MapPage ().CreateViewController ();
		window.MakeKeyAndVisible ();
		
		return true;
	}
}

The Results

Here is what the above code does on the iOS simulator. It shows a map of my home city, Phoenix, AZ, about 1/2 mile above the center of the city. The default map style is called Street and the hybrid and Satellite versions are also available.

XamarinFormsMap iOSMap

 

Pin Action

The Xamarin Forms Maps view comes with a simple collection of Pins. You can add pins to the map buy adding a pin to this Pins collection. You create a Pin with the same Position type used in the MapSpan in the above example. Pins currently do not have an event raised when you tap them. Hopefully in the next release we’ll see this feature added.

The current version of Map in Xamarin Forms is impressive and I use it today. I’m looking forward to seeing what the folks at Xamarin do next. Give maps a try in your next Xamarin Forms app; I think you’ll enjoy the experience and so will your users.

 

The post Xamarin Forms Maps Recipe appeared first on Syntax is my UI.

December 08, 2014 12:53 GMT

Extending Xamarin Studio's mdtool For Fun and Profit

In Xamarin Studio, if you look in the About dialog you'll find all sorts of information about the versions for all the various tools involved in building your apps. There's so much more to compiling an app than the version of Xamarin you have installed. There's the version of OS X, Android tools, Xcode, etc. Any one of these things is a significant data point in any app release you have.

Every time we do a release at Olo I've been copying the output of that dialog and pasting it into a release in GitHub so we don't lose track of exactly what was in that release. We manage a ton of releases, so every data point matters. It's no secret that I'm big on automating this sort of thing, so I set out to see if I could do so for this task. Spoiler alert: I could.

Before I get into the details, I want to extend a big thank you to Michael Hutchinson, the guru of all things Xamarin Studio, for pointing me in the right direction which definitely saved me many hours of digging through the MonoDevelop source. After maybe five years of using MonoDevelop/Xamarin Studio, this was the first time I'd ever tried writing any sort of add-in and I am definitely impressed by how approachable the add-in system is.

To prove that, let's take a look at how little code it took to achieve what I wanted to do. If you're just getting started building add-ins for Xamarin Studio, I'd recommend starting with the guide on their site which is a great primer.

The first step was defining my add-ins manifest:

<?xml version="1.0" encoding="UTF-8"?>  
<ExtensionModel>  
    <Extension path="/MonoDevelop/Core/Applications">
        <Application id="systeminfo" class="Olo.BuildTools.SystemInfo" description="Gather info on tool and add-in versions"/>
    </Extension>
</ExtensionModel>  

There are many different options for extension paths, depending on what you want to achieve with your add-in. For this one, there's no actual UI to expose, so I used the /MonoDevelop/Core/Applications extension point to simply add a command to mdtool. If you're unfamiliar with mdtool, it's a command line tool included with Xamarin Studio that can be used to do various tasks from the command line, such as building iOS apps. I had no idea before writing this that it was so easy to extend this core tool.

With the manifest defined, all that's left is defining the class that it points to. The code there wasn't much more complicated:

using System;  
using System.IO;  
using System.Linq;  
using MonoDevelop.Core;

namespace Olo.BuildTools  
{
    class SystemInfo : IApplication
    {
        public int Run(string[] arguments)
        {
            var systemInformationSummary = SystemInformation.GetTextDescription();

            if (!arguments.Any())
                printHelp();

            foreach (var argument in arguments)
            {
                if (argument == "-c")
                    Console.WriteLine(systemInformationSummary);
                else if (argument == "-h")
                    printHelp();
                else if (argument.StartsWith("-f:"))
                    File.WriteAllText(argument.Substring(3), systemInformationSummary);
            }

            return 0;
        }

        private void printHelp()
        {
            Console.WriteLine();
            Console.WriteLine("System Info Tool");
            Console.WriteLine("Usage: mdtool systeminfo [-c] [-f:file-path]");
            Console.WriteLine();

            Console.WriteLine("Options");
            Console.WriteLine("  -h                Print this message");
            Console.WriteLine("  -c                Output system information to the console");
            Console.WriteLine("  -f:file-path      Output system information into the specifed file");
            Console.WriteLine();
        }
    }
}

To be honest, the "hard" work here was mostly just spending some time getting to know the source to MonoDevelop a little better, and coming across the SystemInformation class, which is what gets used in the dialog in Xamarin Studio. The code above essentially just reproduces what happens there, and redirects it to either a file or the console.

That's it! Once that add-in is loaded into Xamarin Studio, you can go to the command line and do:

mdtool systeminfo -c  

and you'll get the same output you see in the About dialog. If you want to pipe the output to a file, as we do in our build process, you can do:

mdtool systeminfo -f:versions.txt  

We then take that file and publish it as a build artifact in TeamCity, alongside the actual app package.

In addition to this post, we've created an open source repository on our GitHub account where we intend to put more add-ins as we come up with them. You can also find this add-in from any Xamarin Studio install by searching for Olo.BuildTools.

Xamarin Studio Add-In

December 08, 2014 12:10 GMT

Polyglot Apps for iOS, Android and Beyond

It's well known by now that you can use C# to write apps for iOS and Android by leveraging Xamarin tools, especially if you've been following this column. It's also well documented that you can take a lot of that C# over to other platforms such as Windows Phone and Windows Store, but did you know you can use F#, Visual Basic, Razor, HTML, and JavaScript in your apps, as well?

View the full post over at Visual Studio Magazine

December 06, 2014 6:39 GMT

What Exactly is a Plugin for Xamarin?

I am so glad that you asked! I recently blogged about creating reusable plugins for Xamarin.Forms, and it might have caught you a bit off guard. Does Xamarin.Forms or Xamarin itself have plugins? The short answer is YES with the power of PCLs and NuGet.

Component vs. Plugin

For a long time, Xamarin developers have been able to add rich functionality to their mobile applications by adding Components from the Component Store. While you might consider these “plugins” of sorts, let me define what a plugin means to me.



Component
When refer to Components, we’re generally talking about a library for Xamarin.iOS or Xamarin.Android that has been packaged for the Xamarin Component Store - similar to how a NuGet is a Library that has been packaged for the NuGet Gallery. Sometimes they have the same API, however sometimes they do not. For instance, Twilio has a great component that has very specific and tight integration with iOS and Android, and requires you to write code in the platform specific project.

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

I like to use the name Plugin as it follows the same pattern as MVVMCross. In fact, nearly every single MVVMCross Plugin could be turned into a Plugin for Xamarin & Windows with a small amount of work so any Xamarin developer could take advantage of it.

I created my Vibrate and Settings Plugins specifically to provide simple examples of Plugins for Xamarin & Windows - but another great source for model plugins would be nearly anything that comes from Paul Betts, such as Akavache.

Xamarin.Forms or Xamarin plugin?


If you read my earlier blog post about creating plugins specifically for Xamarin.Forms, you might be wondering if you should create them for only Xamarin.Forms or if you should create a more platform independent Xamarin plugin. This is a great question as well and just remember that any “Xamarin plugin” would work in a Xamarin.Forms project. So, it really only depends on what you are trying to accomplish. If you intend to leverage some of the functionality that is built into Xamarin.Forms, or to create custom controls for Xamarin.Forms, then your plugin should be a “Plugin for Xamarin.Forms”.

If you are not using anything that explicitly depends on Xamarin.Forms, then you should really strive to make it completely platform independent, and leverage the Bait & Switch approach to target iOS, Android, and Windows Platforms. I tend to always attempt to target iOS, Android, and Windows Phone at minimum in all of my plugins to ensure compatibility with Xamarin.Forms.

Naming


After taking a few swings at this, I’ve found that following this naming scheme works pretty well:

Xamarin.Forms only:
Feature Plugin for Xamarin.Forms

Xamarin.iOS/Android/Mac:
Feature Plugin for Xamarin

Xamarin + Windows Platforms:
Feature Plugin for Xamarin and Windows

Replacing “Feature” with what your plugin does :)

If you want to learn more about creating plugins, be sure to check out my full repo on GitHub.
December 06, 2014 8:16 GMT

Using an ObservableCollection in Xamarin Forms Labs

Xamarin.Forms is an excellent solution for data-driven apps, and I'm willing to bet a Xamarin monkey that ListView is one, if not the most, widely used control in XF apps. If the data displayed in a ListView might change at runtime, it is appropriate to use an ObservableCollection as the ListView's ItemSource. ObservableCollection implements the INotifyCollectionChanged interface that is wired up to the ListView's CollectionChanged event. I will demonstrate the use of an ObservableCollection in a sample XF app that uses Xamarin Forms Labs. I'm using XF v1.3.0.6275-pre1 and XF.Labs v1.2.1-pre2.

Dependency Injection

DI setup is necessary for ViewFactory which is described in the next section. XF.Labs comes with a built-in DI container called SimpleContainer. You can also choose to use a 3rd-party container such as TinyIOC or Ninject. In any case, we will need to wire it up in each of our platform-specific projects.

Let's kick things off by changing the AppDelegate class, so it inherits from an XF.Labs-provided UIApplicationDelegate:

public partial class AppDelegate : XFormsApplicationDelegate

On the Android side of things, the change is similar:

public class MainActivity : XFormsApplicationDroid

Then, in the FinishedLaunching method on iOS and in the OnCreate method on Android, let's call the following:

private void IoC() 
{
    var resolverContainer = new SimpleContainer();
    resolverContainer.Register<IDependencyContainer>(t => resolverContainer);
    Resolver.SetResolver(resolverContainer.GetResolver());
}

ViewFactory

This is unrelated to the use of ObservableCollections, but it is a nice feature that is baked in XF.Labs that does simplify certain things. ViewFactory allows you to register Views to particular ViewModels. You can then call navigation (see the INavigation interface) methods inside ViewModels instead of Views. For example, assuming that FooView is registered to FooViewModel, calling Navigation.PushAsync<FooViewModel> will push FooView on the stack and also set its BindingContext to FooViewModel. Neat!

Let's modify the GetMainPage method in App.cs as following:

        ViewFactory.Register<FooView, FooViewModel>();
        return ViewFactory.CreatePage<FooViewModel>();

Model

We will be showing a collection of FooModels in our ListView.

public class FooModel
{
    public string MonkeyName { get; set; }
}

View

We need to make sure our ViewModel class inherits from BaseView. BaseView binds the Navigation property that you can use in your ViewModels.

public class FooView : BaseView

Let's add a private property to have a reference to the ViewModel from the View:

    private FooViewModel ViewModel
    {
        get { return BindingContext as FooViewModel; }
    }

In the constructor, add the following code:

var list = new ListView();
// Names is the ObservableCollection of FooModels in the ViewModel
list.SetBinding(ListView.ItemsSourceProperty, new Binding("Names"));

var cell = new DataTemplate(typeof(TextCell));
// We are showing the FooModels' MonkeyName property
cell.SetBinding(TextCell.TextProperty, "MonkeyName");

list.ItemTemplate = cell;

Content = new StackLayout { Children = { list }};

We will populate the ListView using the Command pattern. Add the following method override to the class:

    protected override void OnAppearing() {
        base.OnAppearing();

        if (ViewModel == null)
            return;

        ViewModel.LoadItemsCommand.Execute(null);
    }

Notice that we did not have to set the BindingContext property. Thanks ViewFactory!

ViewModel

As with the View, we need to make sure our class inherits
from a base class, in this case, ViewModel.

public class FooViewModel : ViewModel

Let's add our ObservableCollection and instantiate it in the constructor:

    private ObservableCollection<FooModel> names;
    public ObservableCollection<FooModel> Names 
    { 
        get {
            return names;

        }
        set {
            // Change the property if it's different and raise the PropertyChanged event
            // This is necessary if the items' properties change at runtime
            this.SetProperty(ref names, value);
        }
    }

    public FooViewModel() {
        Names = new ObservableCollection<FooModel>();
    }

We also need to determine what LoadItemsCommand command will do. The data would probably come from a database or a web service.

    private Command _loadItemsCommand;
    public Command LoadItemsCommand
    {
        get { return _loadItemsCommand ?? (_loadItemsCommand = new Command(ExecuteLoadItemsCommand)); }
    }

    private void ExecuteLoadItemsCommand()
    {
        Names.Add(new FooModel { Name = "Bob" });
        Names.Add(new FooModel { Name = "Jane" });
        Names.Add(new FooModel { Name = "Ivan" });
    }

That's it! Here are the results:

You can grab the complete project on GitHub.

December 05, 2014 5:44 GMT

Creating Reusable Plugins for Xamarin.Forms

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

The Idea

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

The Interface

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

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

Creating New PCL

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

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

Platform Libraries

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

FullSolutionSetup

Android Implementation

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

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

iOS Implementation

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

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

Windows Phone Implementation

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

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

Pulling Everything Together

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

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

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

public static void Init() { }

Create the NuGet and Test

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

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

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

NuGetPackageManager

Distributing

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

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

December 05, 2014 4:32 GMT

Xamarin.Forms – Groups and Jump Lists

My goal is to create a simple list of Employees with the employees grouped byJump Lists the first letter of their name.  I’d also like to create a jump list to allow the user to jump to a particular letter in the list.

To see the implementation, click here

December 04, 2014 3:43 GMT

Building an Estimote Scavenger Hunt on iOS, Android, and Windows in C# with Xamarin

estimote:

This is a guest post by James Montemagno, Developer Evangelist at Xamarin.

It seems like there’s another tech conference somewhere every week. Putting together a world class event is extremely challenging, but creating a unique digital experience for your attendees can be even more of a hurdle. First step is choosing the right tools. With the Xamarin Platform, you are able to create native iOS, Android, and Windows applications all from a shared C# code base. At this year’s Xamarin Evolve 2014 conference, I thought there would be no better way to showcase the platform, and make sure attendees have fun at the same time, than to create a scavenger hunt mobile app: The Evolve Quest. It’s based on iBeacon technology and uses over 50 Estimote Beacons placed throughout the conference venue to create a game for attendees to complete during the conference.

image

Read More

December 02, 2014 12:00 GMT

Open Source Oslo M

For those of you on the cutting edge of Microsoft technologies that don’t ship ;), you probably have fond memories of one particular product that had so much promise: Olso “M”.

Just to refresh your mind on how cool it was, just go and read Fowler’s or Clarks’s cool reviews of Oslo.

The product didn’t go anywhere, with Microsoft investing heavily on OData and the Entity Data Model instead (or EDM, the metadata format behind Entity Framework).

Oslo as a whole, owned by the SQL Server group, ended up being a gigantic thing too tied to the database for its repository, and with a grand vision that was very hard to sell. That’s why OData and EDM won, in a way: they aren’t SQL Server-specific.

But “M”, separated from the rest of the SQL/RDBMS tie-ins, was a great thing in its own right, for building textual DSLs, even with nice almost automatic tooling for Visual Studio. Think keeping just the top box:

Oslo

Who does modeling anyway?

Well, if you have any sort of configuration for whatever library of framework, and you provide a serialized format for that configuration in some form, you’re modeling ;). “Back in the day”, people were making up textual DSLs in XML. Editing was so-so (if you could provide an XSD), validation was so-so (unless you needed anything beyond basic structural validation via XSD), but at least XSD gave you something beyond plain text. There never was a true logical model, unless you just did straight XmlSerializer stuff to your POCOs and called that your model. Very rudimentary. A lot of developers didn’t even bother with that and just went straight XmlDocument/XDocument.

If you were mindful about extensibility, you could even allow extensions to your model via XML namespaces and let others take your model further. But even fewer devs went so far.

Now JSON is all the rage, and you see ASP.NET vNext (K) doing this all over again, as a single-purpose-thing again but on top of Json: little DSLs with hardcoded editing knowledge of (some) JSON schemas, and some hardcoded IDE integration, and again, no logical model unless you do it yourself. (but you can always use it as just a persistence/configuration thing and even read it untyped with Json.NET’s JObjects).

Not moving forward!

We’re never moving forward! We’re never moving up to truly executable models, models that can be integrated, reasoned about, extended, etc. JSON-based DSLs are even worse than XML-based ones in that regard, since at least XML had extensibility built-in via namespaces!

This makes me very sad. We were on the verge of a revolution in modeling and abstractions and executable models with “M”, and now we’re back to an even pre-XML/Infoset world with even more hardcoded one-off tooling.

At Xamarin, for example, we have to deal with Android’s application manifest (XML) and Apple’s unbelievably ugly PList “XML” files, with no hope of having anything more expressive, unless we invest a lot in custom tooling and come up with yet-another-DSL that we’ll have to maintain.

Granted, every possible usage of a textual DSL will be met with questions as to why isn’t JSON/XML enough, since parsing is so trivial, etc. And granted, you also face the usual “you can do that with some custom tooling!” (which we know and do anyway). But that’s not the point. Of course we can make custom textual DSLs, we’ve been doing it for way too long already! And every time using the wrong tool for the job: XML in the past, JSON in the present.

Imagine how amazing it would have been if the new configuration system in ASP.NET vNext with all that Gulp, Grunt, Bower and npm was based on Oslo instead of being one-off tooling endeavors by the awesome but very unique Mads Krinstensen. The mere mortal developers can only dream of putting together that kind of tooling for their own projects.

Open Sourcing Oslo “M”

A general-purpose modeling tool like M has wide applicability, and I’m sure devs would apply it to things we never even thought about. And that’s the whole point :).

I sincerely hope that Microsoft considers contributing this part of Oslo to the .NET Foundation. Even dumping the whole thing in GitHub would probably spark some interesting experiments.

December 01, 2014 7:31 GMT

Getting Started with Xamarin and IBM Worklight

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

Xamarin-IBM

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

Adding IBM MobileFirst SDK to your project

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

Xamarin-IBM-Add-Component

Adding Worklight Add-In to Xamarin Studio

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

Xamarin-Studio-IBM-Worklight-Addin

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

Xamarin-Studio-IBM-Worklight-Addin-Preferences

Running IBM Worklight Server locally

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

Xamarin-Studio-IBM-Worklight-StartServer

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

Configuring the Xamarin.iOS and Xamarin.Android projects

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

Android

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

iOS

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

Code

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

Initializing IWorklightClient on Xamarin.Android

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

Initializing IWorklightClient on Xamarin.iOS

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

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

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

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

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

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

Register Now


Discuss this blog post in the Xamarin Forums

November 29, 2014 11:00 GMT

Postcards from Pripyat

Int 2011, a friend organised a trip to Pripyat, which is the town which was evaculated during the Chernobyl disaster.

It was a surreal, eye opening and wonderful trip for many different reasons. I blogged about it here and Leonie has her view here.

British documentary maker Danny Cooke has just released a video "Postcards from Pripyat", which is the first time area has been filmed from the air. It's stunning, and really captures the place.

HT: The Guardian

November 27, 2014 12:08 GMT

Make a CocosSharp Game for the Amazon Fire TV Stick

I just got a new FireTV stick, which I purchased for the $19 Amazon Prime offer. Amazon has done some fantastic work in creating this device. Even at the $39 price it is a great buy imho :)

Amazon Fire TV Stick

The first thing I wanted to try out was getting CocosSharp running on it. It turns out this was very easy thanks to the work that has gone into MonoGame plus CocosSharp, along with the Amazon Fire TV SDK Xamarin component that we released when the Fire TV came out.

The first thing I did to get up and running was deploy a hello world Xamarin.Android app. This was trivial following the instructions on the Xamarin component page. The button click event automatically mapped to the remote so all looked good. Amazon mapped the remote to key events, so you can do normal Android key processing in an activity to get input from the remote control. This makes it super easy.

More info on the working with the remote is available in the Amazon docs.

Moving over to CocosSharp, I decided to attempt running a simple game I had made earlier in the week for a Xamarin University lecture. Without any changes, the game deployed and ran just fine! However, it was written to handle touch, so I needed to add code to handle input from the remote.

First I tried adding a CCEventListenerKeyboard to handle it from shared code under CocosSharp, but as it turns out this didn’t work. Next attempt, I tried adding key handling in the AndroidGameActivity, which I knew worked from the earlier HelloWorld app I had tried. Interestingly, in a plain Activity it worked OK, but when using AndroidGameActivity, it didn’t. It seems there’s some special input handling under MonoGame for the Fire TV. I’m not sure if that’s related or not to what I ran into here. I’ll blog about that in the future if I learn more.

Moving right along, the next thing I tried was going straight at MonoGame input via the Keyboard class. Eureka, this worked fine.

All I needed to do was call Keyboard.GetState, followed by IsKeyDown to determine which key is being pressed. For this game, I move the ship up and down vertically, so all I needed to inspect were the up and down keys:

var state = Keyboard.GetState ();

var up = state.IsKeyDown (Keys.Up);

var down = state.IsKeyDown (Keys.Down);

Then I simply used actions to move the ship up and down appropriately. I could have done it with manual positioning in the game loop, but I like how easy it is to use actions. Plus, this makes adding timing functions a snap since they are available as actions as well. In this case I used CCEaseSineInOut.

Aside, if you want to learn more about timing functions and animation check out Jérémie Laval’s talk from Evolve 2014.

With this code to handle the remote control input in place I deployed the app via Xamarin Studio and voilà, I could control the ship via the remote.

The next thing I noticed however was the custom particle systems I add for explosion effects seemed to cause performance to degrade. It wasn’t too bad, but I could notice it.

It turns out I was not being efficient with how I handled these particle systems. I was recreating a new system for each explosion (as the code below does), which required parsing the plist each time, among other things:

var explosion = new CCParticleSystemQuad ("implode.plist");

explosion.Position = pt;

AddChild (explosion);


To resolve this, I pre-created the system once and reused it as shown below:

void InitExplosionParticles ()

{
  
  explosion = new CCParticleSystemQuad ("implode.plist");
 
  explosion.AutoRemoveOnFinish = false;
  
  explosion.StopSystem ();
  
  explosion.Visible = false;
  
  AddChild (explosion);
}

Then every time I created an explosion effect I set it as visible, moved it to the new location, and reset the system:

explosion.Visible = true;
explosion.Position = pt;
explosion.ResetSystem ();


With that change in place, the game ran smoothly.

Here’s a video of the game running on my Fire TV stick:




The code for the game is available in my GitHub repo.

There’s more to the Fire TV stick. The sdk supports, among other things, game controllers, which I’m going to pick up over the holiday and try out next, if I don’t get tackled by some angry shoppers. Hmm, angry shoppers, maybe there’s a game concept in that ;)


November 26, 2014 11:00 GMT

Holiday Meetups and Events with Xamarin

It’s Holiday season again and with the New Year right around the corner, you won’t want to miss any of the Year End events happening with Xamarin! Stay in tune by following @XamarinEvents posts on Twitter and be sure to check out our Events forum with new events being added daily from all around the world!

meetup-banner

Here are some upcoming Xamarin developer group meetups:

XHackers Kerala us

  • Kerala, India: Saturday, Nov 29th 2:00PM
  • Recap of Xamarin Evolve and Introduction to Xamarin

Melbourne Xamarin Meetup us

  • Melbourne, Australia: December 1st/8th/12th/22nd 5:00pm – 7:00pm
  • Weekly Xamarin Coding Session

Seattle Mobile .NET Developers Group us

  • Seattle, Washington: Tuesday, December 2nd 6:00pm – 8:30pm
  • Seattle Mobile .NET 1 Year Anniversary!

Queensland C# Mobile Developers (iOS/Android/Windows) us

  • Brisbane, Australia: Thursday, December 4th 5:00pm
  • Brisbane Tech Christmas Drinks

DFW Mobile .NET us

  • Irving, Texas: Wednesday, December 10th 6:00pm
  • Tour of Xamarin with Xamarin and Microsoft MVP Brent Schooley

Space Coast .Net User Group us

  • Melbourne, Florida: Wednesday, December 10th 6:30pm
  • Redis – Caching for .NET Developers

Copenhagen Xamarin Developers us

  • Copenhagen, Denmark: Wednesday, December 10th 5:00pm
  • First CPH Xamarin Developers Meetup

NYC Mobile .NET Developers Group us

  • New York, New York: Tuesday, December 16th 6:45pm
  • Couchbase Mobile: Introduction and Hands-On Workshop with Xamarin

Windows Apps London us

  • London, England: Wednesday, December 17th 6:30pm
  • Xamarin Re-Evolved and porting from Windows Phone – With Dominique Louis and Michael James from Xamarin

XL Soft us

  • Tokyo, Japan [日本]: Thursday, December 18th 2:00pm – 6:00pm
  • Introduction to Mobile Development (workshop will be held in Japanese)

Didn’t see your city listed above? Not to worry, look to this December Announcements forum for MORE upcoming Xamarin events, meetups, and presentations happening every day!

Don’t see a developer group in your area and you are interested in getting one started? We are here to help! Here’s a tips and tricks guide on staring a developer group, a brand new introduction to Xamarin slide deck, and of course our community sponsorship program to get you on your way. Also, we’d love to hear from you so please feel free to send us an email or tweet @XamarinHQ to help spread the word and continue to grow the Xamarin community.

November 26, 2014 7:16 GMT

Open Source Xamarin.Forms Demo App: VervetaCRM

upload (1)I love Xamarin.Forms.  It’s one of the core features released in Xamarin 3, giving you the ability to build beautiful, native UIs for iOS, Android, and Windows Phone from a single shared C# codebase.  To show Xamarin.Forms in action, we created a cloud-connected, fully functioning CRM app for iOS, Android and Windows Phone to demonstrate the power of Xamarin.Forms.  Today, we’re making the source code available to you.

VervetaCRM is a mobile CRM app for salespeople at a fictional office-supply company (named after the vervet monkey).  The app lets mobile salespeople track their sales performance, see their contacts, view customer location maps, and capture orders with user signatures.  Even with these complex, cross-platform requirements, we were able to get over 90% code re-use. Watch this short video in full-screen to dive into the code and see VervetaCRM working on iOS, Android and Windows Phone.

To fulfill enterprise requirements and add complex features, it relies on several components and libraries:

Azure Mobile Services: this app uses Azure Mobile Services (AMS) as the cloud backend for authentication and data.  It integrates with Azure Active Directory to create a consistent sign-on experience for mobile users.  The AMS component simplifies the implementation and uses oAuth to both authenticate a user and provide a token.

Data is synchronized with an Azure SQL cloud database and a SQLite database that runs on the device – providing fast, offline data access and a consistent data access API.

OxyPlot: this is an outstanding, open-source .NET-based plotting and charting library that shows sales performance with basic graphs.

Signature Pad: available from the Xamarin Component Store to capture and display user signatures.  This component highlights Xamarin.Forms extensibility; using custom renderers, it was easy to consume the platform-specific signature pad components into the Xamarin.Forms shared UI code.

Download the Code

The code is available for download on GitHub at https://github.com/xamarin/vervetacrm.

Learn More

Here are some additional links to help get you started with Xamarin.Forms apps:

Happy Thanksgiving!

November 26, 2014 6:56 GMT

Using Mocks to test Xamarin

Many of us believe that Unit Testing is critical in any non-trivial programming.  But Unit Testing can be difficult, especially the use of fakes.  The most common fake is a Mock; unfortunately they are also the most confusing.

There are a number of Unit Testing libraries you might use with Xamarin, but the easiest to integrate is nUnit.  For mocking, Moq makes great sense, especially as it works so well with nUnit.  Continued here…

November 25, 2014 4:35 GMT

Two Hot New Features for Calca

See Calca 1.3 on the Mac App Store

Calca 1.3 has hit the Mac App Store and it contains two features that I hope you’ll love: plotting and quick entry.

Plotting

When Calca was first released, I was asked a great question by Jason Brennan:

Do you think plotting is an essential function missing (most of) today’s “calculators”?

My answer was an unequivocal “YES!” followed by a lament for having cut it from v1.0 (#irony). A year passed and plotting became the #1 voted feature for Calca.

Well plotting has finally arrived! You can now create as many plots as you want, each with multiple series. To do it, just pass a function to the plot function. For example, I can plot a sine wave at 5 Hz with:

plot(sin(5t * 2pi))

Passing multiple arguments generates multiple series:

plot(sin(5t * 2pi), cos(5t * 2pi))

You can also plot data!

plot([-1, pi, 0, 2])

The plots are displayed in the right margin of the application and support mouse tracing, zooming, panning, and even export as CSV or SVG.

All plots are displayed as 2D line graphs and are drawn using Calca’s standard colors. The area under the curve - the integral - is always displayed as it gives quick visual indication of whether your data is positive or negative. Also, I think it looks pretty.

When you run Calca, go to Help and choose Plots for more details and examples.

More formatting options and more plot types will be added in the future, but I couldn’t let this feature go unreleased any longer. I’m looking for your feedback! Now that we have plotting, I want to know what kind of plots you make so Calca can help you better in the future.

Quick Entry

Calca is certainly a powerful “math document” editor, but sometimes you just want to do some quick math.

I often find myself in another app needing to do some quick calculations. Of course I could switch over to Calca, create a new document, do my work and switch back to that app. These aren’t hard steps, but they wear on the soul.

The truth is, I found myself falling back to Spotlight for these quick computations - you can’t argue with efficiency! But I missed Calca, I missed its symbolic nature, its units, its functions.

No More! Calca now has a UI mode that is very similar to Spotlight’s. When Calca is running, simply hit the global keyboard shortcut ⇧⌘C (of course you can change this) and you will be greeted with a little centered window all ready for you. Just start typing and Calca will happily perform your calculations and display the last one in the bottom half of the window. It makes computations in other apps fast and easy.

This has changed everything for me and is, honestly, my primary way of interacting with Calca now. I almost always start my work in the quick entry window and quite often just stay there. Only when the window gets to be too unwieldy do I hit ⌘N to start working on a new document with that math. It’s a great workflow that I hope you’ll love.

One More Thing

There has been this terribly annoying bug in Calca that resulted in text jumping around when editing long documents. That bug is dead now. Squashed. Eradicated. It will plague us no more.

What about iOS and Windows?

They’re coming!

November 24, 2014 12:00 GMT

Xamarin Weekly Newsletter Progress Report – November 2014

Four months ago, around the beginning of August 2014, I was frustrated in keeping up with all things Xamarin. I was subscribed to the monthly newsletter, Xamarin Inc. blogs, and Twitter feeds of all things Xamarin. Thinking I was missing things, I started a Feedly of every blog I could find as well as setting up some Google Alerts.

With my RSS reader and my minions (Google alerts), I had a finger on the Xamarin pulse, or as much as any non-employee could. One thing bothered me about my setup, it was only for me. How many other developers had to do the same thing?  I wished someone would start a weekly newsletter like HTML5 Weekly or JavaScript Weekly.

HTML5 Weekly and JavaScript Weekly from Cooper Press are a great way to stay informed. These newsletters are a curated set of links to articles, blog post, videos and podcasts produced in the last week. Keeping up to date on these topics is so much easier, just subscribe and the information comes to you.

Starting the Xamarin Weekly Newsletter

I didn’t think I could get Peter from Cooper Press interested in Xamarin, so I decided to do it myself. Starting a weekly newsletter or any newsletter is not a decision to be made lightly. Being a full time cross-platform mobile developer I knew the time I put into the newsletter would benefit myself and the Xamarin community. After a couple of months and 15 newsletters later, I know I made the right decision.

Transferable

One of the key aspects of XamarinWeekly.com is how the whole thing is transferable. I’m the current scribe or writer of Xamarin Weekly and will be for the foreseeable future but I may not be the last. I want Xamarin Weekly to be around for as long as Xamarin Inc. is around. All the services and emails used in Xamarin Weekly are not commingled with my personal or professional life. With a few updates, someone else would be able to pickup where I left off.

Costs

Setting up the domain, website, Google Apps (email, sites), Twitter, Facebook and MailChimp was pretty easy. The cost of services and registration fees are pretty reasonable at around $100 a year. MailChimp is free for email lists with under 10,000 emails a month. Xamarin would need around 2,500 subscribers to break out of the free tier. Wouldn’t that be a great problem to have?

Report

Ok, enough of the backstory, let’s get to the progress report. Xamarin Weekly has had 15 newsletters delivered to over 320 subscribers. The website www.XamarinWeekly.com has seen 933 unique users.

Subscribers and Growth

Xamarin Weekly Growth

The newsletter growth has been steady and growing linearly. We average 120 new subscribers every 30 days. With the year end and holidays I do suspect that number to dip. It will be interesting to see subscriber rates in the New Year. I have no doubt more businesses are going to start looking to Xamarin for cross platform mobile development.

Newsletter Performance

Xamarin Weekly Performance

Xamarin Weekly newsletter performance is well above the industry average. Opens are around 68% and click rates are 35%. The larger the subscriber base the lower the opens and click rates will be. It’s not all roses, we did have one person unsubscribe from the list. I knew it was going to happen, but was a little sad to see it happen so soon.

Hot Topics

Without a doubt, Xamarin Forms is the number one topic newsletter readers are interested in. Xamarin Forms links are consistently the most clicked on links for each newsletter. So, if you want more traffic, start writing about Xamarin Forms. In the future, you will see this blog cover Xamarin Forms more closely.

The Next 15

I couldn’t be happier with the start of Xamarin Weekly. Interacting and serving the Xamarin community has been a very fulfilling experience. If you have a blog, or are thinking about starting one, please email me so that I can get it on the Xamarin Weekly newsletter. Here’s to the next 15 newsletters and hopefully, with your help, a bunch more.

 

The post Xamarin Weekly Newsletter Progress Report – November 2014 appeared first on Syntax is my UI.

November 24, 2014 1:34 GMT

Android Material Image Loading

Among the plethora of seemingly impossible things in the Material Design specification, there is one that piqued my curiosity this morning.

It’s something everybody does at least once, if not everywhere, in his app which is loading and transitioning images.

Now to make this more glamour we generally all went with the classical, battle-tested approach of shifting the opacity of our image container to announce the change (that was even one of my first Android tip).

But the new approach taken by Material and detailed in the “Loading Images” section goes a lot further than this by also throwing some image levels manipulation in the mix.

The process is summarized in the following graph:

It outlines a 3-steps process where a combination of opacity, contrast/luminosity and saturation is used in concert to help salvage our poor users eyesight.

Android has always supported image manipulation through the ColorFilter class that can be set on any drawable and on some view classes (ImageView for instance).

When used with its 4x5 ColorMatrix-based implementation ColorMatrixColorFilter, you can virtually implement any kind of image transformation provided you grok the way vector/matrix multiplication work (head to the ColorMatrix documentation for the resulting equations).

The only thing that was a limiting factor is that a filter is initialized once and for all. If you want to change the effect you need to create a new instance of the filter (which initialize a native counterpart) and replace the old version with the new one.

Obviously this is a complete downer when you do animations because you don’t want to stress out the GC and GPU during those phases by creating a new instance of the filter at every refresh step.

But thanks to Lollipop and the fact that @hide can’t stop us, there is actually a new public method allowing us to update a filter after the fact.

Armed with this knowledge, we can now set out to create a custom ITypeEvaluator to tweak our filter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Refer to http://developer.android.com/reference/android/graphics/ColorMatrix.html
// for a list of the matrix indexes
class AlphaSatColorMatrixEvaluator : Java.Lang.Object, ITypeEvaluator
{
	ColorMatrix colorMatrix = new ColorMatrix ();
	float[] elements = new float[20];

	public ColorMatrix ColorMatrix {
		get { return colorMatrix; }
	}

	public Java.Lang.Object Evaluate (float fraction, Java.Lang.Object startValue, Java.Lang.Object endValue)
	{
		// There are 3 phases so we multiply fraction by that amount
		var phase = fraction * 3;

		// Compute the alpha change over period [0, 2]
		var alpha = Math.Min (phase, 2f) / 2f;
		elements [19] = (float)Math.Round (alpha * 255);

		// We substract to make the picture look darker, it will automatically clamp
		// This is spread over period [0, 2.5]
		const int MaxBlacker = 100;
		var blackening = (float)Math.Round ((1 - Math.Min (phase, 2.5f) / 2.5f) * MaxBlacker);
		elements [4] = elements [9] = elements [14] = -blackening;

		// Finally we desaturate over [0, 3], taken from ColorMatrix.SetSaturation
		float invSat = 1 - Math.Max (0.2f, fraction);
		float R = 0.213f * invSat;
		float G = 0.715f * invSat;
		float B = 0.072f * invSat;

		elements[0] = R + fraction; elements[1] = G;            elements[2] = B;
		elements[5] = R;            elements[6] = G + fraction; elements[7] = B;
		elements[10] = R;           elements[11] = G;           elements[12] = B + fraction;

		colorMatrix.Set (elements);
		return colorMatrix;
	}
}

Here is how you can set it up:

1
2
3
4
5
6
7
8
9
10
11
12
var imageView = FindViewById<ImageView> (Resource.Id.image);
var drawable = (BitmapDrawable)Resources.GetDrawable (Resource.Drawable.monkey);
var evaluator = new AlphaSatColorMatrixEvaluator ();
var filter = new ColorMatrixColorFilter (evaluator.ColorMatrix);
drawable.SetColorFilter (filter);

var animator = ObjectAnimator.OfObject (filter, "colorMatrix", evaluator,
                                        evaluator.ColorMatrix,
                                        evaluator.ColorMatrix);
animator.Update += (sender, e) => drawable.SetColorFilter (filter);
animator.SetDuration (2500);
animator.Start ();

And here is the result:

It’s probably safe to assume Google will come out with an official way for this pattern e.g. in a subsequent support library update. In the meantime, you can get cracking with this version.