Sunday, August 3, 2014

[Video] Introduction to iBeacons with Xamarin

Recently I attended a 'Xamarin Hack Day' organised by Michael Ridland & SSW here in Sydney. It was a great day which started with a few presentations, and led into everyone sitting down and coding away on Xamarin applications.

SSW are taking the concept around the world, so if you're interested in learning more about Xamarin you should check out XamarinHackDay.com

In the morning I gave a presentation on iBeacons and how to use them with Xamarin. I've got a keen interest in beacons and think there are big opportunities for developers that create applications which leverage them. I've spent some time trying out different beacon brands and trying out the iOS and third party Android SDK's. I've also been involved in discussing potential use cases to customers of Envoy as part of our iBeacon software development offering.

SSW recorded and edited the video, and have put it online here on their SSW TV website.

For convenience, here is the youtube video embedded:


And here are the slides:

Saturday, March 29, 2014

Thoughts on Xamarin for iOS development

Recently I had the opportunity to develop an iPad/iPhone application using Xamarin iOS. For those of you that don't know Xamarin are a company that develop cross-platform implementations of the .NET framework. Their two main mobile product are Xamarin.iOS and Xamarin.Android, which are wrappers around the native iOS and Android SDK's. This allows you to write C# code that is compiled into native mobile apps.



The good thing about this is that it allows you to write applications that have a shared 'core' library of platform agnostic code (for instance connections to web services, in-app database, business logic) while the user interface is written individually for each platform, providing an a good user experience while allowing for some code-sharing. This is in contrast to writing the app twice, in either Java for Android, or Objective C for iOS, and also differs from fully cross-platform solutions like PhoneGap, which requires some compromise in terms of the user interface. I often say the benefit of Xamarin is you write your  app 1.5 times instead of 2, while maintaining an optimal user experience.


The project I was tasked with was to create a mobile inspection app for building certifiers which was to replace a JQuery mobile website. The goals of the replacement app were to improve the offline support, which was subject to some limitation in HTML5 offline storage API's on iOS devices, to improve the user interface and to add some extra features like the ability to take photos of defects. Given these requirements, and especially that we really wanted to give a top quality experience for the user, I decided that a native app was the best way to go (note that I'm referring to Xamarin as native apps, which isn't technically correct however the terms native, hybrid and cross-platform are often mixed around. I consider hybrid to be a combination of native UI elements and webviews, others consider Xamarin to be hybrid).

Having decided on a 'native' app, it came down to writing it with XCode and Objective-C, or giving Xamarin a go. Envoy (the company I work for) specialise in .NET development, which is one factor, however I'm a believer in choosing the best tool for the job, and that learning new languages/technologies isn't something to be afraid of. In the end I went with Xamarin because it allows code sharing with a possible future Android version of the app, and because the core library could be built out faster in C#.



The app was finished in around 7 developer-weeks (including back-end work), and is live on the app store. After completing the app, and having worked on Objective-C iOS projects previously, I thought I'd share some of my observations on the current state of Xamarin.

The Good

Xamarin is a high quality product

One concern I had was that if Xamarin goes broke the code we produce is probably useless as the framework and tooling won't get updated for new iOS updates, however they are well funded and have been around for quite a while now in various forms, and just keep getting bigger and bigger. Updates are pushed frequently, documentation is well written and kept up to date, and they even put on a yearly conference that has some great presentations. They also have a partnership with Microsoft, and there's all sorts of rumours about Microsoft possibly buying them.

Our app ended up performing well and I didn't feel my development time was held back by the Xamarin product at all.

C# and Xamarin Studio fit in well with Cocoa Touch

I don't think Objective C is that bad, however there's no doubt that I found C# to be a more productive language, you can use Linq, Async/Await and some great .NET libraries including the SQLite.NET mini ORM. Xamarin Studio, which is their IDE for the Mac worked well, and integration with storyboards in Xcode works well enough.

Growing community

There is a growing community of developers who are making great things in Xamarin, there are open source projects like MVVMCross (which I chose not to use this time, but will look at in the future) that are actively contributed to and user groups around the globe full of developers. There are many blog posts and Stack Overflow questions that are Xamarin specific, which helps to accompany the official documentation.

The Bad

Missing out on iOS open source 

