Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

AdSense Account Stats UWP App Released

Introducing AdSenseAccountStats App

For all those AdSense account owners with Windows mobiles or tablets out there, I recently released a new UWP app that may come in handy. This simple app will allow you to quickly and easily check up on your AdSense performance.

Watch your monetization efforts pay off and your earnings grow

After logging in with your AdSense account and authorising the app for read-only access, you can easily see metrics such as:
  • Earnings Clicks, Cost Per Click
  • Page Views, Click Through Rate and RPM
  • Coverage

Code components that make it work

The app simply leverages Google APIs, specifically the AdSense Management API v1.4, and Google OAuth v2 for authentication of the user.  Basically, all calls to the AdSense APIs have to be authenticated or else they won't work.

So the first problem was to tackle Google OAuth v2 for a UWP app.  There are complexities around the Google provided libraries and support for UWP, and I have touched on these in another blog post.

OAuth v2 Authentication

The following code snippet deals with authentication successfully:

            UserCredential credential;
            try
            {
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { AdSenseService.Scope.AdsenseReadonly },
                        "user",
                        CancellationToken.None,
                        new PasswordVaultDataStore()
                        );
                }
            }
            catch (UwpCodeReceiver.AuthenticateException ex)
            {
                // Login failed or authorisation not granted
                credential = null;
                await LoginFailed(ex);
            }
            catch (Exception ex)
            {
                credential = null;
                await SomethingWrong(ex);
            }

Creating a client service for your API calls

Once the user has logged on and authenticated their AdSense account, and granted permissions to the app so it can access the user's AdSense details, you then create a client service to use for your API calls.  Pass the credential object created by the code above to the http initializer.

            var adSenseService = new AdSenseService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "AdSense Accounts Stats",
            });

Setting up and executing an API request

After the user has logged on and allowed access for the app, the next piece is to construct a valid API request, execute it and handle the response in a meaningful way.  This can be achieved along the following lines:

            var earningsRequest = adSenseService.Reports.Generate(startString, endString);
            earningsRequest.Dimension = dimensionString;
            earningsRequest.UseTimezoneReporting = true;
            earningsRequest.Metric = new List<string>{ "earnings","page_views","individual_ad_impressions","clicks",
                                                "page_views_ctr","individual_ad_impressions_ctr",
                                                "page_views_rpm","individual_ad_impressions_rpm","cost_per_click",
                                                "ad_requests_coverage" };

            var earningsResponse = await earningsRequest.ExecuteAsync();

Once you have that response object, you can use it in any way you see fit, for example use its member items as a list source etc.

Hope you enjoyed this post and if you like go grab the app from the Microsoft Store.

Cheers

MB



Google OAuth2 for UWP C# XAML Apps Example

I have previously posted on consuming Google YouTube APIs in UWP C# XAML apps, showing how to consume Google APIs using the API key technique for authentication.

That technique works well, but has its drawbacks.  Mainly, you can't access any of the non-public user specific information that the APIs expose.  In other words, to get to the juicy bits you need to make authenticated Google API calls.  To do that, you need to work out Google OAuth2 authorisation flows.

Now, that's easier said than done if you are a part time hack like myself, and not a serious developer.  Through lack of skill I need to rely on the dotnet API libraries that Google kindly provides.  There are a good number of blog posts out there that detail the API key method, but not many that have a working example for using Google OAuth2 as per Google's developers API reference samples..

This is where this post kicks in.  But it also comes with a disclaimer (see below).  The following code snippet is an actual working example for a Google API OAuth2 authentication flow.  It uses the Google provided libraries which can readily be downloaded from Nuget and implemented in your project in Visual Studio.  Just use the Nuget Package Manager and search available packages for Google.Apis.

The magic sauce here is that the good folk at Google have fixed the OAuth flow for UWP C# only in a beta release of their dotnet libraries.  Specifically version 1.31.0 beta 01.  In the package manager, make sure to tick the box to include pre-releases, or else you won't get the beta on the list of available packages.


And here is the disclaimer... the mainstream release - currently up to 1.32.0 - does NOT work.  The code will build but fail at run time.

Enough said.  Following is the example code that will manage your Google OAuth2 authentication flow for you.  It prompts the user to log in with a Google account, authorise our example App, access the user's AdSense account, grab a list of payments for the account and finally display the results as the items source on a XAML ListView. Sounds tough?  Not really, just a few lines of code 😃

Of course, instead of accessing the AdSense Management API we could access the YouTube Data API or any of the other Google APIs presumably. I have only tested AdSense and YouTube, though.

     private async void PopulateAdsenseList()
     {
         UserCredential credential;
         using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
         {
             credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                 GoogleClientSecrets.Load(stream).Secrets,
                 new[] { AdSenseService.Scope.AdsenseReadonly },
                 "user",
                 CancellationToken.None
                 );
         }
         var adSenseService = new AdSenseService(new BaseClientService.Initializer()
         {
             HttpClientInitializer = credential,
             ApplicationName = "Your App Name",
         });
         var myPayments = adSenseService.Payments.List().Execute();
         MyList.ItemsSource = myPayments.Items;
     }

