/// <summary>Только для запросов с известными maxResults и startIndex, выполняется один раз</summary> private static GaData GetGaData(AnalyticsService service, string ids, string startDate, string endDate, string metrics, string dimensions, string filters, string segment, string sort, int?maxResults, int?startIndex) { DataResource.GaResource.GetRequest request = service.Data.Ga.Get(ids, startDate, endDate, metrics); request.SamplingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.HIGHERPRECISION; if (!string.IsNullOrEmpty(dimensions)) { request.Dimensions = dimensions; } if (!string.IsNullOrEmpty(filters)) { request.Filters = filters; } if (!string.IsNullOrEmpty(segment)) { request.Segment = segment; } if (!string.IsNullOrEmpty(sort)) { request.Sort = sort; } if (startIndex != null) { request.StartIndex = startIndex; } if (maxResults != null) { request.MaxResults = Math.Min(max, (int)maxResults); } var res = request.Execute(); return(res); }
public GaData RunGAAPI(DateTime start, DateTime end, bool iscampaign = false, string campaign = "", string source = "", string medium = "") { //var _logger = EngineContext.Current.Resolve<ILogger>(); string[] scopes = new string[] { AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data AnalyticsService.Scope.AnalyticsManageUsersReadonly }; // View Google Analytics data //string keyFilePath = System.IO.Path.Combine(System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data"), "Get Andorra Analytics Values-73dc38419daa.p12"); string path = ConfigurationManager.AppSettings["p12key"]; string keyFilePath; if (path == "localhost") { keyFilePath = System.IO.Path.Combine(System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data"), "Get Andorra Analytics Values-73dc38419daa.p12"); } else { keyFilePath = System.IO.Path.Combine(path, "Get Andorra Analytics Values-73dc38419daa.p12"); } //string keyFilePath = Path.Combine(_webHelper.GetApp_DataPath(), EngineContext.Current.Resolve<FC_Settings_GoogleAPI>().GA_ApiFilename); string serviceAccountEmail = "*****@*****.**"; // found in developer console //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Get Andorra Analytics Values"// EngineContext.Current.Resolve<Nop.Core.Domain.FC.Settings.FC_Settings_GoogleAPI>().GA_ApiKey }); DataResource.GaResource.GetRequest result = service.Data.Ga.Get("ga:70910396", start.ToString("yyyy-MM-dd"), end.ToString("yyyy-MM-dd"), "ga:sessions,ga:users,ga:newUsers,ga:bounces,ga:avgSessionDuration,ga:pageviews"); //result.Dimensions = "ga:date,ga:countryIsoCode,ga:deviceCategory,ga:source,ga:medium,ga:campaign"; result.Sort = "ga:date"; result.Dimensions = "ga:date"; if (iscampaign) { result.Filters = "ga:campaign!=(not set)"; } if (campaign != "" && source != "" && medium != "") { result.Filters = "ga:campaign==" + campaign + ";ga:source==" + source + ";ga:medium==" + medium; } //result.Filters = "ga:campaign==" + utm_name + ";ga:source==" + utm_source + ";ga:medium==" + utm_medium; result.MaxResults = 10000; //_logger.Information("FC_GA EXECUTE" + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), null, null); return(result.Execute()); }
private GaData QueryAnalytics(DataResource.GaResource.GetRequest request) { GaData response = null; var authToken = googleAuthentication.GetAccessToken(); request.OauthToken = authToken.AccessToken; response = request.Execute(); return(response); }
string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension protected void Page_Load(object sender, EventArgs e) { string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY)); accessToken.Value = Token; var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable); var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(ServiceAccountUser) { Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credentials, ApplicationName = "Google Analytics API" }); string profileId = "ga:53861036"; string startDate = "2016-04-01"; string endDate = "2016-04-30"; string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits"; DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics); GaData data = request.Execute(); List <string> ColumnName = new List <string>(); foreach (var h in data.ColumnHeaders) { ColumnName.Add(h.Name); } List <double> values = new List <double>(); foreach (var row in data.Rows) { foreach (var item in row) { values.Add(Convert.ToDouble(item)); } } values[3] = Math.Truncate(100 * values[3]) / 100; txtSession.Text = values[0].ToString(); txtUsers.Text = values[1].ToString(); txtPageViews.Text = values[2].ToString(); txtBounceRate.Text = values[3].ToString(); txtVisits.Text = values[4].ToString(); }
// Service Account public Analytics TestServiceAccount() { string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data var keyFilePath = ConfigurationManager.AppSettings["keyFilePath"]; //@"c:\users\vivi\documents\visual studio 2015\Projects\CitygateApi\GoogleAnalyticsProject-5253532439c2.p12"; // Downloaded from https://console.developers.google.com var serviceAccountEmail = "*****@*****.**"; // found https://console.developers.google.com //var serviceAccountEmail = "*****@*****.**"; // loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Analytics Service var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Analytics API Sample", }); // Analytics Core DataResource.GaResource.GetRequest request = service.Data.Ga.Get("ga:40204906", "2017-01-23", "2017-01-29", "ga:sessions, ga:pageviews"); request.MaxResults = 1000; Google.Apis.Analytics.v3.Data.GaData result = request.Execute(); //List<List<String>> t = (List<List<String>>)result.Rows; //new List<List<string>>(); foreach (var headers in result.ColumnHeaders) { string name = headers.Name; string ctype = headers.ColumnType; string dtype = headers.DataType; } int sessions = int.Parse(result.Rows[0][0]); int pageviews = int.Parse(result.Rows[0][1]); Analytics an = new Analytics { Id = "ASD123", Name = "2017-01-23 - 2017-01-29", Sessions = sessions, PageViews = pageviews }; return(an); /*foreach (var row in result.Rows) * { * foreach (string col in row) * { * string column = col; * } * }*/ }
// Just loops though getting all the rows. private static GaData ProcessResults(DataResource.GaResource.GetRequest request) { try { GaData result = request.Execute(); List <IList <string> > allRows = new List <IList <string> >(); //// Loop through until we arrive at an empty page while (result.Rows != null) { //Add the rows to the final list allRows.AddRange(result.Rows); // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (result.NextLink == null) { break; } // Prepare the next page of results request.StartIndex = request.StartIndex + request.MaxResults; // Execute and process the next page request result = request.Execute(); } GaData allData = result; allData.Rows = (List <IList <string> >)allRows; return(allData); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
// GET: Home public ActionResult GetGoogleAnalyticsData(string fromDate = "2017-01-01", string toDate = "2017-06-06", string dimensions = "ga:pagePath,ga:pageTitle", string metrics = "ga:pageviews", string sortBy = "-ga:pageviews", int maxResult = 20) { try { var gaTableId = ConfigurationManager.AppSettings["AccountTableId"]; //Authenticate Get Google credential from json client secret //var credential = getUserCredentialFromJson(); ////Authenticate and get credential from clientId and Client Secret var credential = getUserCredential(); //Authenticate google api using service credential var serviceCredential = getServiceCredentialFromPrivateKey(); var gas = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credential.Result, //Below code is for service account //HttpClientInitializer = serviceCredential, ApplicationName = "Google Analytics API Sample", }); //var accountList = gas.Management.Accounts.List().Execute(); //AnalyticsService gas = AuthenticateUser(); //var gaId = ConfigurationManager.AppSettings["AccountTableId"]; // Creating our query // metric: ga:visits, ga:pageviews, ga:users, ga:newUsers, ga:sessions DataResource.GaResource.GetRequest r = gas.Data.Ga.Get(gaTableId, fromDate, toDate, metrics); r.Sort = sortBy; r.Dimensions = dimensions; r.MaxResults = maxResult; //Execute and fetch the results based on requested query GaData d = r.Execute(); ViewBag.isError = false; ViewBag.AnalyticsData = d.Rows; } catch (Exception ex) { ViewBag.isError = true; ViewBag.StatusMsg = ex.Message; } return(View()); }
public void Execute(AnalyticsService service, XML.Objects.Organisation.View view, Excel.Range currentCell) { String metrics = MetricsToString(); Request = service.Data.Ga.Get(view.Tag, Start.ToString("yyyy-MM-dd"), End.ToString("yyyy-MM-dd"), metrics); SetDimensions(Request); SetSort(Request); SetFilters(Request); SetSegment(Request); Request.MaxResults = 10000; Request.PrettyPrint = true; //Send the query GaData result = null; try { result = Request.Execute(); currentCell = Stubs.DisplayGaData(result, currentCell); currentCell.Select(); } catch (Google.GoogleApiException exception) { MessageBox.Show(exception.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main(string[] args) { //apikey.p12の設定 Console.Write("apikey.p12のパスを入力してください。: "); var apikey1 = Console.ReadLine(); //webhookurlの取得 Console.Write("WebhookURLを入力してください。 : "); var webhook = Console.ReadLine(); string WEBHOOK_URL = webhook; //実行ファイルのパスを取得 Assembly myAssembly = Assembly.GetEntryAssembly(); string path = myAssembly.Location; //APIkeyのパスを生成 string path1 = path.Replace("PVtoSlack.exe", ""); string path2 = (path + "apikey.p12"); // ファイルをコピーする FileSystem.CopyFile(apikey1, path2, showUI: UIOption.AllDialogs); //APIkeyの設定 X509Certificate2 certificate = new X509Certificate2(@"apikey.p12", "notasecret", X509KeyStorageFlags.Exportable); //APIの設定 Console.Write("APIのIDを入力してください。 : "); var id = Console.ReadLine(); string serviceAccountEmail = id; ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly } } .FromCertificate(certificate)); AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "pvtoslack", }); string date = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); //PVの取得 Console.Write("GA:"); var ga = Console.ReadLine(); var ga1 = "ga:" + ga; DataResource.GaResource.GetRequest request = service.Data.Ga.Get(ga1, date, date, "ga:pageviews"); GaData data = request.Execute(); var wc = new WebClient(); //送信するBOTの設定 var pvinfo = DynamicJson.Serialize(new { text = (data.Rows[0][0]), username = "******" }); wc.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=UTF-8"); wc.Encoding = Encoding.UTF8; while (true) { //送信 wc.UploadString(WEBHOOK_URL, pvinfo); //1日待機 System.Threading.Thread.Sleep(86400000); } }