Mirror API With C# 13


GoogleAnalyticsGlass

Have you wondered how Google Glass works?  Have you assumed as I did that because Google Glass starts with Google that you are going to have to learn android in order to develop for it?   I have some good news for you, if you can make a HTTP post with a programming language you can post to the Google Glass Time-line.

I will be leaving for Google I/O tomorrow, after that I will be on vacation so I thought I would show you how easy it is to write to Google Glass Time-Line using C#.     So what would be some useful information to write to Google Glass?     How about the Google Analytics Real-time API?    How about a nice notification whenever there are X number of users on your site.   Useful … I do not know someone just told me i was geeky for doing it,   I can live with that.

Real-time API Beta

At this time, the Google Analytics Real-time API is in public beta.  This means that if you want to access the Real-time API you have to request it.    Real Time Reporting API Private Beta it normally takes about 24 hours to get access you will NOT hear anything from Google when you get access.    It just happens like magic, so wait 24 hours then try it.

Console application

In Google Developers console create an application under APIs enable Analytics API and Google Mirror API.   The Mirror API is what we use to talk to Glass,  the Analytics API is what we use to talk to Google Analytics.    For this test version we will be creating a Client id for native application.   Remember as always to fill in the email and the product name under the consent screen.

NuGet

You will need the following NuGet packages for this Tutorial.

pm> Install-Package Google.Apis.Mirror.v1
pm> Install-Package Google.Apis.Analytics.v3

You will probably end up adding most of these using’s.

using Google.Apis.Mirror.v1;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;

Authentication

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret },
                                                                         new[] { MirrorService.Scope.GlassTimeline , AnalyticsService.Scope.AnalyticsReadonly},
                                                                         "LindaGlass",
                                                                         CancellationToken.None,
                                                                         new FileDataStore("Real-timeMirror.Auth.Store")).Result;

This is the same authentication code i always use the only difference is this time we are accessing two APIs.

After running that you should have a file   in %AppData%  \  Real-timeMirror.Auth.Store

{"access_token":"ya29.LgC7epX4ap0MWR8AAABPPREY5vzo2ySNynQjPQG-jWfEnErREVncYqwHVv3Zvg",
   "token_type":"Bearer",
   "expires_in":3600,
"refresh_token":"1/FHR4omNNDH9Wj-CggfBg8VWtpSb_0VXt6AUR2VymLKQ",
       "Issued":"2014-06-18T21:20:01.260+02:00"}

Services!

This tutorial is a little different from my other tutorials.  Normally we only create one service.  Connect to Google Drive, or connect to Google Analytics.   However this time we will need two services, one that will allow us to read from Google Analytics, and another one that will allow us to write to the Mirror API.

// Everything we want to send to the Mirror API will go though the GlassService
 MirrorService GlassService = new MirrorService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Mirror API Sample",
                });
 // When we want to read information from Google Analytics our requests will be made though AnalyticsRealTimeService
AnalyticsService AnalyticsRealTimeService = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Mirror API Sample",
                });

Real-Time Request

The Real-time API is very limited in the dimensions and metrics it has available for you to select from;  this because the core reporting data has not finished processing.   I am going to keep this easy all we are going to do is request rt:activeUsers .  Active Users is the number of users that are interacting with the property right now.

As with request to the core reporting API, you will need to know the profile id. We are going to make our request to Google Analytics so we will be using our AnalyticsRealTimeService.

var RealTimeRequest = AnalyticsRealTimeService.Data.Realtime.Get("ga:" + ProfileId.ToString(), "rt:activeUsers"); 
var RealTimeResults = RealTimeRequest.Execute();

RealTimeResults now contains the response from the server. I recommend that you check RealTimeResults.TotalResults if there is no one on the site right now TotalResults will be 0 so there is no reason to continue anymore.

Because we are not requesting any dimensions and only one metric we know that there will only be one row with one column returned.

int ActiveUsersNow = 0;
if (RealTimeResults.TotalResults > 0) {
 ActiveUsersNow = Int32.Parse(RealTimeResults.Rows[0][0]);    // number of users active on the site now. 
 }

Mirror API

Now that we have the ActiveUsersNow we will want to write that to Glass.   We have a couple of options here. You can right just strait text to the timeline, or you can writ3 some html and make it look nice.

I want to give you a few links i have found useful.

