Securing Mac application with Touch ID

This Monday I got a shiny new Macbook Pro with Touchbar. There few things I don’t like about it but one thing I absolutely love is TouchID integration.

I wanted to check how easy it is to integrate with Xamarin.Mac app. Surprisingly, the APIs are exactly same as what are available on iOS, I used the code from Mike James’ blog post about securing iOS apps with TouchID

App
Touchbar

All you need is below code snippet in your Xamarin.Mac app to secure it with all new Thouch ID


LAContextReplyHandler replyHandler;

// ...

void UseTouchID()
{
    var contex = new LAContext();
    NSError authError;
    if (contex.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out authError))
    {
        replyHandler = new LAContextReplyHandler((success, error) =>
        {
            if (success)
            {
                InvokeOnMainThread(() => ShowMessage());
            }
        });
    }

    contex.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "authenticate", replyHandler);
}

Note that we do need to have a fallback mechanism for legacy Macbook Pros (i.e without Touchbar), you can download complete source code
on Github here https://github.com/prashantvc/SuperSecureApp

JSON Copy version 1.0 for Xamarin Studio

UPDATE: JSON Copy now available in Xamarin Studio’s Add-in Manager, under IDE Extensions

Few months back I published an Addin for MonoDevelop and Xamarin Studio to allow developer to paste JSON string as C# classes. The functionality was primitive and experimental, we did not have any control over the code formatting or class structure.

In v1.0 I have fixed most of those limitations in the Addin, now we have more control over how C# structured. You can find download and installation instruction here.

Here is what’s new in version 1.0:

  1. Choose between Pascal Casing and default lowercase letters
  2. Mark classes as internal or public
  3. Create Properties or Fields for JSON properties.
  4. New Preferences Panel

Imgur

I would love to hear your feedback, please create an issue in Github repo or leave a comment

Paste JSON as Classes in Xamarin Studio

Update: Now compatible with Xamarin Studio/MonoDevelop 5

As a C# mobile developer I spend lot of time writing classes to serialise or deserialise JSON string when integrating apps with third-party REST APIs.Visual Studio has an amazing feature to rescue us from this tedious job, Paste JSON As Classes command, where it automatically generates the strongly typed classes for JSON string.

I was motivated to create a similar add-in for my primary development IDE, Xamarin Studio. I started writing the C# code generator with T4 templates, and quickly realised that it will take too long to finish the development with limited time I get to spend on side projects.

Luckily, I stumbled upon this awesome open source project on codeplex to generate the C# classes for JSON text. It supports typed arrays, typed objects, integers, floats, booleans, strings and nullable types. It helped me quickly put together an Add-in to paste JSON from clipboard to C# classes in Xamarin Studio

image

Installation

You need to follow these three easy steps to install it on our Xamarin Studio.

  1. Download the add-in package from Github
  2. Open Xamarin Studio -> Add-in Manager
  3. Click on Install from file… button and select the downloaded package to install

Once you install the add-in the Paste JSON as classes command will appear in Edit menu, that enable you to paste C# classes directly from the text in your clipboard.

The complete code for the add-in is available on the Github here, please add an issue if you find any bug or send me a pull request 🙂

Magic of NSLinguistic​Tagger

This evening one of my friends sent me the link of iA Writer’s video featuring their latest update to the app.

I was blown away by the syntax highlighter in edit mode, where it highlights words based on selection of parts of speech.

At first, I thought they are doing some sophisticated natural language processing, I’m not expert but supporting multiple languages sounds like a tedious/impossible job to do in an year, unless there is easy way.

Apple provides us NSLinguistic​Tagger class as part of the iOS 5 SDK, it allows us to split up natural language text and tag it with information. As per the documentation it can identify languages, scripts and stem forms of words! NSLinguistic​Tagger is quite easy to use.

We can start by creating the instance of NSLinguisticTagger with tag schemes for a language and bunch of NSLinguisticTaggerOptions, options are used to tell tagger to ignore words, white spaces, punctuations etc.

var options = NSLinguisticTaggerOptions.JoinNames 
              | NSLinguisticTaggerOptions.OmitWhitespace;

var tagger = new NSLinguisticTagger (
    NSLinguisticTagger.GetAvailableTagSchemesForLanguage ("en"), 
    options);

Once we create the instance, we will assign it a string to analyse

tagger.AnalysisString = "A quick movement of the enemy will jeopardise six gunboats";

And finally, fetch the tags with EnumerateTagsInRange method and print them out.

