Is it possible to post windows form Hit info to Google analytics(track id) using Gdata API C#

假如想象 提交于 2019-12-10 23:52:57

问题


May be this is a very dumb question to many.

I have created a Google analytics a/c with a valid track id. Now I have put the javascript code provided by Google analytics to my *.aspx files and could see my Website hit information in Google analytics site.

Now can I do same from a Windows form application?

I tried simple Http post to GA site but failed. I referred following link: https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#overview

Then I came across GData API. https://code.google.com/archive/p/google-gdata/
I have installed GData but not sure how to send Windows form application hit information to Google analytics.


回答1:


Its not a dumb question. yes you can send data to Google analytics using the measurement protocol. You can do it with any language that supports HTTP Posts or HTTP Gets.

The Gdata library is for requesting data from Google analytics and really shouldn't be used, because its old and you should use the newer apis v3 or v4 for requesting data from Google Analytics.

There are a few third party SDKs for the measurement protocol for .net out there personally I didn't like any of them and made my own I haven't released it yet. I plan on doing it soon it will be open sourced.




回答2:


Now after a bit of online search, I came across of the below link http://tilr.blogspot.com/2012/10/google-analytics-use-google-analytics.html

Tested. Works correctly. You need to provide valid GA track Id and winform name.

I have not yet changed other GA settings (unique visitorid, location etc.). May be I could help when I fully understand the methods and parameters.

Check this link: https://developers.google.com/analytics/resources/concepts/gaConceptsTrackingOverview#gifRequestClassification

or

Cause Google Analytics log from non-web application (eg. via WebClient)

or

http://www.analyticsmarket.com/blog/__utmgif-data for detailed information on the parameters.

Final working code from C# winform application:

///<summary>Send winform hit info to Google Analytic</summary>
///<param name="visitorID">Unique visitor id to be set once per session</param>
///<param name="timeStamp">timestamp to be set once per session</param>
///<param name="formName">Name of the winform</param> 

