关于c#:Google Analytics(分析)移动版网站无法跟踪数据

Google Analytics for Mobile Websites not tracking data

有人遇到过这个问题吗?

我们有一个无法使用基于JavaScript的Google Analytics(分析)跟踪的移动网站,因此我们必须使用以下解决方案:http://code.google.com/mobile/analytics/docs/web/#asp

但是,最近几天似乎没有记录任何数据。

这是使用的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class GoogleAnalyticsHelpers
{
    public static String GetTrackingImageUrl()
    {
        StringBuilder url = new StringBuilder();
        url.Append("/ga.aspx?");
        url.Append("utmac=").Append(Configuration.GoogleAnalyticsKey());

        Random randomClass = new Random();
        url.Append("&utmn=").Append(randomClass.Next(0x7fffffff));

        String referer ="-";
        if (HttpContext.Current.Request.UrlReferrer != null &&"" != HttpContext.Current.Request.UrlReferrer.ToString())
        {
            referer = HttpContext.Current.Request.UrlReferrer.ToString();
        }
        url.Append("&utmr=").Append(HttpUtility.UrlEncode(referer));

        if (HttpContext.Current.Request.Url != null)
        {
            url.Append("&utmp=").Append(HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
        }

        url.Append("&guid=ON");

        return url.ToString().Replace("&","&");
    }
}

在ga.aspx页面中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<%@ Page Language="C#" ContentType="image/gif"%>
<%@ Import Namespace="System.Net"%>
<%@ Import Namespace="System.Security.Cryptography"%>
<script runat="server" language="c#">
  /**
    Copyright 2009 Google Inc. All Rights Reserved.
  **/


  // Tracker version.
  private const string Version ="4.4sa";

  private const string CookieName ="__utmmobile";

  // The path the cookie will be available to, edit this to use a different
  // cookie path.
  private const string CookiePath ="/";

  // Two years in seconds.
  private readonly TimeSpan CookieUserPersistence = TimeSpan.FromSeconds(63072000);

  // 1x1 transparent GIF
  private readonly byte[] GifData = {
      0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
      0x01, 0x00, 0x01, 0x00, 0x80, 0xff,
      0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
      0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
      0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
      0x02, 0x44, 0x01, 0x00, 0x3b
  };

  private static readonly Regex IpAddressMatcher =
      new Regex(@"^([^.]+\\.[^.]+\\.[^.]+\\.).*");

  // A string is empty in our terms, if it is null, empty or a dash.
  private static bool IsEmpty(string input) {
    return input == null ||"-" == input ||"" == input;
  }

  // The last octect of the IP address is removed to anonymize the user.
  private static string GetIP(string remoteAddress) {
    if (IsEmpty(remoteAddress)) {
      return"";
    }
    // Capture the first three octects of the IP address and replace the forth
    // with 0, e.g. 124.455.3.123 becomes 124.455.3.0
    Match m = IpAddressMatcher.Match(remoteAddress);
    if (m.Success) {
      return m.Groups[1] +"0";
    } else {
      return"";
    }
  }

  // Generate a visitor id for this hit.
  // If there is a visitor id in the cookie, use that, otherwise
  // use the guid if we have one, otherwise use a random number.
  private static string GetVisitorId(
      string guid, string account, string userAgent, HttpCookie cookie) {

    // If there is a value in the cookie, don't change it.
    if (cookie != null && cookie.Value != null) {
      return cookie.Value;
    }

    String message;
    if (!IsEmpty(guid)) {
      // Create the visitor id using the guid.
      message = guid + account;
    } else {
      // otherwise this is a new user, create a new random id.
      message = userAgent + GetRandomNumber() + Guid.NewGuid().ToString();
    }

    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] messageBytes = Encoding.UTF8.GetBytes(message);
    byte[] sum = md5.ComputeHash(messageBytes);

    string md5String = BitConverter.ToString(sum);
    md5String = md5String.Replace("-","");

    md5String = md5String.PadLeft(32, '0');

    return"0x" + md5String.Substring(0, 16);
  }

  // Get a random number string.
  private static String GetRandomNumber() {
    Random RandomClass = new Random();
    return RandomClass.Next(0x7fffffff).ToString();
  }

  // Writes the bytes of a 1x1 transparent gif into the response.
  private void WriteGifData() {
    Response.AddHeader(
       "Cache-Control",
       "private, no-cache, no-cache=Set-Cookie, proxy-revalidate");
    Response.AddHeader("Pragma","no-cache");
    Response.AddHeader("Expires","Wed, 17 Sep 1975 21:32:10 GMT");
    Response.Buffer = false;
    Response.OutputStream.Write(GifData, 0, GifData.Length);
  }

  // Make a tracking request to Google Analytics from this server.
  // Copies the headers from the original request to the new one.
  // If request containg utmdebug parameter, exceptions encountered
  // communicating with Google Analytics are thown.
  private void SendRequestToGoogleAnalytics(string utmUrl) {
    try {
      WebRequest connection = WebRequest.Create(utmUrl);

      ((HttpWebRequest)connection).UserAgent = Request.UserAgent;
      connection.Headers.Add("Accepts-Language",
          Request.Headers.Get("Accepts-Language"));

      using (WebResponse resp = connection.GetResponse()) {
        // Ignore response
      }
    } catch (Exception ex) {
      if (Request.QueryString.Get("utmdebug") != null) {
        throw new Exception("Error contacting Google Analytics", ex);
      }
    }
  }

  // Track a page view, updates all the cookies and campaign tracker,
  // makes a server side request to Google Analytics and writes the transparent
  // gif byte data to the response.
  private void TrackPageView() {
    TimeSpan timeSpan = (DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime());
    string timeStamp = timeSpan.TotalSeconds.ToString();
    string domainName = Request.ServerVariables["SERVER_NAME"];
    if (IsEmpty(domainName)) {
      domainName ="";
    }

    // Get the referrer from the utmr parameter, this is the referrer to the
    // page that contains the tracking pixel, not the referrer for tracking
    // pixel.
    string documentReferer = Request.QueryString.Get("utmr");
    if (IsEmpty(documentReferer)) {
      documentReferer ="-";
    } else {
      documentReferer = HttpUtility.UrlDecode(documentReferer);
    }
    string documentPath = Request.QueryString.Get("utmp");
    if (IsEmpty(documentPath)) {
      documentPath ="";
    } else {
      documentPath = HttpUtility.UrlDecode(documentPath);
    }

    string account = Request.QueryString.Get("utmac");
    string userAgent = Request.UserAgent;
    if (IsEmpty(userAgent)) {
      userAgent ="";
    }

    // Try and get visitor cookie from the request.
    HttpCookie cookie = Request.Cookies.Get(CookieName);

    string visitorId = GetVisitorId(
        Request.Headers.Get("X-DCMGUID"), account, userAgent, cookie);

    // Always try and add the cookie to the response.
    HttpCookie newCookie = new HttpCookie(CookieName);
    newCookie.Value = visitorId;
    newCookie.Expires = DateTime.Now + CookieUserPersistence;
    newCookie.Path = CookiePath;
    Response.Cookies.Add(newCookie);

    string utmGifLocation ="http://www.google-analytics.com/__utm.gif";

    // Construct the gif hit url.
    string utmUrl = utmGifLocation +"?" +
       "utmwv=" + Version +
       "&utmn=" + GetRandomNumber() +
       "&utmhn=" + HttpUtility.UrlEncode(domainName) +
       "&utmr=" + HttpUtility.UrlEncode(documentReferer) +
       "&utmp=" + HttpUtility.UrlEncode(documentPath) +
       "&utmac=" + account +
       "&utmcc=__utma%3D999.999.999.999.999.1%3B" +
       "&utmvid=" + visitorId +
       "&utmip=" + GetIP(Request.ServerVariables["REMOTE_ADDR"]);

    SendRequestToGoogleAnalytics(utmUrl);

    // If the debug parameter is on, add a header to the response that contains
    // the url that was used to contact Google Analytics.
    if (Request.QueryString.Get("utmdebug") != null) {
      Response.AddHeader("X-GA-MOBILE-URL", utmUrl);
    }
    // Finally write the gif data to the response.
    WriteGifData();
  }
<% TrackPageView(); %>

有没有人遇到这个问题? 我在哪里可以找出为什么什么都没有追踪到? 最近几天仅跟踪了2次访问。 FWIW,该网站在Google Analytics(分析)中的状态确实带有绿色的复选标记,并且工作正常。

谢谢你提供的所有帮助!

更新:更多信息:

看来它正在追踪为1个人。 所有的视图都在那里(即正在跟踪页面视图)。 我想知道是否是因为Web服务器正在提供图像?


我查看了我们应用的Google Analytics(分析)页面设置,然后依次浏览设置,状态,高级,然后将单选按钮更改为移动网站。 从那里开始,看来我们要为移动网站应用程序使用不同的帐号! 即,必须将UA替换为MO,而不是通常的基于UA的帐号。 那应该解决它!