Google Analytics .Net SDK QuickStart 20


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);

[wp_ad_camp_3]
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.
[wp_ad_camp_5]

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.


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.

20 thoughts on “Google Analytics .Net SDK QuickStart

        • 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 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.

  • Shiva Kumar Samalla

    Dear Daimto,
    Thank you so much for help.
    Here, in your dll, in the following Google.Analytics.SDK.Core.Hits.CustomProperties namespace we have CustomDimenison class and its constructor has two parameters. Right now data is sent based on the Index position of CustomDimensions. Is there any way to send the data to CustomDimesions with names such as what we have created in Google Analytics, Because we have so many CustomDimension properties.Based on the Index position its making ambiguity to send data.

  • Shiva Kumar Samalla

    Dear Daimato,
    I need few clarifications on the data sent to google analytics reports.
    1.In PageViewHit method for Datasource property the data was set to “SHIVA”, but in google analytics reports its showing in lower case letters such as “shiva”. May I Know the reason why its showing in lower case letters?
    2. In CurrentLocalTimewe are sending the current system time. But in Behaviour tab we didn’t find any property named with CurrentLocalTime and the same for IpOverride ,User Id property also we didnt find in Behaviour-> Site Content ->All Pages.
    Request you to help me in this.

  • Shiva Kumar Samalla

    Dear Linda Lawaton,
    We are happy with library you have created and its working fine as we expected. Thank You So much for your support.
    We are facing one problem with Google Analytics. When we first created the TrackID UA-XXXXXXXX-1 for any google account, and post the data to google analytics, at the same instance we are getting results in Home tab. But when go to Behavior tab, All pages the report are not loading at the same instance for the first time. It taking hours of half day to Get the report in Behavior tab later once the report was update from next onwards we are getting the report in early.
    Madam Can u please help in that.
    Why its taking longer time to update the report for the first time?
    If you have any document or something related to this please share with me.
    Thank You

  • Nitish Vijai

    Hello Linda,

    Thank you so much for this! Do you know if this will work with UWP apps? Also, my tracking ID starts in the form of “G-XXXXX…”. Will this still work with the solution above.

    Please let me know soon.

  • Nitish Vijai

    Hello Linda,

    Could you please let me know how to get this working for UWP apps? I’ve tried this solution yet nothing shows up in the dashboard.
    Additionally, could you please let me know if there are other options for integrating Google Analytics into my app so I could evaluate them?

    Thank you!