This is the biggest one for me, so many components and UI widgets for iOS are available as open-source drop-ins to your app. Xamarin has a component store where they attempt to make up for this, however it still has a long way to go. For me, if I knew I was creating an app that was only ever going to be on iOS, this factor alone would probably mean I gave Xamarin a miss for that particular project so that I can make use of CocoaPods, however it's pretty rare that you know for certain you are never going to want an android version of an app.

Visual studio integration is flaky

Xamarin has a feature that allows you to write code in Visual Studio and have it remotely compile and launch on a network connected Mac. This was very flaky and slow for me, so I didn't bother with it, Xamarin Studio isn't too bad, and if you like you can develop your core library code as a separate PCL DLL on Windows so you can use NCrunch for increase test driven development productivity and then develop the UI of the app on the Mac.

Extra layer of potential bugs

While the Xamarin team are extremely smart, and have created a great platform, they are not infallible. There is still an extra layer of code between your app and the hardware which could cause bugs, either in the Xamarin code itself, or as a result of you needing to know about how both iOS and the Xamarin garbage collectors/compilation works. After we released the app, we wanted to add some image resizing features, and came across a memory leak (Xamarin ships their own garbage collector in your app) that we had a hard time fixing. After contacting support with a trimmed down app to reproduce the problem they indicated to us they found a bug in Xamarin and were going to push an update shortly. They also gave us a workaround which got us going straight away which was great, however it still cost us a few days of developer time debugging it.

Other things to note

Using Xamarin is not an excuse not to learn Cocoa Touch and bits of Objective C

My earlier point about not being afraid to learn new things applies here as you'll still be reading Objective C code from blog posts and Apple's official documentation. Xamarin just wraps the Cocoa Touch libraries so you'll need to understand how that works - it's different to the web, and different to WPF, so don't think you Xamarin is a choice to help you just use your .NET developer knowledge to ship an iOS app. A great book to get introduced is iOS programming for .NET developers.

License Fees

Xamarin licenses for companies are $999 USD a year, per platform. This isn't cheap, but compared to developers salaries, or some of the common license fees for Microsoft developer products this is as cheap as chips.

Overall

All in all I'm a fan of Xamarin and would definitely use it again in the future, however I wouldn't say it's what you should always use for mobile development, it's a matter of picking the best tool for the job, which may be an Objective C/Android app, a Xamarin app, PhoneGap or a responsive website depending on the project, budget, goals etc. I do however believe Xamarin should definitely be something you consider as a serious option.

Also..
I'd like to give some credit to Vanessa Grixti (@vgrixti) for the visual design/UX work on the Buildaform app, she did a great job working to a tight deadline. Also if you are looking for Xamarin mobile developers in Sydney, get into contact with Envoy, as I'd love to work on some more Xamarin projects. 

Sunday, February 16, 2014

[Revit API] Binding a project parameter to all categories

In a recent project I had the need to create a new project parameter, and then set the value of it on certain elements. This post has great information on creating project parameters, however that post along with much of the Autodesk documentation add certain parameters to the CategorySet for the InstanceBinding method, what I wanted to do was add all of them. Unfortunately adding all categories in document.Settings.Categories throws an error as not all categories can have parameters bound.

There is a simple solution to this, only add categories to the CategorySet if they have their AllowsBoundParameters property set to true. It’s an obvious solution once you know this flag is available.

CategorySet categories = app.Application.Create.NewCategorySet();

foreach (Category category in doc.Settings.Categories)
{
    if (category.AllowsBoundParameters)
    {
        categories.Insert(category);
    }
}

Saturday, January 4, 2014

Setting up node-postgres with a new PostgreSQL installation on OSX

I was getting a PostgreSQL installation setup with NodeJS today on my computer and ran into some difficulty that I thought I'd write a post about in case someone else comes across the issue.

I started off by downloading the PostgreSQL installer from the PostgreSQL website (I had also tried Postgres.app) and running through the installer with mostly default settings.

Once that was done I went to install the node-postgres module in my node project via 'npm install pg', this threw the following error:

gyp: Call to 'pg_config --libdir' returned exit status 127. while trying to load binding.gyp

After some searching I found this Github issue which pointed me to the solution. The problem is that the installer did not add the PostgreSQL binary folder to my PATH. To get around this, I updated my ~/.bash_profile (vim ~/.bash_profile is the easiest way to do this) to add the following line:

export PATH=/Library/PostgreSQL/9.3/bin:$PATH

(be sure to use the version of PostgreSQL you installed. Also, if you already have that line, you should just add '/Library/PostgreSQL/9.3/bin:' after PATH=)

Save that file, restart terminal and you should be able to type pg_config and get some output on your screen. Once you've done that, reinstall the node-postgres module and you should not see the error anymore.

Hope this helps!

Wednesday, November 13, 2013

SQLite.Net ORM with Task Parallel Library in Xamarin

I've recently had the opportunity to work on a Xamarin.iOS project with Envoy. Having previously built iOS applications with Objective C I've been enjoying the chance to investigate techniques to share code across platforms.

With Xamarin, you can share some common code between Android and iOS projects if you structure it in a certain way. One technique that is commonly used to share code is to use the SQLite.NET ORM with SQLite rather than using Core Data or other device specific data access API's. Xamarin themselves have used this for an application which they've open sourced as example code: MWC 2012 

In that application, they create a subclass of SQLiteConnection with a static constructor that initialises a static variable to hold a reference to itself, as a kind of singleton. I followed this pattern in my code, however I've since discovered that this is perhaps not the best approach in all circumstances.

My application makes use of the Task Parallel Library to do some web service calls and subsequent database updates on a background thread. Much like the MWC sample I wrapped my calls to the database with a lock so that multiple threads won't update the database at once, and the application appeared to work correctly. However at various stages during my testing I came across seemingly random crashes, where the application which had been working fine would crash out of the blue with an error similar to the following:

mono-rt: Stacktrace:
mono-rt: at <0xffffffff>
mono-rt: at (wrapper managed-to-native) SQLite.SQLite3.Prepare2 (intptr,string,int,intptr&,intptr)
mono-rt: at SQLite.SQLite3.Prepare2 (intptr,string)
mono-rt: at SQLite.SQLiteCommand.Prepare ()
mono-rt: at SQLite.SQLiteCommand.ExecuteNonQuery ()
mono-rt: at SQLite.SQLiteConnection.Execute (string,object[])

This isn't particularly helpful and originally made me worried that perhaps the SQLite.NET ORM wasn't stable. However after some more research I've discovered that others were having the same problem and that they believed it was caused by the SQLite connection being accessed on different threads, even if it's not at the same time. When you think about it, of course this is an issue - the subclass of SQLiteConnection shouldn't be a singleton, it's a connection similar to those seen in ADO.NET and should be thread specific and closed when not needed. I believe the MWC application musn't have ran into this issue as they were only doing updates to the database on certain threads, not leaving it up to the Task Parallel Library.

So now, instead of having a singleton in my SQLite Connection, I'm using it in the IDisposable fashion it is designed to be used so that a connection is opened and closed with each query.
using (var db = MyDatabse.NewConnection())
{
    db.Insert(itemToInsert);
}
I've since stopped having the random application crashes. Hopefully this helps someone out who is having the same issue.

Tuesday, May 28, 2013

Styling Two or More Fusion Tables Layers in Google Maps

The Google Maps API has a feature called 'Fusion Tables Layer' which lets you overlay data from a Google Fusion Tables. Using this feature, you can upload some KML data into a Fusion Table and see it represented on the map (for example, you can highlight an area on a map to represent some sort of data). The Maps API has in built support for using KML directly, however KML files can get quite large for complex data, so using Fusion Tables is a high performance alternative (Google handles large data sets with ease) This is what my exmaple Fusion Table with KML data uploaded looks like:


You can display markers, polygons, and polylines on a layer and can style each of these as you wish using the options supplied to the API call. An example of the code to do this is available here.

If you have multiple bits of data to show, you can add multiple layers from a range of different Fusion Tables. However, there is one limitation, which is pointed out in the documentation:
Styles can only be applied to a single Fusion Tables layer per map. You may apply up to five styles to that layer.
I recently ran into this limitation when trying to overlay two separate (complex) data sets. For my use case, I wanted to show data from two different Fusion Tables with two different styles, which means I was out of luck. I tried a number of workarounds to avoid this (seemingly odd) limitation. I attempted to combine them into the one table, but the queries don't allow OR statements,  I then tried using my own KML file, however that came out larger than 1MB, which loaded very slowly, whereas the Fusion Tables layer handled that data with ease.

