Last time, I built a simple app to get the number of visitors to a site using the Google Analytics API. So the obvious next step is to get that data displayed on a web page. The simplest way to do this would be to add some server-side code to an ASP.NET page. But if you’ve run the code in the previous blog entry, you’ll notice it’s pretty slow, generally taking over a second to get the data back from Google. Adding a second to every page load isn’t such a good idea, so this is my slightly more complicated solution, which loads up the hit count via AJAX.
First we need a generic handler, looking something like this
<%@ WebHandler Language="C#" Class="visitorCounter" %> using System; using System.Web; using Google.GData.Analytics; public class visitorCounter : IHttpHandler { public void ProcessRequest (HttpContext context) { AccountQuery feedQuery = new AccountQuery(); AnalyticsService service = new AnalyticsService("DoogalAnalytics"); service.setUserCredentials("email", "password"); DataQuery pageViewQuery = new DataQuery("https://www.google.com/analytics/feeds/data"); pageViewQuery.Ids = "ga:103173"; pageViewQuery.Metrics = "ga:visits"; pageViewQuery.GAStartDate = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd"); pageViewQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd"); DataEntry pvEntry = service.Query(pageViewQuery).Entries[0] as DataEntry; context.Response.ContentType = "text/plain"; context.Response.Write(pvEntry.Metrics[0].Value); } public bool IsReusable { get { return false; } } }
Then we just need a bit of jQuery magic to show it on the page.
<p> Visitors this month: <span id="visitorCount"></span> <script type="text/javascript"> $(document).ready(function () { $.get('visitorCounter.ashx', function (data) { $('#visitorCount').html(data); }); }); </script> </p>
With a little work this could probably be wrapped up as an ASP.NET control, but I’ll leave that as an exercise for the reader.
No comments:
Post a Comment