Google

[SOLVED] Firebase Performance Monitoring in Xamarin Android

Oliver Brown
— This upcoming video may not be available to view yet.

I decided to add Firebase Performance Monitoring to the latest version of Tic-tac-toe Collection.

What is it

This allows you to collect timed traces of things that happen in your app. You can set up custom traces for anything you like, but it also tracks how long HTTP requests take by default. At least it’s supposed to. On iOS it worked well, but Android had nothing.

There is an open issue on the repo with the Xamarin binding that was created in December 2018. It includes suggestions to make sure your app is set to using the native HTTP handlers (which makes sense since whatever Firebase is doing it won’t be expecting a random third party HTTP stack to be used), however it still does not work.

How does it work

So I decided to investigate how the HTTP tracing is actually implemented. How found this Stack Overflow question which lead me to this video. It turns out the implementation works by doing some byte code rewriting that changes any references in your app to the HTTP classes to instead reference Firebase provided wrappers.

Why doesn’t it work for Xamarin Android?

I kind of assumed it was doing something like that, but didn’t really think through the implications. Specifically - it does the byte code rewriting as part of a Gradle plugin that is not executed as part of a Xamarin build.

Solution

It may be possible to get the Gradle plugin to execute it’s transformer, but that seems complicated. Luckily, Firebase does provide support for adding HTTP tracing to other libraries, so I decided to work with that.

I decided to implement my own HttpMessageHandler that sets up the HttpMetric and then delegates to a normal HttpClientHandler. This can be passed into the constructor of HttpClient.

public class FirebaseHttpMessageHandler : DelegatingHandler
{
    public FirebaseHttpMessageHandler() : base(new HttpClientHandler())
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var metric = StartTracking(request);
        var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        StopTracking(metric, response);
        return response;
    }

    private HttpMetric? StartTracking(HttpRequestMessage request)
    {
        try
        {
            var url = new Java.Net.URL(request.RequestUri.AbsoluteUri);
            var metric = Firebase.Perf.FirebasePerformance.Instance.NewHttpMetric(url, request.Method.Method);
            metric.Start();
            if (request.Content?.Headers?.ContentLength is long length)
            {
                metric.SetRequestPayloadSize(length);
            }

            return metric;
        }
        catch (Exception ex)
        {
            Debug.Fail($"URL performance tracking failed: {request.RequestUri.AbsoluteUri} - {ex.Message}");
            return null;
        }
    }

    private void StopTracking(HttpMetric? metric, HttpResponseMessage response)
    {
        if (metric is null)
        {
            return;
        }
        try
        {
            metric.SetHttpResponseCode((int)response.StatusCode);
            if (response.Content?.Headers?.ContentLength is long length)
            {
                metric.SetResponsePayloadSize(length);
            }
            if (response.Content?.Headers?.ContentType?.MediaType is string mediaType)
            {
                metric.SetResponseContentType(mediaType);
            }
        }
        catch (Exception ex)
        {
            Debug.Fail($"URL performance tracking failed: {response.RequestMessage.RequestUri.AbsoluteUri} - {ex.Message}");
        }
        finally
        {
            metric.Stop();
        }
    }
}

Why does it work for Xamarin iOS?

I don’t know the exact method used on iOS, but I do know that iOS has a feature called NSURLProtocol that lets you intercept all HTTP requests by the app, as well as method swizzling which lets you replace basically any method implementation at runtime.

Either of those could be used, and they would both just work in Xamarin.

Google Docs Motion

Oliver Brown
— This upcoming video may not be available to view yet.

Google continue to improve upon Google Docs today with the release of Google Docs motion which will “introduce a new way to collaborate - using your body”. Anything else I saw will be underwhelming compared to the article form Google, especially some of the pictures of some of the more advanced gestures it supports.

I have Google Wave

Oliver Brown
— This upcoming video may not be available to view yet.

Google Wave

I received a Google Wave invite this morning. I’ll post more after I’ve had a play.

This also means I have invites available…

Google Wave update is live - still invite only

Oliver Brown
— This upcoming video may not be available to view yet.

Google Wave

Google Wave went live yesterday but it still invite only.

It seems the people with access are the people who previously had sandbox access (everyone who went to Google I/O and a few others), another 100,000 people who applied early on and select paying Google Apps users. That number will grow slowly however as they also revealed that existing users will be able to invite others (similar to when GMail launched).

So if anyone has an invite… :P

Google Chrome

Oliver Brown
— This upcoming video may not be available to view yet.

Well this came way out of left field for me, but after reading their thoughts and plans on the matter makes a lot of sense: Google have released a browser, called Chrome. Main highlights: based on Webkit and using a spanking new Javascript engine called V8.

I’m using it right now to type this and everything seems in order. It feels faster than Firefox 3, the interface is nice and clean and I’m generally revelling in the nice newness of it all. Interestingly it seems to have a spellchecker built-in that doesn’t recognise the word “Google”…

Anyway, anything I might say about the browser this early will end up repeating most of their hype, and that is done much better by this comic strip they released.

PS. Currently the beta version is Windows only with Linux and Mac versions to follow..

Google Docs rule - if you use them right

Oliver Brown
— This upcoming video may not be available to view yet.

I’ve been vaguely using Google Docs (specifically Spreadsheets) since it came out but never to do anything actually important. Most of the time I just had a list I need sorting, or if I was feeling sophisticated I’d use it to decide on what was best value for money (how much £/GB a range of hard drives were for instance). Recently I started using it to plan lessons for the language learning app. The ability to use it from work (or any other computer I might be on - including viewing it on my Nokia 770) was useful, but in the end I was only really writing a list with it.