I then attempted to add styling information to the KML file before uploading it into the Fusion Table interface (as KML supports this), however the upload process strips that information out. It was while searching for a way to get around this that I found the solution. I discovered that in the Fusion Tables interface you can add your own map, style it there, and it will give you code to easily embed it. This is designed to allow those without coding skills to style and embed a map on a blog or web page. Great! I thought, a bit annoying that I have to store that information in an external dependency instead of in my own code in source control, but at least I can solve this problem (I could perhaps use the Fusion Tables API to set this style from within my application, at the cost of a few HTTP requests).

However when I went to find this map tab that the documentation mentions, it was greyed out...


There's no mention that I could easily find on the page explaining why it was greyed out, but I had a hunch. Given how terribly Google has dealt with Google Apps accounts, I figured that seeing as I was signed in with a Google Apps email, it might have something to do with that. Signing into my personal Gmail revealed that my hunch was indeed correct, I can add a map (you may need to give that account write permissions or copy the table to your personal account).

Sigh. Some searching uncovered some documentation on this. You have to submit a request to Google asking them to turn it on. Would be nice if they just mentioned this in the interface...

Once you've added a map, tools > change map styles will let you style it.
 
You're note quite done yet though, simple embedding this table into the API won't do it, you need to tell the API which style and which template to use in your map. There's some documentation on getting the style number and setting it in the Maps API here. I couldn't find an easy way to get this Id from the API, but it's probably a small number if you just want to try numbers up from 1,2,3,4 etc. Next you need the template ID, which you can find by clicking on the map tab's dropdown and clicking publish. At the end of the URL the querystring will have the template ID as 'tmplt'. 

You then pass these through in your maps API call like so:
 gridLayer = new googleMap.FusionTablesLayer({
                            query: {
                                select: 'geometry',
                                from: fusionTableId,
                            },
                            map: map,
                            templateId: 2,
                            styleId: 2,
                            clickable: false
                        });


You should them see your styled map embedded in your page. Simple... right?

Friday, June 29, 2012

Using C# Named Parameters for Code Readability

In C# 4.0, Microsoft introduced a feature called 'Named Parameters', which lets you refer to parameters in a method that you are calling in a syntax like this:
 
public void MyMethod(firstParameter: firstValue, secondParameter: secondValue)

This lets you call the method with parameters in a different order, and also helps to facilitate optional parameters. Aside from these benefits, I've come to like using them to improve code clarity, particularly in unit tests.
 
Lets say you have a method like this one:
 
public decimal CalculateFuelCostPerKm(double kilometresTravelled, double litresInFuelTank, decimal costToFillTank)
 
If you were to call that method, you might do something like this:
 
CalculateCostPerKm(500D, 60D, 72.58M);

However if you are reading that and don't know the parameters, you're going to have to dive deeper to understand it. A way to improve it might be:
 
var kilometresTravelled = 500D;
var litresInFuelTank = 60D;
var costToFillTank = 72.58M;
CalculateCostPerKm(kilometresTravelled, litresInFuelTank, costToFillTank);

Which is much clearer, but is a fair bit of effort. But with C# named parameters you can do this:
 
CalculateCostPerKm(kilometresTravelled: 500D, litresInFuelTank: 60D, costToFillTank: 72.58M);

Simple to do, and clear to read. In fact, this is probably one of the rare situations where C# being written
more like Objective-C is a good thing. Take this example for creating an alert dialog in the iOS SDK:
 
- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString*)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
 
Which you would call like:
 
[[UIAlertView alloc] initWithTitle:@"Error" message:@"You stuffed up" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

Or in C# you might do something like this (ignoring the delegate business):
 
UIAlertView.InitWithTitle("Error", "You stuffed up", myDelegate, "OK", null);

As you can see, the verbose nature of Objective-C makes for clearer code in this instance, however, we could write the C# method like:
 
UIAlertView.InitWithTitle(title: "Error", message: "You stuffed up", delegate: myDelegate, cancelButtonTitle: "OK", otherButtonTitles: null);

Which makes it just as clear.
 
I've found this technique particularly useful in unit tests, which often tend towards using constant values. For instance I might often have a method to setup a certain state in my stubs where I take in the important parameters required, this technique makes this much easier to read.
 
I’d love to hear your thoughts on this technique, either in the comments on this post or via Twitter (@rodh257)