static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            //Bug? AnalyticsReadOnly scope does not work.
            //string Scope = AnalyticsService.Scopes.AnalyticsReadOnly.ToString().ToLower();
            string              Scope              = "analytics.readonly";
            string              scopeUrl           = "https://www.googleapis.com/auth/" + Scope;
            const string        ServiceAccountId   = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string        ServiceAccountUser = "******";
            AssertionFlowClient client             = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope            = scopeUrl,
                ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
                                                      //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator <AssertionFlowClient> authenticator = new OAuth2Authenticator <AssertionFlowClient>(client, AssertionFlowClient.GetState);
            AnalyticsService service   = new AnalyticsService(authenticator);
            string           profileId = "ga:nnnnnnnn";
            string           startDate = "2010-10-01";
            string           endDate   = "2010-10-31";
            string           metrics   = "ga:visits";

            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();
        }
Beispiel #2
0
        /// <summary>
        /// Gets the inventory page view count.
        /// </summary>
        /// <param name="companyId">The company identifier.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <returns></returns>
        /// <exception cref="StageBitz.Common.Exceptions.StageBitzException">0;Error occurred while connecting to google analytics server.</exception>
        private int GetInventoryPageViewCount(int companyId, DateTime startDate, DateTime endDate)
        {
            try
            {
                string profileId       = string.Concat("ga:", ProfileId);
                string startDateString = startDate.ToString("yyyy-MM-dd");
                string endDateString   = endDate.ToString("yyyy-MM-dd");
                int    pageViews       = 0;

                DataResource.GaResource.GetRequest request = GoogleAnalyticsService.Data.Ga.Get(profileId, startDateString, endDateString, "ga:visits");

                request.Dimensions = "ga:customVarValue1";
                request.Filters    = string.Format("ga:customVarValue1==Inventory;ga:customVarValue2=={0}", companyId);
                request.MaxResults = 1;
                GaData data = request.Fetch();

                if (data != null && data.Rows != null && data.Rows[0] != null)
                {
                    int.TryParse(data.Rows[0][1], out pageViews);
                }

                return(pageViews);
            }
            catch (Exception ex)
            {
                throw new StageBitzException(ExceptionOrigin.WebAnalytics, 0, "Error occurred while connecting to google analytics server.", ex);
            }
        }
Beispiel #3
0
 /// <summary>
 /// You query the Core Reporting API for Google Analytics report data.
 /// Documentation: https://developers.google.com/analytics/devguides/reporting/core/v3/reference
 ///
 /// Dimension and metric reference : https://developers.google.com/analytics/devguides/reporting/core/dimsmets
 /// </summary>
 /// <param name="service">Valid Authenticated AnalyticsServicve </param>
 /// <param name="ProfileId">The unique table ID of the form XXXX, where XXXX is the Analytics view (profile) ID for which the query will retrieve the data. </param>
 /// <param name="StartDate">Start date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer). </param>
 /// <param name="EndDate">End date for fetching Analytics data. Request can specify an end date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer). </param>
 /// <param name="Metrics">A list of comma-separated metrics, such as ga:sessions,ga:bounces. </param>
 /// <param name="optionalValues">Optional values can be null </param>
 /// <returns></returns>
 public static GaData Get(AnalyticsService service, string profileId, string startDate, string endDate, string metrics, OptionalValues optionalValues)
 {
     // ILog logger = LogManager.GetLogger(typeof(OptionalValues));
     try
     {
         DataResource.GaResource.GetRequest request = service.Data.Ga.Get(String.Format("ga:{0}", profileId), startDate, endDate, metrics);
         if (optionalValues == null)
         {
             request.MaxResults = 1000;
         }
         else
         {
             request.MaxResults    = optionalValues.MaxResults;
             request.Dimensions    = optionalValues.Dimensions;
             request.SamplingLevel = optionalValues.Sampling;
             request.Segment       = optionalValues.Segment;
             request.Sort          = optionalValues.Sort;
             request.Filters       = optionalValues.Filter;
         }
         return(ProcessResults(request));
     }
     catch (Exception e)
     {
         //  logger.Error(e.StackTrace);
         //logger.Error(e.Message);
     }
     return(null);
 }