//Writing to time-line
//create a TimeLineItem   Note: you can write to TimeLine.Html and it will use the HTML you add. 
Apis.Mirror.v1.Data.TimelineItem TimeLine = new Apis.Mirror.v1.Data.TimelineItem();
TimeLine.text= ActiveUsersNow.ToString("N0",CultureInfo.CurrentCulture);    
// write the timeline item to Glass
var o = GoogleAutentication.GlassService.Timeline.Insert(TimeLine).Execute();

I am having WordPress issues it will not let me post put the HTML code; you will have to trust me that it works.

Conclusion

Writing to the Glass Time-line is very easy with C#.   GitHub project with slightly confusing directory structure can be found at LindaLawton/Google.MirrorAPI.dotnet


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

13 thoughts on “Mirror API With C#

  • ssc

    Hello ,

    I need to create a solution by using google analytics real time api using c#. Earlier i did the same for the google analytics core reporting api by using another tutorial . For real time api i followed https://github.com/LindaLawton/Google.MirrorAPI.dotnet but unable to get authenticated.
    Please help me on this by creating a solution by using Google analytics real time api using C# by step by step process…:)
    My required dimensions and metrics is for Page Tracking and App Tracking.
    KIndly help on this….

      • ssc

        Thanks for your quick reply,

        Actually i filled the above link and got the necessary credentials, Please help me to create a solution and by using the username and password like the below mentioned urls. By using the links – http://www.reimers.dk/jacob-reimers-blog/added-google-analytics-reader-for-net and http://www.thecyberwizard.com/index.php/5/google-analytics-api-in-c-part-1/ .
        In the above urls, they just used the username and password. Please help me on this.

          • ssc

            Ok my requirment is i have to use this as a dll or directly i have use the code in ssis packages and automated with sql job with the ssis package. But if you go through Oauth2 process, it will pop up with oauth2 window right, so in the sql job i dont want to pop up this window hence the job is failed. This is my requirement. Please share your ideas on this.

          • Linda Lawton

            I have a custom connection manager that makes the authentication request, the custom connection manager then saves my refresh token. Then i have a custom data-source reader that uses the custom connection manager to connect to Google Analytics. When the custom connection manager is created / added to the SSIS package yes it popups up and asks the user for authentication. It wont do it again after that because it has its refresh token.

            Note: You will not be able to use the Google-dot-net client lib to create your dll as they are unsigned. You will have to make all of the calls manually. Welcome to SSIS Oauth2 fun 🙂

            But i wonder what your plan is with this, you are only going to be able to write to the timeline of the person that authenticated it in the package. What are you trying to write and to who?

    • Linda Lawton

      Creating custom SSIS tasks is not easy and creating one that works with Oauth2 is even more so because you have to understand enough about how the Google Oauth2 flow works to be able to send the requests yourself with out the help of a client library. You also have to know enough about the API in question to be able to send those requests without the help of a Client Library. Because of this I have decided not to create a tutorial for creating custom SSIS tasks.

      I do offer a consulting service, if you could use my help with this small project. Email me if you would like a quote.

  • ssc

    I need to get the data from google analytics real api using c# or vb, then i have to automated with this in ssis packages and run this packages using sql job.

  • Harald G

    I’m having problems running your example. After the authentication code, I am left with an open browser window saying that there is a problem with the redirect URI.

    “400. That’s an error.
    Error: redirect_uri_mismatch

    The redirect URI in the request, http://localhost:62371/authorize/, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/xxxxxxxxxxxx.apps.googleusercontent.com?project=xxxxxxxxxxxx to update the authorized redirect URIs.”

    I guess I could just add localhost as an authorized URI, but the port number keeps changing for every run.
    But the thing that really bothers me is that I can’t seem to find out where exactly “http://localhost:[port]/authorize/” comes from, nor a way to override it.

    Could you perhaps shed some light on this mystery?

      • Harald G

        You are 100% correct!
        I’ve been struggling with updating the (deprecated) .NET version of the Mirror API example from GitHub to a working state again.
        The Mirror part of the example was somewhat easy to fix (I think), but I’m having problems with the oAuth part.
        And when I stumbled upon your code, I just copy/pasted my client ID and secret without thinking about local vs web.

        Thank you very much for making this example, it’s very useful for novices who want to create small but functional apps for his or her own use!