Of course you will have to have a XAML page with a ListView (in this case called "MyList") to display the retrieved list of payments.

Just remember, don't be tempted to upgrade your Google.Api Nuget packages.  Stick with the 1.31.0. beta 01 release, or your code will break!  We'll have to wait until the devs at Google fix the libraries properly for UWP support.

Hopefully the above makes sense and you enjoyed reading this post.  If you have any questions or comments, why not drop me a line via email or comment below.

Cheers

MB


Consuming Google APIs In UWP XAML / C# Apps

Google APIs and UWP - How does it all work?

Out of curiosity and for my own education, I recently started to look into Google APIs and how a Universal Windows Platform (UWP) App could consume such web APIs.  Specifically, I wanted to hook the YouTube API to easily get access to basic YouTube channel statistic on my Windows phone.

But how to get started?  As usual one turns to Google for research, and I found there was plenty of material available to get started.

I quickly decided that I wanted to have a crack at actually creating a functional app rather than just do some dry research.  After all, applying the knowledge helps with understanding and retention, right? 

Furthermore, I was curious how hard it would be to actually then publish such a working app in the Windows store.  So I set about finding out, but that will be another post in itself.

Accessing Google APIs - Authentication is Key

There is a lot of material on the web on how to access the Google provided web APIs.  Fundamentally, calls to the Google APIs have to be authenticated. And as far as I can see, there are two options:
  1. Use an API Key
  2. Use OAuth2 Authentication
The first method is simple enough to get going, the second one not so easy when you are dealing with a UWP XAML / C# app.  The main reason for that is that the Google code samples and libraries for OAuth2 actually don't work for UWP C# yet.  While you can freely download the libraries and the code will successfully build, it actually fails at run time.

Google mentioned they would address this and fix their code libraries down the track, but there is no time frame from what I can gather.

Hence I concentrated on the first method of using an Authentication Key.  To get started set up an account and log into the Google Developers API Console.  Once in, click on Enable API which will land you on the Library page where you can pick which Google API to actually enable/allow.


In my case I selected the YouTube API for my app.

Then click on Credentials on the navigator on the left, followed by the Create Credentials button.  This will create an API Key and pop up a window containing your new key.  Be sure the restrict and secure that key so others can't steal your volume allocation. And of course don't publish that key in public code repositories by accident.


Needless to say the one in this screenshot is just for illustration purposes and no longer exists so don't bother copying it ðŸ˜‰.

Let's Get Coding - Visual Studio and Google Nuget Packages

I'm not a developer, so I'm not going to pretend I know exactly what I am doing, but for the purpose of this educational exercise it was simple enough to get going.

Grab Microsoft Visual Studio - the free Community Edition will do just fine - and start your XAML / C# UWP project.  I cheated and used the newly available UWP WindowsTemplateStudio project to create a basic, Windows Store compliant UWP app.

Next I downloaded the required Google API Nuget packages, in this case Google.Apis.YouTube.V3 and I think Google.Apis.Services.  I then cobbled together a XAML UI and a button to click to fetch and display basic YouTube Channel Statistics.



Next I put some code into the button click event handler in the page's code-behind.  It's along the lines of the following:


        private void button_Click(object sender, RoutedEventArgs e)
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "Your-API-Key-From-Google",
                ApplicationName = "BlazingTMYouTubeViewCounter"
            });

            var channelsListRequest = youtubeService.Channels.List("snippet,statistics");
            channelsListRequest.Id = "UCkW0h_mbdmo0YChc0fzMkQw";

            var channelsListResponse = channelsListRequest.Execute();

            foreach (var channel in channelsListResponse.Items)
            {
                var channelViewCount = channel.Statistics.ViewCount.Value;
                textBox1.Text = Convert.ToString(channelViewCount);
            }

            textBox.Text = this.GetType().ToString();
        }


Now that's nowhere near actually the final working code, but you get the drift. You create a new YouTubeService object (part of the Google API Nuget packages code), and set your ApiKey and optional ApplicationName property.

Then you create YouTubeService.Channels.List request object, set a default channel ID and execute the request.  And lastly you have to process the response and display the required values in the UI.

If you are a serious developer, you are probably laughing by now at my description, but hey that's okay.  This is just for illustration purposes.

In any case, I managed to build a basic UWP XAML / C# app which was working fine on my PC and Lumia 930 Windows mobile.

As mentioned earlier in this post, I actually also went on to publish the app in the Windows Store just to get familiar with the process.  If you are curious, search the Windows Store for an app called YouTubeChannelStats, download and install for fun.  Very basic but it works.

How all that was done will be the subject of another post some time.  Hope you enjoyed this one and feel free to comment and share.

Cheers

MB
Get it from Microsoft

Most Popular Posts