tagger.EnumerateTagsInRange (new NSRange (0, statement.Length), NSLinguisticTag.SchemeLexicalClass, options, TaggerEnumerator);

...

void TaggerEnumerator (NSString tag, NSRange tokenRange, NSRange sentenceRange, ref bool stop)
{
    var word = statement.Substring (tokenRange.Location,
      tokenRange.Length);
    words.Add (new Tuple<string, string> (tag, word));
}

The result after processing A quick movement of the enemy will jeopardise six gunboats looks something like this:

 Adjective: quick
 Noun: movement, enemy, gunboats
 Preposition: of
 Verb: will, jeopardise
 Number: six

it even identifies the number, that’s pretty amazing!

PS: You can find the complete code here – https://gist.github.com/prashantvc/8039121

Modal UIAlertView (iOS 7)

It’s common practice to use NSRunLoop to show modal UIAlertView to block code execution until user input is processed in iOS.

The below code worked perfectly on previous versions of iOS (5 & 6)

int ShowModalAletView (string title, string message, params string[] buttons)
{
    int clicked = -1;
    var alertView = new UIAlertView (title, message, null, null, buttons);
    alertView.Show ();
    bool done = false;
    alertView.Clicked += (sender, buttonArgs) => {
        Console.WriteLine ("User clicked on {0}", buttonArgs.ButtonIndex);
        clicked = buttonArgs.ButtonIndex;
    };
    while (clicked == -1){
        NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5));
    }
    return clicked;
}

until Apple released the iOS7, it broke few existing apps 1. Fortunately, there is a better way of implementing it with C#’s async/await

Here’s the new code taking advantage of async/await pattern to show modal UIAlertView:

Task ShowModalAletViewAsync (string title, string message, params string[] buttons)
{
    var alertView = new UIAlertView (title, message, null, null, buttons);
    alertView.Show ();
    var tsc = new TaskCompletionSource ();

    alertView.Clicked += (sender, buttonArgs) => {
        Console.WriteLine (“User clicked on {0}”, buttonArgs.ButtonIndex);
        tsc.TrySetResult(buttonArgs.ButtonIndex);
    };
    return tsc.Task;
}

//Usage
async Task PromptUser() {
    var result = await ShowModalAletViewAsync (“Alert”, “Do you want to continue?”, “Yes”, “No”); //process the result
}

  1. From Apple Developer Forum: https://devforums.apple.com/message/887792

Image Effects with Xamarin.Android

A while ago I was working on a sample app to demonstrate basic image editing abilities using ColorFilter to adjust an image brightness, contrast and saturation.

Color filters are great, but they are comparatively slow on large images, while looking for better options I learned that we could use Effects that are available in Android API Level 14

The effects in Android uses GPU and OpenGL textures to perform all the processing for maximum performances. The EffectFactory provides the list of various effects that can be applied to an image not just basic adjustments like brightness and contrast.

I have ported one of the Google’s sample to Xamarin.Android to demonstrate these effects, this should be a useful getting started sample for developers like me 🙂

The GitHub repository includes the full solution for the app in the screenshot if you want to run from it: monodroid-samples

Why set-only properties are bad design practice?

Last week my team member from Cambridge was reviewing my code; while he was going through a class he noticed a set-only property and told it is really bad idea to have one in the class. As we both kind of busy, he asked me to read the Property Design section from “Framework Design Guidelines” [ISBN: 978-81-317-2978-3] book.

Luckily I have copy of book, it is clearly mentioned in it that.

“DO NOT provide set-only property or properties with the setter having broader accessibility than the getter

If the getter cannot be provided, implement the functionality as a method instead.”

But it is nowhere in the book given the reasons not use it. So, here in this post I will try to list the reasons, why set-only properties are bad design practice.

It is quite obvious, if OO is meant to better represent the real world, a set-only suggest that our modelling is pretty off.  Set-only properties are uncommon and properties are used to for dumb sets just to store a value without much processing.

If I can set a property on something but never get it, I will never know if something else changes/overwrites the value that I set. That could be a problem if I rely on the value that I set, and I am unable to persist it until the time that I would want to get it.

Using a method instead of a set-only property will be less confusing for a fellow developer. The name of the method usually indicates set or get, but property names don’t normally indicate that something can only be set and not be gotten. I suppose if the property were something like “ReadOnlyBackgroundColour” it would not be confusing to the other developers, but that would just look weird.

We can see lot of example of this in .Net framework; AppDomain has a method called SetCachePath instead of having a set-only property called CachePath. These small things may not feel important while writing code, but makes huge positive impact on readability and maintainability of code base.