public static void PostFormDataToGA(int visitorID, long timeStamp, string formName)
    {
        //#if !DEBUG
        //visitor ID I am creating at the application start up for first time and saving it in registry. Read it from registry for subsequent uses.

        const string GA_TRACKING_ID = "UA-XXXXXXX-Y";

        Random randomNum = new Random();
        long timestampForFirstRun, timestampForLastRun, timestampForCurrentRun, numberOfRuns;

        timestampForCurrentRun = DateTimeOffset.Now.ToUnixTimeSeconds();//DateTime.Now.Ticks; //current timestamp

        string[,] temp = new string[1, 1];
        var rk = new ModifyRegistry(); // reading windows registry
        rk.SubKey = Utility.DS_REG_COMMON; //some path in registry

        //Unique timestamp to be set once per session. Else every subsequent form request will be counted as new user.
        temp[0, 0] = rk.Read(Constants.GA_NOOFRUNS); //Reading number of runs
        if (string.IsNullOrEmpty(temp[0, 0])) //On the first run of application after installation, registry values will be empty
        {
            numberOfRuns = 1; //if first run then make it 1
            timestampForFirstRun = timestampForCurrentRun; 
            timestampForLastRun = timestampForCurrentRun;
        }
        else
        {
            //On the subsequent application run, read values from registry
            numberOfRuns = Convert.ToInt64(temp[0, 0]) + 1;

            temp[0, 0] = rk.Read(Constants.GA_TIMESTAMPFORFIRSTRUN); 
            timestampForFirstRun = Convert.ToInt64(temp[0, 0]);

            temp[0, 0] = rk.Read(Constants.GA_TIMESTAMPFORLASTRUN);
            timestampForLastRun = Convert.ToInt64(temp[0, 0]);
        }

        var domainName = Environment.UserDomainName;
        //string domainHash = GenerateDomainHash(domainName);
        string domainHash = "123456789";
        string utmhid = "1943799692";
        string source = "DriveSize";
        string medium = "medium "; 
        //string sessionNumber = "1";
        //sessionNumber = 1; // numberOfRuns is used for this
        string campaignNumber = "1";
        string culture = Thread.CurrentThread.CurrentCulture.Name;

        string statsRequest = "http://www.google-analytics.com/__utm.gif" +
               "?utmwv=4.4" + //Tracking code version e.g. utmwv=1
                //+ visitorID +  //
               "&utmn="+ randomNum.Next(100000000, 999999999) +  //Unique ID generated for each GIF request to prevent caching of the GIF image. e.g. utmn=1142651215
               "&utmhn=hostname.mydomain.com" +
               "&utmcs=-" + //Language encoding for the browser. Some browsers don't set this, in which case it is set to "-"   utmcs=ISO-8859-1
               "&utmsc=-" + //Screen color depth    utmsc=24-bit
               "&utmul=" + culture + //Browser language.    utmul=pt-br
               "&utmje=-" + //Indicates if browser is Java-enabled. 1 is true.  utmje=1
               "&utmfl=-" + //Flash Version utmfl=9.0%20r48
               "&utmdt=" + formName + //Page title, which is a URL-encoded string.  utmdt=analytics%20page%20test -----
               "&utmhid=" + utmhid + //+ randomNum.Next(100000000, 999999999) + //1943799692" + //A random number used to link Analytics GIF requests with AdSense. utmhid = 2059107202
               "&utmr=0" + //Referral, complete URL.    utmr=http://www.example.com/aboutUs/index.php?var=selected
               "&utmp=" + "//" + //Page request of the current page.    utmp=/testDirectory/myPage.html
               "&utmac=" + GA_TRACKING_ID + //Account String.Appears on all requests.   utmac = UA - 2202604 - 2
               "&utmcc=" + //Cookie values. This request parameter sends all the cookies requested from the page.
                           //utmcc = __utma % 3D117243.1695285.22 % 3B % 2B __utmz% 3D117945243.1202416366.21.10.utmcsr % 3Db % 7C utmccn% 3D(referral) % 
                           //7C utmcmd% 3Dreferral % 7C utmcct% 3D % 252Fissue % 3B % 2B
               "__utma%3D" + domainHash + "." + visitorID + "." +
                   timestampForFirstRun + "." + timestampForLastRun + "." +
                   timestampForCurrentRun + "." + numberOfRuns +
               "%3B%2B__utmz%3D" + domainHash + "." + timestampForCurrentRun + "."
                   + numberOfRuns + "." + campaignNumber + ".utmcsr%3D" +
                   source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium +
              "%7Cutmcct%3D%2Fd31AaOM%3B";
        try
        {
            using (var client = new WebClient())
            {
                client.DownloadData(statsRequest); //post
            }
        }
        catch (Exception ex)
        {
            //Handle exception
        }

        //Saving number of runs and timestamp for next use.
        rk.Write(Constants.GA_NOOFRUNS, numberOfRuns.ToString());
        rk.Write(Constants.GA_TIMESTAMPFORFIRSTRUN, timestampForFirstRun.ToString());
        rk.Write(Constants.GA_TIMESTAMPFORLASTRUN, timestampForCurrentRun.ToString());
//#endif
}

Then I found some typical issue: My application is only for windows OS but in GA it shows the application is used from Linux and Mac. How is this possible. Answer to this is : sometime GA is hit by Spams hence showing irrelevant data

https://www.en.advertisercommunity.com/t5/Referral-Spam-Traffic/Google-Analytics-showing-wrong-country-and-Operating-system/td-p/507606#

http://help.analyticsedge.com/spam-filter/definitive-guide-to-removing-google-analytics-spam/

Some more links to understand the GA parameters better way:

http://www.analytics-ninja.com/blog/2011/08/how-google-analytics-calculates-visits.html http://www.lunametrics.com/blog/2011/10/04/utmgif-request-parameters/ http://blog.diniscruz.com/2013/01/creating-server-side-google-analytics.html



来源:https://stackoverflow.com/questions/36595299/is-it-possible-to-post-windows-form-hit-info-to-google-analyticstrack-id-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!