Beispiel #4
0
        public async Task <List <GoogleSource> > GetSource()
        {
            if (!String.IsNullOrEmpty(profileId))
            {
                DataResource.GaResource.GetRequest request = service.Data.Ga.Get(String.Format("ga:{0}", profileId), "30daysAgo", "today", "ga:sessions,ga:users");
                request.Dimensions = "ga:medium";
                var qq = await request.ExecuteAsync();

                List <GoogleSource> visitors = new List <GoogleSource>();
                foreach (var item in qq.Rows)
                {
                    GoogleSource vv = new GoogleSource();
                    vv.Refferal     = item[0];
                    vv.SessionCount = item[1];
                    vv.Users        = item[2];
                    visitors.Add(vv);
                }
                return(visitors);
                //return qq.TotalResults.ToString();
            }
            else
            {
                return(null);
            }
        }
Beispiel #5
0
        public async Task <List <GoogleVisitorsAndPageView> > GetMonthVisitorsAndPageviews()
        {
            if (!String.IsNullOrEmpty(profileId))
            {
                DataResource.GaResource.GetRequest request = service.Data.Ga.Get(String.Format("ga:{0}", profileId), "30daysAgo", "today", "ga:sessions,ga:pageviews,ga:users");
                request.Dimensions = "ga:date";
                var qq = await request.ExecuteAsync();

                List <GoogleVisitorsAndPageView> visitors = new List <GoogleVisitorsAndPageView>();
                foreach (var item in qq.Rows)
                {
                    GoogleVisitorsAndPageView vv = new GoogleVisitorsAndPageView();
                    string time = item[0].Substring(0, 4) + "/" + item[0].Substring(4, 2) + "/" + item[0].Substring(6, 2);
                    vv.Time      = time;
                    vv.Session   = item[1];
                    vv.PageViews = item[2];
                    vv.Users     = item[3];
                    visitors.Add(vv);
                }
                return(visitors);
                //return qq.TotalResults.ToString();
            }
            else
            {
                return(null);
            }
        }
Beispiel #6
0
        /// <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);
        }
Beispiel #7
0
        }         // constructor

        public List <GoogleDataItem> Fetch()
        {
            string sStartDate = m_oStartDate.ToString(GoogleDataFetcher.OAuthDateFormat, CultureInfo.InvariantCulture);
            string sEndDate   = m_oEndDate.ToString(GoogleDataFetcher.OAuthDateFormat, CultureInfo.InvariantCulture);

            DataResource.GaResource.GetRequest request = m_oService.Data.Ga.Get(this.profileID, sStartDate, sEndDate, Metrics);

            //to retrieve accounts: Accounts accounts = service.Management.Accounts.List().Fetch();
            //to retrieve profiles: var profiles = service.Management.Profiles.List("32583191", "UA-32583191-1").Fetch();
            /*foreach (Profile profile in profiles.Items){Console.WriteLine("Profile Timezone: " + profile.Timezone);}*/

            request.Dimensions = Dimensions;

            if (m_sFilters != null)
            {
                request.Filters = m_sFilters;
            }

            Debug("Fetching for {2} - {3} with dimensions {0} and metrics {1}...", Dimensions, Metrics, sStartDate, sEndDate);

            GaData data = request.Fetch();

            Debug("Processing...");

            var oOutput = new List <GoogleDataItem>();

            foreach (List <string> pkg in data.Rows)
            {
                if (pkg.Count != DimMetCount)
                {
                    continue;
                }

                Debug("-- Begin"); foreach (string s in pkg)
                {
                    Debug("-- row: {0}", s);
                }
                Debug("-- End");

                var oItem = new GoogleDataItem();

                foreach (KeyValuePair <GoogleReportDimensions, int> pair in m_oDimensions)
                {
                    oItem[pair.Key] = pkg[Idx(pair.Key)];
                }

                foreach (KeyValuePair <GoogleReportMetrics, int> pair in m_oMetrics)
                {
                    oItem[pair.Key] = int.Parse(pkg[Idx(pair.Key)]);
                }

                oOutput.Add(oItem);
            }             // for each package

            Debug("Fetching stats complete.");

            return(oOutput);
        }         // Fetch
