Xamarin: Inspect, Visualize, and Debug Your App Live

When you’re adding the final polish before releasing your mobile app, it’s easy to get stuck in that dreaded tweak-code-debug-run cycle. For every change that you make, even the simplest ones, you have to relaunch your app on several emulators or devices to ensure it’s working properly. This is where the brand new Xamarin Inspector […]

The post Inspect, Visualize, and Debug Your App Live appeared first on Xamarin Blog.

Daniel Cazzulino: How to get the item type or build action of a file in a project

When working with Roslyn inside a Visual Studio extension, it’s not rare to need to go back and
forth between the two. In Roslyn-land, projects are mostly identified by their Guid. This is the
ProjectGuid MSBuild property of a project, available from the IVsHierarchy
VSHPROPID_ProjectIDGuid property that uniquely identifies the
project in a solution. And documents are most easily identified by their
FilePath property.

In my case, I needed to retrieve the item type (build action in the property browser), given
the things that the Roslyn API works with: project id, file path. Tell me it
doesn’t give you the creeps:

static string GetItemType (IServiceProvider services, Guid projectId, string filePath)
    var solution = services.GetService<SVsSolution, IVsSolution> ();

    IVsHierarchy project;
    uint itemId;
    object projectItem;
    string itemType = null;

    if (ErrorHandler.Succeeded (solution.GetProjectOfGuid (projectId, out project)) &&
        ErrorHandler.Succeeded (project.ParseCanonicalName (filePath, out itemId)) &&
        itemId != (uint)VSConstants.VSITEMID.Nil &&
        ErrorHandler.Succeeded (project.GetProperty (itemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out projectItem)) &&
        projectItem != null && projectItem is ProjectItem) {
        itemType = ((ProjectItem)projectItem).Properties.Item ("ItemType").Value.ToString ();

    return itemType;

And when searching for things like this, it’s pretty awesome to come across posts that say things like Who said building Visual Studio Extensions was hard?.


Xamarin: Tips for Winning a Xammy at Xamarin Evolve 2016

Xamarin app developers, mark your calendars: the last day of 2015 is the deadline to enter your app for consideration in the Xamarin Evolve 2016 Xammy Awards! We will then choose the finalists in each of the three major categories of Enterprise, Emerging Devices, and Consumer, with winners announced on stage at Xamarin Evolve 2016. Here […]

The post Tips for Winning a Xammy at Xamarin Evolve 2016 appeared first on Xamarin Blog.

Chris Riesgo: Android AltBeacon Library: Version 2.7

It’s overdue, but I just published version 2.7 of the Android AltBeacon Library.

You can find it on:

What’s new

There have been several major version releases from AltBeacon since the Xamarin library has been updated, so here’s a quick rundown of new shiny bits you can expect to find:

Features changes:

  • Optionally allow tracking multiple beacons with the same identifiers, distinguishing with the mac address.
  • Support for Gatt-based beacons and interleaved frames
  • Filter out invalid RSSI values of 127 for distance calculations
  • Identifier class now supports conversion to/from the UUID class.
  • Optionally allow using an ArmaRssiFilter for faster distance calculation convergence.
  • Support detection of Eddystone-UID, Eddystone-TLM and Eddystone-URL
  • Support transmission of Eddystone-UID and other GATT-based formats
  • Add more options for parsing identifiers of specific lengths
  • When scanning in Background on Android 5+, do a full scan without filters during the main scan period (default for 10 seconds once every 5 minutes) in case scan filters are unavailable
  • Common open-source BeaconParser layouts are defined as constants on BeaconParser
  • Bluetooth address is now a field on Region, offering the option of monitoring and ranging for all beacon transmissions from a known device’s MAC Address
  • Target SDK bumped to 23 for Android 6.0
  • Adds hardware accelerated detection of Eddystone frames in the background on Android 5+
  • Provides ability to forward BLE scan callbacks for non-beacon advertisements

Bug Fixes:

  • Workaround for 500 alarm limit on Samsung devices.
  • Fix NPE in scanning for beacons on Lollipop in the emulator
  • Restart scanning after app is killed due to memory pressure
  • Protect against crashes when falling behind on scans
  • Protect against null pointer exceptions in race conditions
  • Protect against crash when stopping advertising with bluetooth turned off
  • Stop BLE scanning after stopping ranging of the last region
  • Fix for NPE on Galaxy Note 4
  • Keep from getting stuck in background mode after stopping and restarting service
  • Protect against Null Pointer Exceptions when dynamically adding and removing monitored/ranged regions
  • Protect against an underlying Android BLE bug that sometimes causes Null Pointer Exceptions when starting stopping scanning.
  • Ignore corrupted beacon BLE packets instead of throwing an exception about them
  • Use a private ThreadPoolExecutor for beacon scanning to avoid thread starving apps using AsyncTask
  • Allow missing data fields, setting data values to zero if data fields missing in packet
  • If a custom AltBeacon parser is supplied, don’t crash with NPE if it is not found
  • Android 5.x devices could not detect AltBeacons on with unusual manufacturer codes in versions 2.3 and 2.3.1 due to Android 5.x BLE scan filters being inadvertently enabled in the foreground.
  • Improve handling of PDUs with unexpected lengths.
  • Add ability to optionally shorteten Beacon identifiers if their max length can be longer than the PDU.
  • Fix improper termination of URLs on URI Beacons causing an extra byte to show up on the end.
  • Identifer.parse(“0”) is now handled properly. A bug in the previous release did not handle it properly leading to ranging/monitoring failures on regions with such an identifier.
  • Switch BeaconParsers list to be a CopyOnWriteArrayList to avoid UnsupportedOperationException changing list after starting scanning.
  • Fix crash when region has more identifiers than beacon
  • Fix bugs with compressing Eddystone-URL to bytes and back
  • Allow Regions to match beacons with fewer identifiers if the extra region identifiers are null. This allows matching Eddystone-UID and Eddystone-URL beacon with the default Region with three null identifiers. This started failing in version 2.6.
  • Declare the ACCESS_COARSE_LOCATION permission in the manifest since it is required for Android 6.0. This is helpful to keep beacon detection working on Android 6.0 for apps that don’t explicitly declare this in their own manifest.
  • Fix rescheduling of alarms in the distant future so they don’t inadvertently go off right away

If you notice an issue…

Please help the community by logging any issues you find.

  1. make sure that the issue hasn’t already been logged against the original library
  2. if the original library works correctly, log an issue against the Xamarin binding

Can’t wait to hear about the cool apps you build!

Michael Ridland: MVVM / MVC is dead? Is Unidirectional a MVVM / MVC Killer?

Ah so now when you’ve learnt MVC/MVVM, everyone’s decided that we shouldn’t do it anymore? Huh? MVVM is a great pattern which allows for a clean separation between views and logic, it also lends itself well to unit testing, but is it the only way? If you didn’t already know there’s some new kids on the […]

The post MVVM / MVC is dead? Is Unidirectional a MVVM / MVC Killer? appeared first on Michael Ridland.

Xamarin: Xamarin 4 Parties in December!

Our just released, Xamarin 4, has been a wild success for mobile developers everywhere giving you everything you need to build, test, monitor, and accelerate amazing mobile apps. Xamarin user groups all over the world will be hosting celebrations to learn about the newest features and enhancements introduced in Xamarin 4. Not only will you be able to […]

The post Xamarin 4 Parties in December! appeared first on Xamarin Blog.

James Montemagno: Simplified iOS & Android Runtime Permissions with Plugins!

TLDR; I created a brand new cross-platform Permissions Plugin for Xamarin to enable anyone to query and request common permissions from shared code. You can watch a video here.

Permissions! Blarg!

As an Android developer I have felt pretty spoiled over the last few years when it came to getting access to an API that required a permission. Simply check a checkbox in the project setting and any of the 130+ permissions were mine to have! The user installed my app and automatically granted me every permission my little heart desired. I took a look at what those poor iOS developers (and myself) had to implement in their apps to request a permission, get a callback, and then handle revoking of permissions from users! That looked like no fun at all. Well, Android developers had it too good for too long and now with the release of Android Marshmallow users are back in control with the introduction of Runtime Permissions, and I honestly think it is for the better. However, this means for developers we now have to go off and check permissions on multiple platforms, with different APIs, and no shared code. 

First, let’s take a look at what we would have to do for both iOS and Android to get access to grab the users location.


  1. Add NSLocationWhenInUseUsageDescription or  NSLocationAlwaysUsageDescription to info.plist.
  2. Create new CLLocatonManager
  3. Check we have the permission
  4. Request correct permission if needed
  5. Register for callbacks when authorization changes

Here is what it would look like:

void RequestLocationPermission()

    var locationManager = new CLLocationManager();

    EventHandler authCallback = null;

    authCallback = (sender, e) =>
            if(e.Status == CLAuthorizationStatus.NotDetermined)
            locationManager.AuthorizationChanged -= authCallback;
            //do stuff here 

    locationManager.AuthorizationChanged += authCallback;

    var info = NSBundle.MainBundle.InfoDictionary;
    if (info.ContainsKey(new NSString("NSLocationWhenInUseUsageDescription")))
    else if (info.ContainsKey(new NSString("NSLocationAlwaysUsageDescription")))
        throw new UnauthorizedAccessException("On iOS 8.0 and higher you must set either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in your Info.plist file to enable Authorization Requests for Location updates!");


  1. Add correct permissions to AndroidManifest
  2. Check permissions on API 23+
  3. Check if need to show rationale (user revoked or denied)
  4. Request permissions
  5. Do this every single time before you make a call!

Here is what that would look like:

async Task GetLocationCompatAsync()
  const string permission = Manifest.Permission.AccessFineLocation;
  if (ContextCompat.CheckSelfPermission(this, permission) == (int)Permission.Granted)
    await GetLocationAsync();
  if (ActivityCompat.ShouldShowRequestPermissionRationale(this, permission))
    //Explain to the user why we need to read the location
    Snackbar.Make(layout, "Location access is required to show coffee shops nearby.", Snackbar.LengthIndefinite)
            .SetAction("OK", v => ActivityCompat.RequestPermissions(this, PermissionsLocation, RequestLocationId))
  ActivityCompat.RequestPermissions(this, PermissionsLocation, RequestLocationId); 

The Problem

It is pretty clear that this code is pretty tedious to write and it has to be done in the actual iOS or Android projects, which is a complete bummer. While we have been forced to write this code for years, I say NO MORE! Last week I set out on a goal of creating my next Plugins for Xamarin to solve Permissions once and for all. Here was the goal:

  1. Simple Cross-platform Async API that should:
  2. CheckPermisssion – Simply check the permission
  3. ShouldShowRationale – Tell us if the user revoked access on Android
  4. RequestPermissions – Any amount that you would like!
  5. Work on a wide array of iOS and Android permissions that require runtime checks

Today, I am pleased to introduce my latest Plugin that does just this, Permissions Plugin for Xamarin! This will not only simplify permissions on a per platform basis, but also from shared code such as Xamarin.Forms. More importantly though it will enable Library creators to deeply integrate with the SDKs without having to worry about writing all the permission code. Did I mention it is all async??!?!?! 

Permissions I Handle

The nice thing is that there are just 9 “permission groups”  (about 30+ permissions) on Android that have to be checked and about the same on iOS currently. Here is a full listing of everything the library can do:

  1.   Calendar (Android: Calendar, iOS: Events)
  2.   Camera (Android: Camera, iOS: Camera Roll & Camera)
  3.   Contacts (Android: Contacts, iOS: AddressBook)
  4.   Location (Android: Location, iOS: CoreLocation (Always/WhenInUse))
  5.   Microphone (Android: Microphone, iOS: Microphone)
  6.   Phone (Android: Phone, iOS: Nothing)
  7.   Photos (Android: Nothing, iOS: Photos)
  8.   Reminders(Android: Nothing, iOS: Reminders)
  9.   Sensors (Android: Body Sensors, iOS: CoreMotion)
  10.   Sms (Android: Sms, iOS: Nothing)
  11.   Storage (Android: External Storage, iOS: Nothing)


All in all I have to say that iOS permission requesting is pretty straight forward. You just have to go in aware that each library has its own way of handling permissions, different enums, and different callbacks to handle. If you read through the documentation for each of these APIs you will see that they are pretty identical except that you have different types of status: AVAuthorizationStatus, ABAuthorizationStatus, EKAuthorizationStatus, CLAuthorizationStatus, and more! Each of these actually have a common type though of Granted, Denied, Restricted, or Unknown. I decided copy most of these when returning a PermissionStatus to you:

  1. Denied
  2. Disabled (feature is disabled, such as locatio)
  3. Granted
  4. Restricted
  5. Unknown

To hand the fact that there is a mixture of Async calls to check the status of these permissions and no way to actually request them async I simply used a TaskCompletionSource on every single call such as:

Task<PermissionStatus> RequestPhotosPermission()

    if (PhotosPermissionStatus == PermissionStatus.Granted)
        return Task.FromResult(PermissionStatus.Granted);

    var tcs = new TaskCompletionSource();

    PHPhotoLibrary.RequestAuthorization(status =>
                case PHAuthorizationStatus.Authorized:
                case PHAuthorizationStatus.Denied:
                case PHAuthorizationStatus.Restricted:

    return tcs.Task;

Android on the other hand is a bit more tricky. To check a permission this can be done on the activity or the application context, which is what I will use if you are trying this on a background service.

To request a permission you actually need an Activity and then you have to actually override a method on the activity to handle the request. This is obviously an issue because I am writing a library and can’t access the Activity you are on. Well, that used to be the case until I created the CurrentActivity plugin! Enabling you, me, or any library creator to get access to the current activity! 

This means a new MainApplication.cs file will get installed when you install the plugin, so be sure to read all about that! Now that I have the Activity the next issue to overcome is that fact that the API I created takes in my enum of a permission group, but Android requires you request all of the Manifest permissions you have specified for that group. This means that yes you will still need to add the permissions to your manifest, but I do a reverse lookup to see what you have listed in the AndroidManifest and those are what I request! What!!!! Amazing! I know! However, there is one small caveat here, which is whatever Activity you are requesting from you will have to notify my library when the call is returned by simply adding the following lines of code:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
    PermissionsImplementation.Current.OnRequestPermissionsAsyncResult(requestCode, permissions, grantResults);

If you are supporting more than iOS/Android and have a bunch of Windows apps, do not fear as I added in dummy implementations for all flavors of Windows and .NET so permissions will return true.

In Action

Finally I get to just show you the code! It is actually super straight forward. Let’s say you want to request the location using the Geolocator library (although it does check permissions in the upcoming version 2.0.0).  Here are the calls in a PCL (Xamarin.Forms app hence the DisplayAlerts):

    var status = await CrossPermissions.Current.CheckPermissionStatus(Permission.Location);
    if (status != PermissionStatus.Granted)
        if(await CrossPermissions.Current.ShouldShowRequestPermissionRationale(Permission.Location))
            await DisplayAlert("Need location", "Gunna need that location", "OK");

        var results = await CrossPermissions.Current.RequestPermissions(new[] {Permission.Location});
        status = results[Permission.Location];

    if (status == PermissionStatus.Granted)
        var results = await CrossGeolocator.Current.GetPositionAsync(10000);
        LabelGeolocation.Text = "Lat: " + results.Latitude + " Long: " + results.Longitude;
    else if(status != PermissionStatus.Unknown)
        await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
catch (Exception ex)

    LabelGeolocation.Text = "Error: " + ex;

Grab the NuGet & Code

Last week I pushed all the code up to GitHub and made the NuGet packages available for all. I will be integrating the Permissions plugin into all of my other Plugins that require permission checking. I also recorded a Motz Codes Live with a full walkthrough.