AKA Marketing.com Logo            VISIT THE BLOG            

Blogged thoughts, is our web blog. Expect views, opinion, rants and tirades about everything and anything 

« Home / Forums »        

 


Subscribe to our SEO / IT related blog by entering your email address below

Blogged thoughts

| by the www.akamarketing.com team



Introducing Google Analytics API with asp.net / C#

Recently Google released it’s Google Analytics API into public beta, which means any old joe soap developer can give it a go without having to apply. Despite the fact I didn’t apply for the private beta I’ve been looking forward to this API for a long time… I know, I know get a life. Seriously though this opens the door to some pretty tight integration between web / mobile / desktop apps and analytical data, the possibilities are endless.

Google Analytics Data Export API
The API is easy to use and works with standard HTTP requests which return XML feeds so you can use it from any programming language. I’m going to explore the API more over the next while but I’ve used it below to pull the top 20 content items from an Analytics profile along with pageView counts for each.

Before you dive in please have a look over the developer guide but the Protocol page in particular.

http://code.google.com/apis/analytics/docs/gdata/gdataDeveloperGuide.html
http://code.google.com/apis/analytics/docs/gdata/1.0/gdataProtocol.html

Using the Analytics API mostly centers around 3 key tasks which include Authentication, Account Authorization Query and finally profile Query. Account Authorization Query is not required if you know the numeric ID of the account/profile combo you need to access. All these steps include (in a nutshell) loading a webpage and examining the response for what you need. I’ll go through these steps with code later on but here’s a plain english overview of what’s involved first.

Authentication

You need to tell Google which user your app is representing/requesting data for. Google offers three ways to authenticate your app for access to a certain Google Analytics profile. These are AuthSub, OAuth and ClientLogin.

AuthSub means Google manages the entering of the username/password of the account you want to work with. This will be reassuring to a lot of people as they login via Google.com and your app will get access to only the services they explicitly approve (in this case Google Analytics). Drawback is you lose a bit of control and Google displays nasty warning messages of differing severity depending on a number of things.

OAuth is kind of an open standard version of AuthSub which can be used for authorising the use of data in many apps (not just Google ones). A security certificate corresponding to your app must be uploaded to use it.

ClientLogin on the other hand is more traditional and requires your app to request username/password from the user or manually define (perhaps in the web.config file) it if it is static. If it is static and your working with the same account (your or your clients account) all the time this is not a problem but if your application works with arbitrary accounts, users of those accounts may be uneasy about giving you their Google login details as you might use it in an unethical way or store it stupidly and later be hacked. Additionally when they give your app their user/pass combo they are giving you access to their entire range of Google services which they use (not just Google Analytics).

Therefore depending the type of app your building one authentication mode may be more appropriate than the others. I’ve written C# code which utilizes both AuthSub and ClientLogin authentication which I’ll step through later but if you want to read more about OAuth please visit OAuth Authentication for Web Applications

Account Authorization Query

After your app has ‘logged in’ (authenticated) you need to retrieve the profile ID of the account/profile combo which you want to query for certain data as this is required in the next step. If you intend querying the same profile(s) all the time then you can manually retrieve IDs for these profile(s) via the Google Analytics GUI, simply login and click the ‘Edit’ link listed beside all your website profiles, you will then see the ID listed on the next page. You can hardcode one or more profile IDs into your web.config if you like. If you will not know which website profiles your app will query ahead of time you must run an account query first from which Google will return all website profiles your authenticated user is authorised to work with.

Profile Query

When you are authenticated and have the ID of the profile you want to query you can then do just that, query. This step like the others before involves submitting a HTTP request (asking for a webpage). The response from that request is an XML feed with all the data you asked for. You define the data you want by configuring query params for your aforementioned HTTP request.

Step through - Top 20 page titles by pageview count for March 2009

OK lets actually see how to get our hands on some data. I’m going to grab the top 20 pages (by pageviews) for March 2009 and just output that data in plain text. A rough demo I put together is located at http://www.davecallan.com/analytics/, source code is available at the end of this post.

How to make a HTTP Request (with specified headers) with ASP.NET/C#?
The whole API is HTTP request based so you’ll need to know how to do this. I’m using the below method as a kind of helper when I need to interact with the API at all. The main classes of interest here are HttpWebRequest and HttpWebResponse (if anyone cares these are (roughly speaking) equivalent to using Curl in PHP). Both of these classes are located in the System.Net namespace.