Beispiel #8
0
        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());
        }
Beispiel #9
0
 private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] demensions, string[] metrics,
                                                                 DateTime startDate, DateTime endDate, int startIndex)
 {
     DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),
                                                                      endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));
     request.Dimensions = string.Join(",", demensions);
     request.StartIndex = startIndex;
     return(request);
 }
Beispiel #10
0
        private GaData QueryAnalytics(DataResource.GaResource.GetRequest request)
        {
            GaData response  = null;
            var    authToken = googleAuthentication.GetAccessToken();

            request.OauthToken = authToken.AccessToken;
            response           = request.Execute();

            return(response);
        }
Beispiel #11
0
        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();
        }
Beispiel #12
0
        /// <summary>
        /// Gets the project team activities.
        /// </summary>
        /// <param name="companyId">The company identifier.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="sortBy">The sort by.</param>
        /// <param name="isAscending">if set to <c>true</c> [is ascending].</param>
        /// <param name="totalRecords">The total records.</param>
        /// <returns></returns>
        /// <exception cref="StageBitz.Common.Exceptions.StageBitzException">0;Error occurred while connecting to google analytics server.</exception>
        public List <ProjectTeamActivity> GetProjectTeamActivities(int companyId, DateTime startDate, DateTime endDate,
                                                                   int pageSize, int pageIndex, string sortBy, bool isAscending, out int totalRecords)
        {
            try
            {
                int startIndex = (pageSize * pageIndex) + 1;
                totalRecords = 0;
                string profileId       = string.Concat("ga:", ProfileId);
                string startDateString = startDate.ToString("yyyy-MM-dd");
                string endDateString   = endDate.ToString("yyyy-MM-dd");

                DataResource.GaResource.GetRequest request = GoogleAnalyticsService.Data.Ga.Get(profileId, startDateString, endDateString, "ga:timeOnSite");

                request.Dimensions = "ga:customVarValue1, ga:customVarValue2, ga:customVarValue3, ga:customVarValue4, ga:date";
                request.Filters    = string.Format("ga:customVarValue1==Project;ga:customVarValue2=={0}", companyId);
                request.MaxResults = pageSize;
                request.StartIndex = startIndex;
                request.Sort       = GetSortingValue(sortBy, isAscending);
                GaData data = request.Fetch();

                List <ProjectTeamActivity> activities = new List <ProjectTeamActivity>();
                if (data != null && data.Rows != null)
                {
                    activities = (from pa in data.Rows
                                  select new
                    {
                        Date = DateTime.ParseExact(pa[4], "yyyyMMdd", CultureInfo.InvariantCulture),
                        ProjectId = int.Parse(pa[3]),
                        TimeSpan = TimeSpan.FromSeconds(double.Parse(pa[5])),
                        CompanyId = int.Parse(pa[1]),
                        UserId = int.Parse(pa[2])
                    }
                                  into tempActivities
                                  select new ProjectTeamActivity
                    {
                        Date = tempActivities.Date,
                        ProjectId = tempActivities.ProjectId,
                        SessionTotal = string.Format("{0:D2}:{1:D2}:{2:D2}",
                                                     tempActivities.TimeSpan.Hours,
                                                     tempActivities.TimeSpan.Minutes,
                                                     tempActivities.TimeSpan.Seconds),
                        UserId = tempActivities.UserId
                    }).ToList();

                    totalRecords = (int)data.TotalResults;
                }

                return(activities);
            }
            catch (Exception ex)
            {
                throw new StageBitzException(ExceptionOrigin.WebAnalytics, 0, "Error occurred while connecting to google analytics server.", ex);
            }
        }