Until now. I now have a nifty little C# app that generates modules directly from a Google Spreadsheet which is definitely a Good Thing. I’ve been thinking of writing an app for module editing for a while since writing them by hand is tiresome and error prone. Google Spreadsheets does half the work for me by providing the user interface for generating a table and then provides access as simple XML. Which brings me to the matter of actually accessing the data. Google provide a client library in C# for accessing quite a lot of their API. I tried using it but found it a little confusing. Luckily since I was just wanting to query data, I discovered that raw access was actually easier. You simply make a GET request to http://spreadsheets.google.com/feeds/worksheets/_key_/public/values (where key is provided to you when you “publish” a spreadsheet - access to unpublished spreadsheets requires authorization which is more complicated). This gives you an Atom feed of URLs to the individual worksheets which them contain Atom feeds of either rows or columns (your choice). The query power of LINQ (along with XElement, XAttribute etc.) make transforming the feeds into modules really easy. In fact the code that does the hard work (takes a spreadsheet key and generates the XML) is only 102 lines long, and that’s including unnecessary spacing to make the LINQ more readable (the main LINQ query is 35 lines).

N73, 770 and the Internet

Oliver Brown
— This upcoming video may not be available to view yet.

I recently finally got a new mobile phone contract with a Nokia N73 with T-Mobile (UK), complete with “unlimited” Internet access. I have to say it is actually more useful than I thought it would be.

I have a little app called GCalSync which synchronizes the calendar with Google Calendar. I also have the official Google Mail client which is almost perfectly (it doesn’t seem to show whether messages in my inbox have a label or not - but it’s a minor concern). The best bit though it accessing the internet from Nokia 770 using the N73 as a bluetooth modem.

Setting is not as straight forward as it should be. The 770 has settings wizard and T-Mobile Internet is an option, but it’s settings are wrong. After searching for a bit I found the correct settings:

  • Number to dial: *99***1#
  • APN: general.t-mobile.uk
  • Username: user
  • Password: pass

The “1” part of the number to dial has a slight chance of being different. This number refers to the different connections your phone might have setup. By default the one you want is the first one and will only need to be something different if you’ve changed things.

After that you may want to set your 770 as a trusted device (in the bluetooth pairing options on you N73) so that you don’t need to say “OK” all the time on your N73 when your 770 wants to connect.

Google Checkout is cool

Oliver Brown
— This upcoming video may not be available to view yet.

Google Checkout is an online payment processor. It was originally billed as a “PayPal killer” but there are important differences. Checkout is more shopping orientated whereas PayPal is for general payments. Checkout is also available in far fewer countries at the moment. The best part is their tactics to gain users.

For a limited time Google Checkout will give you £10 off any order over £30 (excluding delivery). Not just your first order, but all your orders while they keep the offer open. This is as much to attract businesses as users (the increased custom from charging £10 less for a lot of different items).

There are still few UK sites supporting Google Checkout - the biggest I know of is Ebuyer. Since most of this blog is about technology though, I’d have to say that’s a pretty good site to get £10 off at…

Google gets hacked - kills the web

Oliver Brown
— This upcoming video may not be available to view yet.

This morning Google went down in a big way, and in a disturbing way slowed down the most of the world wide web. Well it may not actually be most of it, but it was most of the stuff I was browsing.

The whois output for google.com this morning was:

GOOGLE.COM.ZZZZZ.GET.LAID.AT.WWW.SWINGINGCOMMUNITY.COM GOOGLE.COM.ZOMBIED.AND.HACKED.BY.WWW.WEB-HACK.COM GOOGLE.COM.WORDT.DOOR.VEEL.WHTERS.GEBRUIKT.SERVERTJE.NET GOOGLE.COM.VN GOOGLE.COM.UA GOOGLE.COM.SUCKS.FIND.CRACKZ.WITH.SEARCH.GULLI.COM GOOGLE.COM.SPROSIUYANDEKSA.RU GOOGLE.COM.SA GOOGLE.COM.PLZ.GIVE.A.PR8.TO.AUDIOTRACKER.NET GOOGLE.COM.MX GOOGLE.COM.IS.NOT.HOSTED.BY.ACTIVEDOMAINDNS.NET GOOGLE.COM.IS.APPROVED.BY.NUMEA.COM GOOGLE.COM.HAS.LESS.FREE.PORN.IN.ITS.SEARCH.ENGINE.THAN.SECZY.COM GOOGLE.COM.DO GOOGLE.COM.BR GOOGLE.COM.AU GOOGLE.COM

It seems to be back up now although you may still have problems depending on who often your ISP updates its DNS records.

Although it seems only google.com was affected*, most of Google’s other domains reference google.com as a nameserver, so they were inaccessible too. This includes googlesyndication.com, the domain Adsense ads are served from. As such every single site that hosts Google ads well have seemed slower while the browser waits in vain for a response from Google’s servers.

* At least as far as Google are concerned. A whois on yahoo.com was almost the same but I didn’t actually notice whether Yahoo was down or not.

Fun with Google calculator

Oliver Brown
— This upcoming video may not be available to view yet.

I’ve talked about the clever calculator features built into Google before. Most of my examples then were rather silly. Well I’ve started using it a bit more seriously recently. The great thing it does is allow unit conversions to be done effortlessly at the same time as the main calculation.

For example, I have a video clip that is about 350 MB and 45 minutes long. I want to know what the average bit rate for the encoding is, in kbps. 350 MB is 350 * 1024 * 8 kbits. 45 minutes is 45 * 60 seconds. Works those two out, divide the first by the second and I have my answer. Or just type [350 MB / 45 minutes in kbps](http://www.google.com/search?sourceid=navclient-ff&ie=UTF-8&rls=GGGL,GGGL:2006-22,GGGL:en&q=350+MB+%2F+45+minutes+in+kbps) into Google and I have my answer with far less effort.