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();
        }
Esempio n. 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);
            }
        }
Esempio n. 3
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
Esempio n. 4
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);
            }
        }
Esempio n. 5
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);
            }
        }
Esempio n. 6
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);
        }