Esempio n. 1
0
    public AnalyticDataPoint GetAnalyticsData(string profileId, string[] demensions, string[] metrics, DateTime startDate, DateTime endDate)
    {
        AnalyticDataPoint data = new AnalyticDataPoint();

        if (!profileId.Contains("ga:"))
        {
            profileId = string.Format("ga:{0}", profileId);
        }
        //Make initial call to service.
        //Then check if a next link exists in the response,
        //if so parse and call again using start index param.
        GaData response = null;

        do
        {
            int startIndex = 1;
            if (response != null && !string.IsNullOrEmpty(response.NextLink))
            {
                Uri    uri         = new Uri(response.NextLink);
                var    paramerters = uri.Query.Split('&');
                string s           = paramerters.First(i => i.Contains("start-index")).Split('=')[1];
                startIndex = int.Parse(s);
            }
            var request = BuildAnalyticRequest(profileId, demensions, metrics, startDate, endDate, startIndex);
            response           = request.Execute();
            data.ColumnHeaders = response.ColumnHeaders;
            data.Rows.AddRange(response.Rows);
        } while (!string.IsNullOrEmpty(response.NextLink));
        return(data);
    }
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
 public static GaData EvolveSortersDirect(
     this GaData sortingGaData, IRando randy)
 {
     return(sortingGaData.Eval()
            .SelectWinningSorters()
            .UpdateSortersDirect(randy));
 }
Esempio n. 4
0
        public static ProcResult Scheme4(int steps, GaData gasd)
        {
            var randy      = Rando.Standard(gasd.Data.GetSeed());
            var strRet     = String.Empty;
            var _stopwatch = new Stopwatch();

            _stopwatch.Reset();
            _stopwatch.Start();

            for (var i = 0; i < steps; i++)
            {
                gasd = gasd.EvolveStageDimerSortersAndSortables(randy);
                gasd.Data.SetCurrentStep(gasd.Data.GetCurrentStep() + 1);
            }

            _stopwatch.Stop();
            gasd.Data.SetSeed(randy.NextInt());

            var dRet = new Dictionary <string, object>();

            dRet.SetGaSortingData(gasd);
            return(new ProcResult(data: dRet,
                                  err: strRet,
                                  stepsCompleted: steps,
                                  time: _stopwatch.ElapsedMilliseconds));
        }
        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. 6
0
        public void Serialize(GaData gaData)
        {
            using (var s = new StreamWriter(_filePath))
            {
                int i = 0;
                foreach (var h in gaData.ColumnHeaders)
                {
                    if (i++ > 0)
                        s.Write("\t");
                    s.Write(h.Name);
                }
                s.WriteLine();

                foreach (var row in gaData.Rows)
                {
                    for (int col = 0; col < row.Count; col++)
                    {
                        if (col > 0)
                            s.Write("\t");
                        s.Write(row[col]);
                    }
                    s.WriteLine();
                }
                s.Flush();
                s.Close();
            }
        }
Esempio n. 7
0
        private DataTable ToDataTable(GaData response, string name = "GA")
        {
            var requestResultTable = new DataTable(name);

            if (response != null)
            {
                requestResultTable.Columns.AddRange(response.ColumnHeaders.Select(c => new DataColumn(GaMetadata.RemovePrefix(c.Name), GetDataType(c))).ToArray());

                if (response.Rows != null)
                {
                    foreach (var row in response.Rows)
                    {
                        var dtRow = requestResultTable.NewRow();

                        for (var idx = 0; idx != requestResultTable.Columns.Count; idx++)
                        {
                            var col = requestResultTable.Columns[idx];
                            if (col.DataType == typeof(DateTime))
                            {
                                dtRow.SetField(col,
                                               DateTime.ParseExact(row[idx], "yyyyMMdd", new DateTimeFormatInfo(),
                                                                   DateTimeStyles.AssumeLocal));
                            }
                            else
                            {
                                dtRow.SetField(col, row[idx]);
                            }
                        }
                        requestResultTable.Rows.Add(dtRow);
                    }
                }
                requestResultTable.AcceptChanges();
            }
            return(requestResultTable);
        }
Esempio n. 8
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. 9
0
 public static GaData EvolveSortersConjRecombSortablesConj(
     this GaData sortingGaData, IRando randy)
 {
     return(sortingGaData.Eval()
            .SelectWinningSortables()
            .SelectWinningSorters()
            .RecombineSelectedSorters(randy)
            .EvolveSortablesConj(randy)
            .UpdateSortersDirect(randy));
 }