Beispiel #13
0
        // 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;
             *  }
             * }*/
        }
Beispiel #14
0
        // 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());
        }
Beispiel #15
0
 /// <summary>
 /// You query the Core Reporting API for Google Analytics report data.
 /// Documentation: https://developers.google.com/analytics/devguides/reporting/core/v3/reference
 ///
 /// Dimension and metric reference : https://developers.google.com/analytics/devguides/reporting/core/dimsmets
 /// </summary>
 /// <param name="service">Valid Authenticated AnalyticsServicve </param>
 /// <param name="ProfileId">The unique table ID of the form XXXX, where XXXX is the Analytics view (profile) ID for which the query will retrieve the data. </param>
 /// <param name="StartDate">Start date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer). </param>
 /// <param name="EndDate">End date for fetching Analytics data. Request can specify an end date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer). </param>
 /// <param name="Metrics">A list of comma-separated metrics, such as ga:sessions,ga:bounces. </param>
 /// <param name="optionalValues">Optional values can be null </param>
 /// <returns></returns>
 public static GaData Get(AnalyticsService service, string profileId, string startDate, string endDate, string metrics, OptionalValues optionalValues)
 {
     DataResource.GaResource.GetRequest request = service.Data.Ga.Get(String.Format("ga:{0}", profileId), startDate, endDate, metrics);
     if (optionalValues == null)
     {
         request.MaxResults = 1000;
     }
     else
     {
         request.MaxResults    = optionalValues.MaxResults;
         request.Dimensions    = optionalValues.Dimensions;
         request.SamplingLevel = optionalValues.Sampling;
         request.Segment       = optionalValues.Segment;
         request.Sort          = optionalValues.Sort;
         request.Filters       = optionalValues.Filter;
     }
     return(ProcessResults(request));
 }
Beispiel #16
0
        /// <summary>
        /// Gets the user activity days count.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <returns></returns>
        /// <exception cref="StageBitz.Common.Exceptions.StageBitzException">0;Error occurred while connecting to google analytics server.</exception>
        private int GetUserActivityDaysCount(int userId, DateTime startDate, DateTime endDate)
        {
            try
            {
                string profileId       = string.Concat("ga:", ProfileId);
                string startDateString = startDate.ToString("yyyy-MM-dd");
                string endDateString   = endDate.ToString("yyyy-MM-dd");

                DataResource.GaResource.GetRequest request = GoogleAnalyticsService.Data.Ga.Get(profileId, startDateString, endDateString, "ga:visits");

                request.Dimensions = "ga:customVarValue1, ga:date";
                request.Filters    = string.Format("ga:customVarValue1==Project;ga:customVarValue3=={0}", userId);
                request.MaxResults = 1;
                GaData data = request.Fetch();
                return(data.Rows != null ? (int)data.TotalResults : 0);
            }
            catch (Exception ex)
            {
                throw new StageBitzException(ExceptionOrigin.WebAnalytics, 0, "Error occurred while connecting to google analytics server.", ex);
            }
        }
Beispiel #17
0
        private IEnumerable <T> MapRows <T>(DataResource.GaResource.GetRequest request) where T : new()
        {
            var columnPosityions = new Dictionary <Tuple <string, string>, int>();
            var gaData           = QueryAnalytics(request);
            var headers          = gaData.ColumnHeaders;

            int i = 0;

            foreach (var columnHeadersData in headers)
            {
                var headerNameTypeKey = new Tuple <string, string>(columnHeadersData.ColumnType, columnHeadersData.Name);
                columnPosityions[headerNameTypeKey] = i;
                i++;
            }
            if (gaData.Rows != null && gaData.Rows.Any())
            {
                return(gaData.Rows.Select(row => MapRow <T>(row, columnPosityions)).ToList());
            }

            return(Enumerable.Empty <T>());
        }