public static string GArequestResponseHelper(string url, string token, mode mode)
{

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

 //will always be a token of some sort required in the header but the format
 //it is passed in will depend on what type of authorization is being used
 if (mode == mode.ClientLogin)
 {
     myRequest.Headers.Add(”Authorization: GoogleLogin auth=” + token);
 }
 else if (mode == mode.AuthSub)
 {
     myRequest.Headers.Add(”Authorization: AuthSub token=” + token);
 }

 //obviously you need some kind of try/catch here
 //but OK to bubble auth/connection failures up for demo
 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
 Stream responseBody = myResponse.GetResponseStream();

 Encoding encode = System.Text.Encoding.GetEncoding(”utf-8″);
 StreamReader readStream = new StreamReader(responseBody, encode);

 //return string itself (easier to work with)
 return readStream.ReadToEnd();

}

The above code requests ‘url’ and returns the response to the calling code. You’ll need to import System.Net, System.I0 and System.Text to use it. The Google Analytics API requires (well not always but mostly) authorization tokens to be included in headers which are sent along with requests to the API. An example of how an authorization key is included via HTTP headers when AuthSub or ClientLogin mode is used is also included above. You’ll notice the expected format of the Authorization header changes slightly based on what authentication mode your app is using.

How to authenticate (step 1 of possible 3) using AuthSub. (ClientLogin can be used here instead)
As outlined by Google on the Protocol page regarding AuthSub authentication:

AuthSub proxy authentication is used by web applications that need to authenticate users to Google Accounts. With AuthSub, the website operator and the client code never see the user’s username and password. Instead, the client obtains special AuthSub tokens which it uses to act on a particular user’s behalf.

To use this mode your app must first direct users (via a standard link) to the Google site to login securely. After logging in takes place Google will redirect users back to your app with a query param named ‘token’ embedded in the URL. Your app then in turn needs to upgrade this once off token for a session token, it does this yes you guessed it via a HTTP request.

Click on the ‘AUTHSUB REMOTE LOGIN’ link on http://www.davecallan.com/analytics/ to see what the process is like (notice the address bar when you get redirected back to my site). Notice also the structure of the link which directs users to the login page on Googles site in the first place. In my case it’s

https://www.google.com/accounts/AuthSubRequest?
&next=http://www.davecallan.com/analytics/default.aspx

&scope=https://www.google.com/analytics/feeds/
&secure=0
&session=1

The most important param here is ‘next’. It is used by Google after authentication to determine where to redirect the user to. Please read http://code.google.com/apis/analytics/docs/gdata/1.0/gdataProtocol.html#AuthSub for an explanation of the other params.

In terms of upgrading the once of token in the address bar to a longer term session token, well I’m using the method below for that

