Google Analytics .Net SDK QuickStart 10


Please Share

Google AnalyticsAre you working on a .Net core console application. Have you been wondering how you can add Google Analytics tracking to your project. Well your in luck using the Google Analytics .Net sdk You can have Google analytics tracking added to your project in a matter of minutes.

Setup

For this project I recommend creating a mobile Google Analytics account. Unfortunately Google thinks that all Google Analytics mobile accounts should be routed though Firebase. We don’t want to do that, so here is the work around. In Google Analytics create a property and chooses type web. After you have done that go to the views tab and create a new view you can create one of type mobile here and not have it linked to firebase. Note your web property id it should look something like this UA-123456789-1 you will need it soon

NuGet Package

Create a new console application and add the NuGet package Google Analytics .Net sdk This will add everything you need to track your application.

Code

Screen view hit. With mobile google analytics accounts everything runs though screen hits. Before we can do that we need to create yourself a tracker. You only need one tracker, this tracker will be used to send hits to Google analytics from your application.

Tracker

Here is where you will need your web property id from Google analytics. As well as some basic information about your application.

private const string DemoDataApplicationWebProplerty = "UA-123456-1";
private const string Applicationname = "QuickStart core";
private const string ApplicationVersion = "1.0";
private const string ApplicationId = "1.0.0";
var tracker = TrackerBuilder.BuildMobileTracker(DemoDataApplicationWebProplerty, Applicationname, ApplicationVersion, ApplicationId);



You are now ready to track Google Analytics data.

Screen view hit

With mobile google analytics accounts everything runs though screen hits. So we will need to build yourself a hit

public static async Task SendAsync(ITracker tracker, string screenName)
        {
            var hit = new ScreenViewHit(screenName)
            {
                
                DataSource = "app",
            };

            // create the hit request.
            var request = (HitRequestBase)tracker.CreateHitRequest(hit);

            // Run a debug check to ensure its valid.
            var debugResponse = await request.ExecuteDebugAsync();
            if (!((DebugResult)debugResponse).IsValid()) return false;
            
            // Send hit.
            var collectRequest = await request.ExecuteCollectAsync();
            Console.Write(collectRequest.RawResponse);
            return true;
        }

There are two different end points we can send to with the measurement protocol. The first is the debug endpoint which allows us to check that our request is correct before actually sending it to the collect endpoint. The debug end point does not log data to Google analytics its just here to tell use if its a valid hit. Also the debug endpoint is not perfect you can get a false positive.

The collect endpoint is the end point that actually registers hits to Google analytics. The collect end point does not return an error if there is anything wrong with your hit.

Putting it all together

Here we build our tracker and then send a hit to google analytics.

 class Program
    {
        private const string DemoDataApplicationWebProplerty = "UA-53766825-1";
        private const string Applicationname = "QuickStart core";
        private const string ApplicationVersion = "1.0";
        private const string ApplicationId = "1.0.0";

        public static async Task Main(string[] args)
        {
            Console.WriteLine("Hello Google Analatics SDK!");
            var tracker = TrackerBuilder.BuildMobileTracker(DemoDataApplicationWebProplerty, Applicationname, ApplicationVersion, ApplicationId);
            
            if (!await ScreenViewHitHelper.SendAsync(tracker, "QuickStartMain"))
            {
                Console.WriteLine("Send Hit Failed");
                return 1;
            }

            Console.WriteLine("Hit Sent");
            return 0;
        }
    }

GitHub Sample Project

The sample project for this and all the other Quick starts for the Google Analytics .net SDK can be found on Github Google.Analytics.SDK.QuickStarts

Conclusion

Sending hits to Google analytics from a .net console application is quite strait forward using the Google Analytics .Net sdk

You can have a little fun with this code and run it in a for loop.

Please Share


Linda Lawton

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 Reply to Shiva Kumar Samalla Cancel reply

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.