Esempio n. 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);
        }
Esempio n. 11
0
        public static GaData RecombineFineSelectedSorterDimerGenomes(
            this GaData sortingGaData, IRando randy)
        {
            var data = sortingGaData.Data.Copy();

            var bestDimerGenomePool = data.GetBestDimerGenomePool();

            data.SetBestDimerGenomePool(bestDimerGenomePool.ToRecombFine(randy));
            return(new GaData(data: data));
        }
Esempio n. 12
0
        public static string Report(this GaData sortingGaData)
        {
            var data           = sortingGaData.Data;
            var bestSorterPool = data.GetBestSorterPool();
            var sortingResults = data.GetSortingResults();

            var avgAllSorters = sortingResults.SorterResults.Average(sr => sr.Value.AverageSortedness);

            return($"{avgAllSorters}");
        }
Esempio n. 13
0
 public static GaData EvolveStageDimerSorters(this GaData sortingGaData,
                                              IRando randy)
 {
     return(sortingGaData
            .MakeSortersFromStageDimerGenomes()
            .Eval()
            .SelectWinningSorters()
            .SelectSorterDimerGenomes()
            .EvolveSorterDimerGenomes(randy));
 }
Esempio n. 14
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();
        }
Esempio n. 15
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!(context.Controller is Controller controller))
            {
                return;
            }

            var gaData             = new GaData();
            var locationFromCookie = _locationCookieStorageService.Get(Constants.LocationCookieName);

            if (context.HttpContext.Request.Query.TryGetValue("location", out var location))
            {
                gaData.Location = location.ToString();
            }
            else if (locationFromCookie != null)
            {
                if (!string.IsNullOrEmpty(locationFromCookie.Name) && locationFromCookie.Lat != 0 &&
                    locationFromCookie.Lon != 0)
                {
                    gaData.Location = locationFromCookie.Name;
                }
            }


            if (context.RouteData.Values.TryGetValue("providerId", out var providerId))
            {
                if (uint.TryParse(providerId.ToString(), out var ukprn))
                {
                    if (context.HttpContext.Request.Query.TryGetValue("data", out var data))
                    {
                        try
                        {
                            var base64EncodedBytes = WebEncoders.Base64UrlDecode(data);
                            var decoded            = System.Text.Encoding.UTF8.GetString(_protector.Unprotect(base64EncodedBytes));
                            var decodedItems       = decoded.Split("|").ToList();
                            gaData.ProviderId        = ukprn;
                            gaData.ProviderPlacement = Convert.ToInt32(decodedItems.FirstOrDefault());
                            gaData.ProviderTotal     = Convert.ToInt32(decodedItems.LastOrDefault());
                        }
                        catch (FormatException)
                        {
                            _logger.LogInformation("Unable to decode GA data");
                        }
                        catch (CryptographicException)
                        {
                            _logger.LogInformation("Unable to unprotect GA data");
                        }
                    }
                }
            }

            controller.ViewBag.GaData = gaData;

            base.OnActionExecuting(context);
        }
Esempio n. 16
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. 17
0
        public static GaData MakeSortersFromStageDimerGenomes(
            this GaData sortingGaData)
        {
            var data = sortingGaData.Data.Copy();

            var dimerGenomePool = data.GetDimerGenomePool();
            var sorters         = dimerGenomePool.SorterGenomes.Select(g => g.Value.ToSorter());

            data.SetSorterPool(new SorterPool(Guid.NewGuid(), sorters));
            return(new GaData(data: data));
        }
Esempio n. 18
0
        public void SetValues(GaData data)
        {
            if (data == null || data.Rows == null)
                return;

            foreach(var row in data.Rows)
            {
                Labels.Add(row[0]);
                Data.Add(row[1]);
            }
        }
Esempio n. 19
0
        public static GaData MakeSortersFromConjOrbitGenomes(
            this GaData sortingGaData)
        {
            var data = sortingGaData.Data.Copy();

            var conjOrbitGenomePool = data.GetConjOrbitGenomePool();
            var sorters             = conjOrbitGenomePool
                                      .SorterGenomes
                                      .Select(g => g.Value.ToSorter(g.Value.Stagecount));

            data.SetSorterPool(new SorterPool(Guid.NewGuid(), sorters));
            return(new GaData(data: data));
        }
