Reputation: 179
I have a ASP.NET MVC web application. I want to show the number of LIVE users from a website.
How can I read this from Google Analytics?
I have already followed this guide:
http://www.markwemekamp.com/blog/c/how-to-read-from-google-analytics-using-c/
But I can't get the code to work. It keeps on running and gives a System.NullReferenceException
.
So I hope there are people with better idea's or guides here. And please, only complete guides with every detail in it. Not those half guide where you don't know what to do.
Thanks in Advance.
Update:
This is the code from the guide that I am using. I only added the date's. I am using the code in de Global.asax.cs file.
The Null exception occures on this piece of code:
foreach (var x in response.Reports.First().Data.Rows)
{
Debug.WriteLine("The next line doesn't appear: seee.....");
Debug.WriteLine(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
Code:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<EFDbContext>(null);
MethodSomethingGoogle();
}
public void MethodSomethingGoogle()
{
string todaysDate = DateTime.Now.ToString("yyyy-MM-dd");
string tomorrowsDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
try
{
var filepath = @"C:\Users\ckersten\Downloads\Dashboard-Match-Online-b2f3f0b438a1.json";
var filepath2 = @"~\App_Data\Dashboard-Match-Online-b2f3f0b438a1.json";
// path to the json file for the Service account
var viewid = "109154097"; // id of the view you want to read from
Googl
eCredential credentials;
using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
var googleCredential = GoogleCredential.FromStream(stream);
credentials = googleCredential.CreateScoped(scopes);
}
var reportingService = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credentials
});
var dateRange = new DateRange
{
StartDate = todaysDate,
EndDate = tomorrowsDate
};
var sessions = new Metric
{
Expression = "ga:pageviews",
Alias = "Sessions"
};
var date = new Dimension { Name = "ga:date" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date },
Metrics = new List<Metric> { sessions },
ViewId = viewid
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach (var x in response.Reports.First().Data.Rows)
{
Debug.WriteLine("The next line doesn't appear: seee.....");
Debug.WriteLine(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
}
catch (Exception e)
{
Debug.WriteLine("Google Exception: " + e.ToString());
}
Debug.WriteLine(Console.ReadLine());
}
Upvotes: 1
Views: 1172
Reputation: 117281
Your code uses the reporting api which isnt going to give you real time data. Data in the reporting api wont be done processing for 24 -48 hours .
You should be using the realtime api if you want to see whats going on now. Just remember that you can only make 10000 requests against the api a day per view.
DataResource.RealtimeResource.GetRequest request =
service.Data.Realtime.Get(String.Format("ga:{0}", profileId), "rt:activeUsers");
RealtimeData feed = request.Execute();
foreach (List row in realTimeData.Rows)
{
foreach (string col in row)
{
Console.Write(col + " "); // writes the value of the column
}
Console.Write("\r\n");
}
My tutorial on the realtime api here GitHub sample project can be found here you also might want to consider using a service account
Note:
The Real Time Reporting API, in limited beta, is available for developer preview only. Sign up to access the API.
Upvotes: 1