So if you want to create your own version of Embedded analytics, the first thing to do is figure out how to use the Google Analytics API. If you’re wanting to use the .NET API, then this little snippet might help you get started. It loops through all the registered sites and shows the number of visits to each site over the last month.
class Program { static void Main(string[] args) { AccountQuery feedQuery = new AccountQuery(); AnalyticsService service = new AnalyticsService("DoogalAnalytics"); service.setUserCredentials("email", "password"); foreach (AccountEntry entry in service.Query(feedQuery).Entries) { Console.WriteLine(entry.Title.Text); DataQuery pageViewQuery = new DataQuery("https://www.google.com/analytics/feeds/data"); pageViewQuery.Ids = entry.ProfileId.Value; pageViewQuery.Metrics = "ga:visits"; pageViewQuery.GAStartDate = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd"); pageViewQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd"); foreach (DataEntry pvEntry in service.Query(pageViewQuery).Entries) { Console.WriteLine(pvEntry.Metrics[0].Value); } } Console.ReadLine(); } }
4 comments:
I have attempted to run the code but receive the following error: "The remote server returned an error: (403) Forbidden." What can I do to resolve this?
Are you passing in the right email address and password?
Yep, I am able to log into google analytics.
Not too sure what the problem is then. I've just tested it using my account and it all works fine.
Post a Comment