65.9K
CodeProject is changing. Read more.
Home

Fetch Data from Google Analytics Service

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jul 14, 2011

CPOL

1 min read

viewsIcon

25484

Fetch Data from Google Analytics Service

Google analytics is a service where all our website statistics stored at Google server. If we want get the reports like TopPages viewed in my website, Top cities my website viewed, Top zip codes, Average time spent on my website, etc., this solution will be very helpful. The main aim of the solution is how to get data from Google Analytics Server.

Using the Code

To install the solution in your current project:

  1. Download the .cs file
  2. Add into your project
    • Add the following application settings to the web.config file.
    <add key="AnalyticsUrlSite" value="http://www.example.com"/>
    <add key="uName" value="Username"/>
    <add key="pwd" value="Password"/>
    <add key="dFeedUrl" value="https://www.google.com/analytics/feeds/data"/>
    <add key="google_map_api_key" value="Get your website key from google map api"/>
    • Once you configure the settings, now we can utilize the service in our application.

How does the code actually work?

The code is nothing but a simple service, which requests the data from Google analytics service. First when we send out user credentials to the service, it will fetch the account profile data from the service. Once we got the profile id, then we can send requests to the service for top pages, top visits, etc. The Google service will returns the value as a collection of DataEntry objects. Once we got the return collection, we can manipulate the data as per our reporting manner.

What is going on inside the code snippets?

//Instantiate the service request
GoogleAnalyticsResult objGA = new GoogleAnalyticsResult(ConfigurationManager.AppSettings["AnalyticsUrlSite"].ToString());
//Fetch the data from the date
var dtStartdate = DateTime.Now.AddMonths(-1);
//Fetch the data till
var dtEnddate = DateTime.Now;

objGA.RefreshFeed(dtStartdate, dtEnddate, strUsersitename);

//Get the unique number of visitors based on country
objGA.GetUniqueVisitorsByCountry(strCountry);

//Average time spent on website
objGA.GetAverageTimeSpentOnWebsite();

//Top zip codes by country wide
objGA.GetTopZipCodesByCountryWide(strCountry, 3);

//Top citied by country wide
objGA.GetTopCitiesByCountryWide(strCountry, 3);

//Top pages viewed.
objGA.GetTopPages(3);

Points of Interest

I have learned a new thing about the Google metrics and dimensions to fetch specified data related to me. At the start, it will be a bit difficult for everybody to understand what are metrics and dimensions. This solution contains only frequent methods used in the routine. But this will gives a heads-up on how to fetch the data from the service. For more information about the Google metrics and dimensions, please visit the link.