Esempio n. 20
0
 public static GaData EvolveRecombineFineStageDimerSortersAndSortables(this GaData sortingGaData,
                                                                       IRando randy)
 {
     return(sortingGaData
            .MakeSortersFromStageDimerGenomes()
            .Eval()
            .SelectWinningSorters()
            .SelectWinningSortables()
            .SelectSorterDimerGenomes()
            .RecombineFineSelectedSorterDimerGenomes(randy)
            .SelectWinningSortables()
            .EvolveSortablesConj(randy)
            .EvolveSorterDimerGenomes(randy));
 }
Esempio n. 21
0
        public static GaData SelectConjOrbitGenomes(
            this GaData sortingGaData)
        {
            var data = sortingGaData.Data.Copy();

            var conjOrbitGenomePool = data.GetConjOrbitGenomePool();
            var bestSorterPool      = data.GetBestSorterPool();

            var bestConjOrbitGenomePool = bestSorterPool
                                          .Select(s => conjOrbitGenomePool.SorterGenomes[s.GenomeId])
                                          .ToGenomePoolConjOrbits(Guid.NewGuid());

            data.SetBestConjOrbitGenomePool(bestConjOrbitGenomePool);
            return(new GaData(data: data));
        }
Esempio n. 22
0
        public static GaData SelectSorterDimerGenomes(
            this GaData sortingGaData)
        {
            var data = sortingGaData.Data.Copy();

            var dimerGenomePool = data.GetDimerGenomePool();
            var bestSorterPool  = data.GetBestSorterPool();

            var bestDimerGenomePool = bestSorterPool
                                      .Select(s => dimerGenomePool.SorterGenomes[s.GenomeId])
                                      .ToGenomePoolStageDimer(Guid.NewGuid());

            data.SetBestDimerGenomePool(bestDimerGenomePool);
            return(new GaData(data: data));
        }
Esempio n. 23
0
        public IEnumerable <T> Execute(QueryData queryData, Func <ContextDataModel, T> expression, FieldsMap fieldsMap)
        {
            var request = getRequest(queryData);

            try
            {
                GaData data = request.Fetch();
                return(getResult(data, expression, fieldsMap));
            }
            catch (Exception ex)
            {
                var requestExceprion = new GoogleAnalyticsRequestException("Can't fetch data", ex);
                throw requestExceprion;
            }
        }
Esempio n. 24
0
        public static GaData EvolveSortablesConj(this GaData sortingGaData, IRando randy)
        {
            var data                = sortingGaData.Data.Copy();
            var sortableWinRate     = data.GetSortableWinRate();
            var bestSortablePool    = data.GetBestSortablePool();
            var wholeSortablePool   = data.GetSortablePool();
            var sortableMutantCount = (uint)(wholeSortablePool.Sortables.Count * (1.0 - sortableWinRate));

            var sortableNextGen = bestSortablePool.Sortables.Values.Concat(
                bestSortablePool.Sortables.Values.ToRoundRobin().Take((int)sortableMutantCount)
                .Select(p => p.ConjugateByRandomSingleTwoCycle(randy).ToSortable()));

            data.SetSortablePool(new SortablePool(Guid.NewGuid(), sortableNextGen));
            return(new GaData(data: data));
        }
Esempio n. 25
0
        public static GaData SelectWinningSorters(this GaData sortingGaData)
        {
            var data = sortingGaData.Data.Copy();

            var sorterPool     = data.GetSorterPool();
            var sorterWinRate  = data.GetSorterWinRate();
            var sorterWinCount = (int)(sorterPool.Sorters.Count * sorterWinRate);
            var sortingResults = data.GetSortingResults();
            var bestSorters    = sortingResults.SorterResults.Values
                                 .OrderBy(r => r.AverageSortedness)
                                 .Take(sorterWinCount).Select(sr => sr.Sorter);

            data.SetBestSorterPool(new SorterPool(Guid.NewGuid(), bestSorters));

            return(new GaData(data: data));
        }
Esempio n. 26
0
        public static string ReportMore(this GaData sortingGaData)
        {
            var data           = sortingGaData.Data;
            var bestSorterPool = data.GetBestSorterPool();
            var sortingResults = data.GetSortingResults();

            var avgAllSorters  = sortingResults.SorterResults.Average(sr => sr.Value.AverageSortedness);
            var avgBestSorters = bestSorterPool.Sorters.Values
                                 .Select(s => sortingResults.SorterResults[s.Id])
                                 .Average(sr => sr.AverageSortedness);

            var sorterDiv = data.GetBestSorterPool().Sorters.Values
                            .Select(s => sortingResults.SorterResults[s.Id])
                            .GroupBy(sr => sr.AverageSortedness).Count();

            return($"{avgAllSorters} {avgBestSorters} {sorterDiv}");
        }
