Reputation: 379
I have a cookie bar that install a cookie called "CookiePolicy" to store user preferences (value = 1 states for OK, of course).
I need to use this value to activate/deactivate Google Analytics from my site. I thought it was easy... but it's a real mess! :(
My code
<script runat="server">
protected void Page_Load(object sender, EventArgs e) {
HttpCookie cookie = Request.Cookies.Get("CookiePolicy");
if( cookie.Value != "1" ){
Response.Write("<script>");
Response.Write("function (i, s, o, g, r, a, m) {");
Response.Write("i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {");
Response.Write("(i[r].q = i[r].q || []).push(arguments)");
Response.Write("}, i[r].l = 1 * new Date(); a = s.createElement(o),");
Response.Write("m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)");
Response.Write("})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');");
Response.Write("ga('create', 'UA-xxxxx-x', 'auto');");
Response.Write("ga('send', 'pageview');");
}
}
</script>
I receive all kind of errors. What's wrong??
The worst of them... System.NullReferenceException: Object reference not set to an instance of an object. (issued by the if clause)
Upvotes: 0
Views: 32
Reputation: 1791
Please try this:
HttpCookie cookie = Request.Cookies["CookiePolicy"];
For checking for null
if (cookie == null) {
Response.Write("Cookie not found.");
}
Reference: http://www.informit.com/articles/article.aspx?p=25045&seqNum=4
Upvotes: 1