Sunday, February 22, 2009

Google Analytics WebControl for ASP.NET

Tonight I’ll provide a Quick Useful WebControl in order to add Google Analytics Feature to your ASP.NET WebSite.

This WebControl allow you to choose between the 2 different Analytics Mode :

  • Analytics GA
  • Analytics Urchin

Here is the Code :

[DefaultProperty("Text")]
[ToolboxData("<{0}:GoogleAnalytics runat=server>")]
public class GoogleAnalytics : Control
{
#region Inner Enum

public enum AnalyticMode
{
Urchin,
GA
}

#endregion

#region Public Properties

public String UACode
{
get { return ViewState["UACode"] as String; }
set { ViewState["UACode"] = value; }
}
public AnalyticMode GMode
{
get { return (AnalyticMode)ViewState["Mode"]; }
set { ViewState["Mode"] = value; }
}

#endregion

#region Protected Overrides Methods

protected override void Render(HtmlTextWriter output)
{
switch (GMode)
{
case AnalyticMode.GA:
output.Write(GetGAString());
break;
case AnalyticMode.Urchin:
output.Write(GetUrchinString());
break;
default:
output.Write(GetGAString());
break;
}
}

#endregion

#region Private Methods

private String GetUrchinString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("");
sb.AppendLine("");
return sb.ToString();
}

private String GetGAString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("");
sb.AppendLine("");
return sb.ToString();
}

#endregion
}

Sample Usage :


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Sb2.Web.Tests._Default" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>
<Sb2:GoogleAnalytics ID="analytics" runat="server" GMode="GA" UACode="XXXXX" />
div>
form>
body>
html>


Source : http://blog.sb2.fr/post/2008/12/21/Google-Analytics-WebControl-for-ASPNET.aspx

No comments:

Post a Comment