Beispiel #18
0
        // 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);
            }
        }
Beispiel #19
0
        private GoogleAnaliticsStatisticModel GetAnaliticsDataMethod(string scope, string clientId, string keyPassword, Core.Domain.Media.Download download, DateTime startDate, DateTime endDate)
        {
            var model = new GoogleAnaliticsStatisticModel();
            AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;

            //Create a certificate object to use when authenticating
            X509Certificate2 key = new X509Certificate2(download.DownloadBinary, keyPassword, X509KeyStorageFlags.Exportable);

            //Now, we will log in and authenticate, passing in the description
            //and key from above, then setting the accountId and scope
            AssertionFlowClient client = new AssertionFlowClient(desc, key)
            {
                ServiceAccountId = clientId,
                Scope            = scope,
            };

            //Finally, complete the authentication process
            //NOTE: This is the first change from the update above
            OAuth2Authenticator <AssertionFlowClient> auth =
                new OAuth2Authenticator <AssertionFlowClient>(client, AssertionFlowClient.GetState);

            //First, create a new service object
            //NOTE: this is the second change from the update
            //above. Thanks to James for pointing this out
            AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer()
            {
                Authenticator = auth
            });

            //Create our query
            //The Data.Ga.Get needs the parameters:
            //Analytics account id, starting with ga:
            //Start date in format YYYY-MM-DD
            //End date in format YYYY-MM-DD
            //A string specifying the metrics
            DataResource.GaResource.GetRequest r =
                gas.Data.Ga.Get("ga:" + _googleAnliticsSettings.AccountId, startDate.ToString("yyy-MM-dd"), endDate.ToString("yyy-MM-dd"), "ga:visitors,ga:uniquePageviews,ga:AvgTimeOnSite,ga:exitRate");

            //Specify some addition query parameters
            //r.Sort = "-ga:visitors";
            //r.Sort = "-ga:AvgTimeOnSite";
            //r.Sort = "-ga:uniquePageviews";
            //r.Sort = "-ga:exitRate";
            r.MaxResults = 50;

            //Execute and fetch the results of our query
            GaData d = r.Fetch();

            //Write the column headers
            //Write the data
            foreach (var row in d.Rows)
            {
                model.Visitors          = row[0];
                model.UniquePageViews   = row[1];
                model.AverageTimeOnSite = row[2];
                if (row[3].Length > 5)
                {
                    model.ExitRate = row[3].Substring(0, 5);
                }
                else
                {
                    model.ExitRate = row[3];
                }
            }

            r            = gas.Data.Ga.Get("ga:" + _googleAnliticsSettings.AccountId, startDate.ToString("yyy-MM-dd"), endDate.ToString("yyy-MM-dd"), "ga:visitors");
            r.Dimensions = "ga:visitorType";
            r.MaxResults = 50;

            //Execute and fetch the results of our query
            d = r.Fetch();
            if (d.Rows.Count == 1)
            {
                if (d.Rows[0][0] != "Returning Visitor")
                {
                    model.NewToOldVisitorsRate = "100%";
                }
                else
                {
                    model.NewToOldVisitorsRate = "0%";
                }
            }
            else
            {
                model.NewToOldVisitorsRate = (((double)(int.Parse(d.Rows[0][1])) / (int.Parse(d.Rows[1][1]))) * 100).ToString() + "%";
            }

            if (model.NewToOldVisitorsRate.Length > 5)
            {
                model.NewToOldVisitorsRate = model.NewToOldVisitorsRate.Substring(0, 5);
            }

            if (model.AverageTimeOnSite.Length - model.AverageTimeOnSite.IndexOf(".") > 3)
            {
                model.AverageTimeOnSite = model.AverageTimeOnSite.Substring(0, model.AverageTimeOnSite.IndexOf(".") + 3);
            }

            return(model);
        }
Beispiel #20
0
        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);
            }
        }
        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);
            }
        }