Esempio n. 27
0
        public static GaData Eval(this GaData sortingGaData)
        {
            var data = sortingGaData.Data.Copy();

            var sorterPool   = data.GetSorterPool();
            var sortablePool = data.GetSortablePool();

            var sr = sortablePool.AsParallel()
                     .SelectMany(
                sb => sorterPool.Select(st => st.Sort(sb)));

            var sortingResults = new SortingResults(sr, false);

            data.SetSortingResults(sortingResults);

            return(new GaData(data: data));
        }
Esempio n. 28
0
        public static GaData UpdateSortablesDirect(
            this GaData sortingGaData, IRando randy)
        {
            var data                = sortingGaData.Data.Copy();
            var sortableWinRate     = data.GetSortableWinRate();
            var bestSortablePool    = data.GetBestSortablePool();
            var wholeSortablePool   = data.GetSortablePool();
            var sortableMutantCount = (uint)(wholeSortablePool.Sortables.Count * (1.0 - sortableWinRate));

            var sortableNextGen = bestSortablePool.Sortables.Values.Concat(
                0u.CountUp(sortableMutantCount)
                .Select(s => randy.ToPermutation(bestSortablePool.Order).ToSortable())
                );

            data.SetSortablePool(new SortablePool(Guid.NewGuid(), sortableNextGen));
            return(new GaData(data: data));
        }
Esempio n. 29
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());
        }
Esempio n. 30
0
        public void ExecuteAsync(QueryData queryData, Func <ContextDataModel, T> expression, FieldsMap fieldsMap, Action <IEnumerable <T> > callback)
        {
            var request = getRequest(queryData);

            request.FetchAsync(lazyData =>
            {
                try
                {
                    GaData data = lazyData.GetResult();
                    callback(getResult(data, expression, fieldsMap));
                }
                catch (Exception ex)
                {
                    var requestExceprion = new GoogleAnalyticsRequestException("Can't fetch data", ex);
                    throw requestExceprion;
                }
            });
        }
Esempio n. 31
0
        public static GaData EvolveSorterDimerGenomes(this GaData sortingGaData, IRando rando)
        {
            var data = sortingGaData.Data.Copy();

            var sorterWinRate       = data.GetSorterWinRate();
            var dimerGenomePool     = data.GetDimerGenomePool();
            var bestDimerGenomePool = data.GetBestDimerGenomePool();
            var sorterMutantCount   = (int)(dimerGenomePool.SorterGenomes.Count * (1.0 - sorterWinRate));

            var newDimerGenomePool = bestDimerGenomePool
                                     .SorterGenomes.Values.ToRoundRobin()
                                     .Take(sorterMutantCount)
                                     .Select(g => g.Mutate(rando))
                                     .Concat(bestDimerGenomePool.SorterGenomes.Values)
                                     .ToGenomePoolStageDimer(Guid.NewGuid());

            data.SetDimerGenomePool(newDimerGenomePool);
            return(new GaData(data: data));
        }
Esempio n. 32
0
        public static GaData UpdateSortersDirect(
            this GaData sortingGaData, IRando randy)
        {
            var data = sortingGaData.Data.Copy();

            var sorterWinRate        = data.GetSorterWinRate();
            var wholeSorterPool      = data.GetSorterPool();
            var bestSorterPool       = data.GetBestSorterPool();
            var stageReplacementMode = data.GetStageReplacementMode();
            var sorterMutantCount    = (int)(wholeSorterPool.Sorters.Count * (1.0 - sorterWinRate));

            var sorterNextGen = bestSorterPool.Sorters.Values.Concat(
                bestSorterPool.Sorters.Values.ToRoundRobin().Take(sorterMutantCount)
                .Select(s => s.Mutate(randy, stageReplacementMode))
                );

            data.SetSorterPool(new SorterPool(Guid.NewGuid(), sorterNextGen));
            return(new GaData(data: data));
        }
Esempio n. 33
0
        public void Serialize(GaData gaData)
        {
            using (var s = new StreamWriter(_filePath))
            {
                int i = 0;
                foreach (var h in gaData.ColumnHeaders)
                {
                    if (i++ > 0)
                        s.Write("\t");
                    s.Write(h.Name);
                }
                s.WriteLine();

                if (gaData.Rows != null)
                {
                    foreach (var columnArray in gaData.Rows)
                    {
                        SerializeRemainderOfRow(s, new StringBuilder(), columnArray, 0);
                    }
                }
                s.Flush();
                s.Close();
            }
        }