10 thoughts on “Google Analytics .Net SDK QuickStart

        • Linda Lawton
          Linda Lawton Post author

          You might want to read the note on microsofts library dotnet / windows-sdk-for-google-analytics

          This repo is archived. A .NET Standard-based version is maintained by @LindaLawton here.

          Microsoft isnt supporting theirs anymore they are recommending you use mine.

          Unfortunately neither microsoft nor Google wants to be responsible for maintaining a .net Google analytics tracker that’s why i have created one. Its your choice if you use it or not this is as official of one that you are going to get. I can talk to the team at google next week to see about getting them to back it but i dont think they are going to be willing to take it over as its Google.

      • Shiva Kumar Samalla

        Thanks Linda Lawaton for your replay.
        The Nuget package you have created was meeting my requirement and thanks a lot for support.
        But my client want to use “Google.Apis.Analytics.v3” (https://www.nuget.org/packages/Google.Apis.Analytics.v3/1.42.0.1720) dll provided.
        My requirement by using C# .Net code is there any possible way to post(hit) the data to Google Analytics by using this “Google.Apis.Analytics.v3” nuget package to track user activity for my windows application using.
        My self I didn’t find any method in the dll.

        If so, can you help me in that how use achieve my requirement.

  • Shiva Kumar Samalla

    Hello Daimto,
    Thank You so much for your previous replay and support and I feel great pleasure to work with you.
    We are using your dll for our Google Analytics. My requirement was we have a Windows application on clicking of any page(tab) we are making async method call to hit your dll from our application. So that user can perform his regular work without any performance impact.
    I just want to know what is the use of ExecuteDebugAsync() in the below method.
    public static bool SendPageViewHit(ITracker tracker, PageViewHit hit)
    {
    var request = (HitRequestBase)tracker.CreateHitRequest(hit);
    var debugResponse = Task.Run(() => request.ExecuteDebugAsync());
    debugResponse.Wait();
    var response = (DebugResult)debugResponse.Result;
    if (!response.Response.hitParsingResult.FirstOrDefault().valid) return false;
    var collectRequest = Task.Run(() => request.ExecuteCollectAsync());
    collectRequest.Wait();
    return true;
    }
    1. Is it necessary to validate data all the time with ExecuteDebugAsync() async call?
    2. I observed that by commenting ExecuteDebugAsync() method, this method ExecuteCollectAsync() is posting all data to Google analytics. Is all the data will be posted or not? Can you please confirm the same.
    3. Because if I use ExecuteDebugAsync() this method my application taking more time lo load the page than normal time.
    Our main mission is without any application performance impact, we want to track the user activity for my windows application.

    public static bool SendPageViewHit(ITracker tracker, PageViewHit hit)
    {
    var request = (HitRequestBase)tracker.CreateHitRequest(hit);
    //var debugResponse = Task.Run(() => request.ExecuteDebugAsync());
    // debugResponse.Wait();
    //var response = (DebugResult)debugResponse.Result;
    //if (!response.Response.hitParsingResult.FirstOrDefault().valid) return false;
    var collectRequest = Task.Run(() => request.ExecuteCollectAsync());
    // collectRequest.Wait();
    return true;
    }

    Finally my code looks like above.
    Can I proceed with the above. Madam, Please confirm me.
    May I Know the use of above commented lines.

    • Linda Lawton
      Linda Lawton Post author

      To be clear this is an open source project which i work on in my spare time. If you need support for commercial use then i do offer consulting service you can contact me through the contact for if that would interest you.

      1. Is it necessary to validate data all the time with ExecuteDebugAsync() async call?

      I would validate it once during development

      I observed that by commenting ExecuteDebugAsync() method, this method ExecuteCollectAsync() is posting all data to Google analytics. Is all the data will be posted or not? Can you please confirm the same.

      Debug data posts to the debug endpoint the debug endpoint validate the request it does not submit the request for collection.

      Because if I use ExecuteDebugAsync() this method my application taking more time lo load the page than normal time.

      I will log it as an issue and check the next time if i can find a reason why debug would take longer to load. Shouldn’t really be a problem as again you should only be using this in development.

  • Shiva Kumar Samalla

    Hello Daimto,
    Thanks so much for your support and we are using yours dll for our application. It is simple and easy to use.
    Basically we are having .Net Windows application and track the user activity. So,when we were creating a new Google Analytics Account.. in Step2 asking to select any of the 3 measurements options.Which measurements suits us either Web (or) Apps (or) Apps &Web for my windows application.