//used when you have authenticated on Google (via AuthSub & query params) & have a temp token
public static string getSessionTokenAuthSub(string tempToken)
{

string response = GArequestResponseHelper(”https://www.google.com/accounts/AuthSubSessionToken“, tempToken, mode.AuthSub);

 //temp (once off) token will have been exchanged for session token, return it
 return response.Split(’=')[1];

}

Following the API reference on the analytics developer site I know what URL to ask for. I also specify the authentication mode so the HTTP request/response helper method will know what format of header to include.

How to get a list of website profiles which authenticated user is allowed access (step 2 of 3).
This step is not needed if you know the ID of the profile you want to work with. The method I’m using is below

public static NameValueCollection getAccountInfo(string sessionToken, mode mode)
{

string response = GArequestResponseHelper(”https://www.google.com/analytics/feeds/accounts/default“, sessionToken, mode);

//response will contain an XML formatted string similar to
//http://code.google.com/p/ga-api-http-samples/source/browse/trunk/src/v1/accountFeedResponse.xml

//we need to convert it to proper XML for parsing
XmlDocument accountinfoXML = new XmlDocument(); accountinfoXML.LoadXml(response);

//each account/profile combo the current user is authorized for will have an ‘entry’ element
XmlNodeList entries = accountinfoXML.GetElementsByTagName(”entry”);

NameValueCollection profiles = new NameValueCollection();
for (int i = 0; i < entries.Count; i++)
{
    //profile name, profile ID - profile ID is needed for ID what data you want from the API
    profiles.Add(entries.Item(i).ChildNodes[2].InnerText,entries.Item(i).ChildNodes[7].Attributes["value"].Value);
}

return profiles;

}

Pass in the token (now a session token) aquired in the previous step. This method parses the XML response to get website profile name and profile ID which I have bound to a dropdownlist (see the demo) so the user can select the relevant profile to query (in the next step). You need System.XML namespace for the above to work.

How to actually query an account (step 3 of 3).
Authentication this, authorization that… it’s time to actually request and get some real data. Specifying what data you want is all done by configuring query params in the URL which you request from the Analytics API. The Retrieving Report Data section on the protocol page has a wealth of information (but there’s more to be had on other sections of the analytics developer site too) so get it open in another window if you haven’t already done so.

As before it’s all based around a HTTP request (asking for a webpage) so we’ll be using our friend GArequestResponseHelper again. The base request URL is https://www.google.com/analytics/feeds/data however we need to add a load of query string params to that URL to instruct Google what type of information we want. First I’ll show you the URL I have hardcoded (for the purposes of this demo only) which gets me the top 20 page titles by pageviews and then I’ll explain it somewhat. Please refer to the retrieving report data section linked to above for more.

https://www.google.com/analytics/feeds/data?ids=ga:202020
&metrics=ga:pageviews
&dimensions=ga:pageTitle
&sort=-ga:pageviews
&start-date=2009-03-01
&end-date=2009-03-31
&max-results=20

IDs is required and allows you to specify the profileID for the profile you want data for (you got this ID previously). The last four params should be fairly obvious. Metrics are the actual values you want to get hold off. In this case I’ve requested pageview counts. Dimensions relates to metric contexts or breakdowns (or cross sections) . Without dimensions specified the metric value reflects data in an Analytics account as a whole (1 aggregated value only) however if you specify that you want to see a metric (or metrics) broken down by a dimension, you get a breakdown of dimension->value combos. In this instance I don’t just want a count of total pageviews in an Analytics acccout, I want total page views for each (top 20) individual pagetitle in the account.

What’s returned from the API is completely dependent on what you ask for in the request parameters (assuming you have any data in the first place of course). An excerpt from the XML returned by the above request (on the Google Analytics website profile for akamarketing.com) is below:

<entry>
<id>http://www.google.com/analytics/feeds/data?ids=ga:459940&amp;ga:pageTitle=dynamic%20URL%20rewriter%20tool%20%7C%20mod%20rewrite%20tool%20%7C%20convert%20dynamic%20urls%20into%20static%20urls&amp;start-date=2009-03-01&amp;end-date=2009-03-31</id>
<updated>2009-03-30T17:00:00.001-07:00</updated>
<title type=’text’>ga:pageTitle=dynamic URL rewriter tool | mod rewrite tool | convert dynamic urls into static urls</title>
<link rel=’alternate’ type=’text/html’ href=’http://www.google.com/analytics’/>
<dxp:dimension name=’ga:pageTitle’ value=’dynamic URL rewriter tool | mod rewrite tool | convert dynamic urls into static urls’/>
<dxp:metric confidenceInterval=’0.0′ name=’ga:pageviews’ type=’integer’ value=’409′/>
</entry>
<entry>
<id>http://www.google.com/analytics/feeds/data?ids=ga:459940&amp;ga:pageTitle=Google%20Analytics%20-%20exclude%20your%20visits%20even%20with%20a%20dynamic%20IP&amp;start-date=2009-03-01&amp;end-date=2009-03-31</id>
<updated>2009-03-30T17:00:00.001-07:00</updated>
<title type=’text’>ga:pageTitle=Google Analytics - exclude your visits even with a dynamic IP</title>
<link rel=’alternate’ type=’text/html’ href=’http://www.google.com/analytics’/>
<dxp:dimension name=’ga:pageTitle’ value=’Google Analytics - exclude your visits even with a dynamic IP’/>
<dxp:metric confidenceInterval=’0.0′ name=’ga:pageviews’ type=’integer’ value=’389′/>
</entry>
               

Each dimension (pagetitle) is separated into ‘entry’ elements. In this case each ‘entry’ element has only one dimension and metric however sInce you can request multiple metrics and multiple dimensions in the same request this will not always be the case. You will therefore have to alter your XML parsing code depending on what exact data your requesting. It is important to note that not all metrics can be combined with all dimensions, some data relationships just don’t make sense. If you request a bad combination Google will throw a ‘bad request’ exception.

I’ve used AuthSub method for step 1 above. Step 2 and 3 above are the same regardless of which authentication mode is used. I won’t go through the ClientLogin mode much as it’s simple enough and the code is available & commented. Basically to use ClientLogin you need to POST username/password details to a specific URL (as defined in the API reference), if they are correct you will get back a session token which you will use exactly the same way as if the token had originated from AuthSub authentication.

I’ve put all code helper segments into a class called GoogleAnalytics for you to see the full source. It’s by no means production ready code, so please don’t comment me bringing that to my attention. If you want to see the full code for what’s located on http://www.davecallan.com/analytics then I’ve created an analytics.zip file which might be helpful. The code behind for the default page is quite simple and really just makes use of the static helper methods in the GoogleAnalytics class but if you’ve any questions let me know. The main thing for you, me & everyone else to do at this stage is to just play around with the new API and eventually I’m sure lots of excellent resources, tutorials and walkthroughs will appear to enable it to really take off.

If your not an ASP.Net developer heres some PHP resources about the new Analytics API
Similiar to this blog post only targetted towards PHP programmers
http://www.alexc.me/using-the-google-analytics-api-getting-total-number-of-page-views/74/

Using PHP & CURL to authenticate against ClientLogin
http://www.electrictoolbox.com/google-analytics-login-php-curl-username-password/

PHP Class for doing common API thing.
http://www.electrictoolbox.com/php-class-google-analytics-api/

60 Comments on “Introducing Google Analytics API with asp.net / C#”
1| Google Analytics for Umbraco - First installment « MC’s BLOG said,

[...] the .NET client library, this article is a good place to start for using the available api in C#: Introducing Google Analytics API with asp.net / C#. It could of course be implemented using javascript, but not sure how well it would fit into the [...]

2| Bart said,

Nicely done. Actually. I was trying my self. Nearly finished it and then found your post! Nice example

3| Jess said,

You website http://www.davecallan.com/ is down can you please send me the code

4| David Callan said,

Don’t think it’s down. There’s nothing on the homepage but demo is at http://www.davecallan.com/analytics/

5| Kim Jensen said,

That is very, very sweet! Thanks Dave!

6| luke said,

Great tutorial, will help me out a lot.

7| David Callan said,

Thanks folks, glad your liking the post. Any backlinks are appreciated :-)

8| Thomas said,

Hello,
would it be possible to publish the source of http://www.davecallan.com/analytics/ ?
I would like to use the implementation on a number of ASP.NET websites.
Best regards

Thomas Debray

9| David Callan said,

Code is very basic, it’s available through the zip mentioned above.

http://www.davecallan.com/analytics/analytics.zip

Rgds
Dave.

10| Sutanu said,

How to calculate Direct Traffic,Referring Sites,Search Engines,Home Page Bounce Rate using Google Analytics API with ASP.NET/C#?

11| Lukas Bart said,

Hi,

Thanks alot about this post.

A great help to begin develop in Google Analytics Export API.

Regards,
LB

12| Komweb said,

Hi Dave,

Great code, it’s really helping me along the way. I’m however a very newbie ASP developer, so I was wondering if you could give me some pointers:

1. How would I go about to manually define the login information for ClientLogin?
2. How do I manually define which profile/tableID for the script to pull data from?

I’m trying to create a static page with top content sorted by pageviews, which I can then pull an RSS feed from.

Kind Regards,
Siam

13| David Callan said,

Manually define data in the web.config file when you know what that data is ahead of time. There’s a setting in there called appSettings:

appSettings
add key=”analyticsLoginEmail” value=”siam@siam.com”
add key=”analyticsLoginPassword” value=”XXXXXXXXX”
appSettings

Put the angles in above yourself (wordpress takes angles out)

You can then access that data via configurationManager namespace as in :

string analyticsLoginEmail = ConfigurationManager.AppSettings["analyticsLoginEmail"].ToString();

Google for web.config and appSettings to know more.

14| Saurabh Pant said,

Hi dear,
Great code.Please tell me one more thing.
How can I retrieve pagePath, pageTitle and pageviews in a single request from google analytics account Content template.
Thanks

15| Obteniendo datos de Google Analytics con CSharp | Conocimiento compartido - Blog de César Nicola said,

[...] Fuentes: http://analytics.blogspot.com/2009_05_01_analytics_archive.html http://www.akamarketing.com/blog/103-introducing-google-analytics-api-with-aspnet-c.html http://code.google.com/apis/analytics/docs/gdata/1.0/gdataProtocol.html [...]

16| Dylan said,

Hi Dave.

Read your code. Its really helpful. But Im a newbie and im a bit lost in the coding. Im gonna use it for a statiscal desktop application. They dont want it via web. I hope you could help me out.

Dylan

17| David Callan said,

What part are you getting stuck on specifically? Have you parsed XML using C# before?

18| Dylan said,

Nope i havent. Ill study the code u gave first and try convert it to a desktop application. Ill get back to your forum. And email you my codes.

As an appreciation to your effort. And of course the credit is yours.

Thanks.

19| Cómo integrar Google Analytics en una web en .net | Raúl Carrión said,

[...] Y si necesitáis otros tipos de acceso hay mucha información en este tutorial de Akamarketing de donde he obtenido información para este [...]

20| Vishwanatha Rao said,

I am new to Google Health API. I want to build a sample app with H9. How can I request AuthSub Token using C# code? Can someone please give me sample code?

21| Raj said,

This is a nice post. It is really very helpful.
How to use Custom segment section?
I have two custom segments IsAdmin and IsValid.
I just required to use only IsAdmin.
I am trying with UserdefinedValue, the issue with me is I am getting all the custom defined values grouped by as
IsAdmin=1/IsValid=1,
IsAdmin=1/IsValid=0,
IsAdmin=0/IsValid=1 and
IsAdmin=0/IsValid=0.
Instead of this, I require only IsAdmin. I mean two rows.
Is there a way to group by IsAdmin.
Please let me know.
Thanks in Advance,
Raj

22| Raj said,

How to use filters for userDefinedValue(custom segments)?
We can filter city using
filters=ga:city%3D%3DIrvine
how to apply filters for userDefinedValue(ga:userDefinedValue)?
I have a user defined value “station”. I have to filter with station=”Manila”.
Can any one help me here?
Thanks in Advance,
Raj

23| Mitul said,

i need analytics.zip for .net 2.0, how can i get it?
please, help me

24| John Benjamin said,

Hey it was very helpful. Thanks. But i need a little more. I could not get the charts from google. Can you explain to me how i can get charts or images from my GoogleAnalytics account.

Best Regards

25| Franz said,

Dude! I owe you a six pack for that one! You just saved me a ton of time!

26| Carolus Holman said,

Is it possible to save the AuthSub Session Token and re-use at a later date and time. For instance I want the user to allow access to their GA account so out application can make daily request on their behalf. It seems as thought the session ends as soon as I stop debugging? When I read Googles documentation they make it seem as though the session is still going on their servers indefinitely.

27| Vasanth said,

hi
i am trying to use the api and somehow the pageviews displayed in the data and the page views displayed in the analytics website seems to be inconsistent. i get 96 as the numebr when the website shows 2000. any thing that ic ould be missing.

28| Vish said,

Hi, I have downloaded your sample code and have tried running it through Visual studio. The problem in the line myRequest.GetRequestStream() in function getSessionTokenClientLogin() is getting timedout with a socket exception with the message ( SocketException (0×274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 209.85.227.103:443]). When i used my google analytics account and password on your website ( top 20 visits) then it was able to access the analytics server and provide me the correct list of profiles. Can you help shed some light on why it is not working on my server? I am able to connect to internet from my machine using IE.

29| Sutanu said,

Hi,

Thanks alot about this post.
How to calculate Direct Traffic,Referring Sites,Search Engines,Home Page Bounce Rate using Google Analytics API with ASP.NET/C#?
Best Regards

30| Trilok Giri said,

I created new project and took Default.aspx, Default.aspx.cs and GoogleAnalytics.cs file in my new web project. I tried to run the application, it ask me creadential, after giving credential it fetch all website in dropdown. wheb I tried to click ‘Get Top 20 Content Items with Pageviews for March 2009′, I’m getting error like “The remote server returned an error: (400) Bad Request.” Please help me on this.

Thanks in Advance

31| Will said,

For Step 2/3, I recommend getting the node values by name instead of index. Google just changed around the order so the line:

profiles.Add(entries.Item(i).ChildNodes[2].InnerText,entries.Item(i).ChildNodes[7].Attributes["value"].Value);

..no longer works as profile ID is now index #6. I changed this to:

profiles.Add(entries.Item(i)["title"].InnerText, entries.Item(i).SelectSingleNode(”dxp:property[@name='ga:profileId']“, man).Attributes["value"].Value);

and now its working. Please correct my horrible coding here to get at the specific profileID node as im definitely not an expert on the matter.

The “man” variable above is the namespacemanager. If you want to use SelectSingleNode, you have to add the namespace:

XmlNamespaceManager man = new XmlNamespaceManager(accountinfoXML.NameTable);
man.AddNamespace(”dxp”, “http://schemas.google.com/analytics/2009″);

32| Daniel said,

When using the ClientLogin method at http://www.davecallan.com/analytics/ and when I puch the button Get Top 20.. I got a error; http://www.davecallan.com/analytics/.

Details:
Line 120: //obviously you need some kind of try/catch here
Line 121: //but OK to bubble auth/connection failures up for demo
Line 122: HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Line 123: Stream responseBody = myResponse.GetResponseStream();

Do you know the solution for this error?

33| Raj said,

I have tried your sample code and also the URL you given to test, both are throwing error, Can you help me out to fix this. thanks in advance

34| Dana said,

Hey David… When I started doing some research as to how to get Google Analytics stats into an ASP.NET, this was the first article I came across. (I think that Google might even have a link to you?) I eventually stumbled across this Google supported open source project:

http://code.google.com/p/google-gdata/

While the current release version (1.4.0.2) does not include support for Analytics, the Subversion truck does:

http://google-gdata.googlecode.com/svn/trunk/

In any case, definitely worth checking out for you or anybody else who reads this blog entry. Thanks for your help.

35| Bjorn van der Neut said,

Hello If I run your code on:
http://www.davecallan.com/analytics/

I can retreive the accounts but when I want to get the top 20 I get this error message:

The remote server returned an error: (400) Bad Request.
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

Is there something changed during your version and the API whats beeing called?

Thanks,
Bjorn

36| David Callan said,

Hi everyone, I have to update the code. The Google guys changed the API a little a couple of months after I wrote this blog post so that’s why some of yous are getting 400 errors - bad request. I”ll get to it as soon as possible.

37| Tim said,

Hi Guys the only way i got this to work with the interface was to change to the profile id instead of the account id, i think i might have picked up the new interface so excuse me if i’ wrong.

Just a qucik fix as it’s been ages since i have palyed with XML in .net i changed this

In the getAccountInfo sub

profiles.Add(entries.Item(i).ChildNodes(2).InnerText, entries.Item(i).ChildNodes(7).Attributes(”value”).Value)
Next

To

profiles.Add(entries.Item(i).ChildNodes(2).InnerText, entries.Item(i).ChildNodes(6).Attributes(”value”).Value)
Next

This returns the profile id instead of the account id, so might need some more code to bring out the account id, hope it helps.

Tim.

38| Henrik said,

Hi. I also has the problem with 400 error.
It would be great if you could help us.

Thanks,
Henrik

39| Henrik said,

Hi Again.
I Fixed the Error 400.

Change the line 84 in GoogleAnalytics.cs to …
profiles.Add(entries.Item(i).ChildNodes[2].InnerText,entries.Item(i).ChildNodes[6].Attributes["value"].Value);

Now the demo is working.

/Henrik

40| Ashok said,

David , Please Let Me know when you can get the updated code , i waiting eagerly , i need to integrate it.

41| jessy venus said,

if you changed the code can you sent it to me which property we must take please sent me codes

42| Sandy said,

Is there any update on code modification?

43| Alex Jayson said,

HELLO David ,this blog post was so helpful and fruity . i am wondering did you fix the error (400) bad request which occurs eveytime i try to get the report data . Hopefully you update it as soon as possible because i really need it .
thank you

44| Sandy said,

Hi Everyone, I got a fix in GoogleAnalytics.cs page to avoid rhe bad request
In the method getAccountInfo, while adding the Profile in collection,
Replace the code as
profiles.Add(entries.Item(i).ChildNodes[2].InnerText,entries.Item(i).ChildNodes[6].Attributes["value"].Value);
Here
I have changed the index in the second parameter from 7 to 6 to get the Profile ID but not the Profile account code

Happy coding
Regards,
Sandy

45| Milos said,

Hi Bjorn,

There was little changes in data feed parameters understanding. You were probably using profileID value (looks like ‘UA-xxxxxxx-x’) in “ids”-
parameter. But have to change “ids”-parameter
manually to value provided in web interface of Google Analytics (in
link https://www.google.com/analytics/reporting/?reset=1&id=xxxxxxx&pdr=20...
it is “id”-parameter’s value) and our script started to work properly
again!

46| sagi said,

is the 400 error fixed?? i realy want to use this code…

47| matt said,

add this to line 100 of GoogleAnalytics.cs to solve those (400)Bad Request Errors.
profileID = profileID.Split(’-')[1];

48| matt said,

with your code and a few others like it, I am able to retrieve the auth token just fine, but the request for the actual feed always comes back (401) unauthorized. I have checked to make sure im forwarding token in header. Ive tried on a live domain. I’ve tried on a live domain in a directory where Network Service has write permission. Do I need to set something in the analytics account?

49| Paul said,

David

Have you fixed the issues the other guys where getting yet ?

Thanks

Paul

50| Greg said,

You need to change this line…

profiles.Add(entries.Item(i).ChildNodes[2].InnerText, entries.Item(i).ChildNodes[7].Attributes["value"].Value);

To this…

profiles.Add(entries.Item(i).ChildNodes[2].InnerText, entries.Item(i).ChildNodes[6].Attributes["value"].Value);

It looks like they move the profile id location in the xml file.

51| Aman said,

I am also getting 400 errors - bad request
Did anybody figured it out? Thanks

52| David Callan said,

Thanks to all the people who noted that an index number needed to be changed in the code to make it work. Also if possible I recommend following Wills advice above and using node names rather than indexes as the are less sensitive to change (from for example Google engineers).

I’ve updated code in the demo and the zip file, sorry for the major delay.

53| Henrik said,

Thanks for the code anyway.
We made it work.

54| Arjay45 said,

Hi David. What should I change to get the site visits only and not the total page views? Thanks :)

55| Mike Chase said,

Hi - great job. I need to dig into the code and try it. Thanks again.

56| Google Analytics API in C# – Introduction | The Cyberwizard said,

[...] VB.NET) code.  After a quick search on Google, I found an article on akamarketing.com called Introducing Google Analytics API with asp.net / C#.  Exactly what I [...]

57| Google Analytics API in C# – Part 1 | The Cyberwizard said,

[...] am starting with the code I downloaded from Introducing Google Analytics API with asp.net / C# by AKA Marketing.  As I was looking around, I also found an article by Jacob Reimers called [...]

58| Dheeraj said,

I have simple asp.net aplication (using vb.net)
I have following requirments to do in my application

1. How to call google API in asp.net application?
2. How to retrives data from Google API in asp.net application?
3. How to show Google login in asp.net application?
4. How to send shopping carty data?
5. How to redirect user to order complete page after google checkout?

59| maily said,

I’m re-thinking what I thought I knew before reading this. Thanks for a well written piece that breaks through the fog to present a clear picture on a fascinating subject

60| منتديات said,

with your code and a few others like it, I am able to retrieve the auth token just fine, but the request for the actual feed always comes back (401) unauthorized. I have checked to make sure im forwarding token in header. Ive tried on a live domain. I’ve tried on a live domain in a directory where Network Service has write permission. Do I need to set something in the analytics account?

Leave a Comment
Name:
Email:
Website:
 
HOME | ABOUT US | CONTACT US | SITEMAP | GOOGLE SITE SEARCH | TOP
12 Lorcan Crescent, Santry, Dublin 9, Ireland +353 87 9807629