Esempio n. 34
0
        public static Excel.Range DisplayGaData(GaData data, Excel.Range range)
        {
            Excel.Worksheet activeWorksheet = range.Worksheet;
            Excel.Range currentCell;
            int row = range.Row;
            int column = range.Column;
            int endRow = row;
            int endColumn = column;
            int maxRowLength = 0;
            if (data == null)
                return range;
            if (data.Rows != null)
            {
                // Display results of the query
                for (int j = 0; j < data.Rows.Count(); j++)
                {
                    for (int i = 0; i < data.Rows[j].Count(); i++)
                    {
                        currentCell = activeWorksheet.Cells[column + 1 + j][row + i];
                        currentCell.Value2 = data.Rows[j][i];

                    }
                    if (data.Rows[j].Count() > maxRowLength)
                        maxRowLength = data.Rows.Count();
                }
                endColumn += data.Rows.Count();
                for (int k = 0; k < data.ColumnHeaders.Count; k++)
                {
                    currentCell = activeWorksheet.Cells[column][row + k];

                    currentCell.Value2 = data.ColumnHeaders[k].Name.Remove(0, 3);
                }
            }
            range = activeWorksheet.Cells[endColumn][endRow];
            return range;
        }
 private static Type GetDataType(GaData.ColumnHeadersData gaColumn)
 {
     switch (gaColumn.DataType.ToLowerInvariant())
     {
         case "integer":
             return typeof(int);
         case "double":
             return typeof(double);
         case "currency":
             return typeof (decimal);
         case "time":
             return typeof(float);
         default:
             if (gaColumn.Name.ToLowerInvariant().Equals(GaMetadata.WithPrefix(GaMetadata.Dimensions.Time.Date)))
             {
                 return typeof(DateTime);
             }
             return typeof(string);
     }
 }
        private DataTable ToDataTable(GaData response, string name = "GA")
        {
            var requestResultTable = new DataTable(name);
            if (response != null)
            {
                requestResultTable.Columns.AddRange(response.ColumnHeaders.Select(c => new DataColumn(GaMetadata.RemovePrefix(c.Name), GetDataType(c))).ToArray());

                if (response.Rows != null)
                {
                    foreach (var row in response.Rows)
                    {
                        var dtRow = requestResultTable.NewRow();

                        for (var idx = 0; idx != requestResultTable.Columns.Count; idx++)
                        {
                            var col = requestResultTable.Columns[idx];
                            if (col.DataType == typeof(DateTime))
                            {
                                dtRow.SetField(col,
                                    DateTime.ParseExact(row[idx], "yyyyMMdd", new DateTimeFormatInfo(),
                                        DateTimeStyles.AssumeLocal));
                            }
                            else
                            {
                                dtRow.SetField(col, row[idx]);
                            }
                        }
                        requestResultTable.Rows.Add(dtRow);
                    }
                }
                requestResultTable.AcceptChanges();
            }
            return requestResultTable;
        }
Esempio n. 37
0
        private bool getGaData(int max, int index)
        {
            string id = GaViewDataGridView.SelectedCells[0].Value.ToString();
            string metrics = metricsTextBox.Text;

            DataResource.GaResource.GetRequest req = service.Data.Ga.Get(
                "ga:" + id,
                startDateTextBox.Text,
                endDateTextBox.Text,
                metrics);
            req.MaxResults = max;
            req.StartIndex = index;
            req.Dimensions = dimensionsTextBox.Text == "" ? null : dimensionsTextBox.Text;
            req.Filters = filterTextBox.Text == "" ? null : filterTextBox.Text;
            req.Sort = sortTextBox.Text == "" ? null : sortTextBox.Text;
            req.Segment = segmentTextBox.Text == "" ? null : segmentTextBox.Text;
            req.SamplingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.DEFAULT;

            try
            {
                gaData = req.Execute();
            }
            catch (System.Exception ex)
            {
                errorTextBox.Text = ex.Message;
                return false;
            }
            if(gaData.ContainsSampledData.Value){
                sampleTextBox.Text = Math.Round((decimal)((float)gaData.SampleSize / (float)gaData.SampleSpace) * 100, 2).ToString() +
                    "%(" + gaData.SampleSize.ToString() + "/" + gaData.SampleSpace.ToString() + ")";
            }else{
                sampleTextBox.Text = "WholeData";
            }
            return(true);
        }
Esempio n. 38
0
 private static void Serialize(GaData result, string filePath)
 {
     IGaDataSerializer serializer = new GaDataTsvRecursiveSerializer(filePath);
     serializer.Serialize(result);
 }