private void InitView() { AnalyticsService srv = new AnalyticsService(); var ctx = srv.CreateAuthorizationContext(); IAnalyticsSystemInfo systemInfo = srv.GetAnalyticsSystemInfo(); string dashboardName = this.Page.Request.Params["Dashboard"]; if (srv.HasDashboardAccess(dashboardName)) { IAnalyticsDashboard dashboard = srv.GetAnalyticsDashboard(dashboardName); string dashboardPath = dashboard.Path; DashboardTitle = dashboard.DisplayName; string url = string.Format(@"{0}/SLXDashboard.aspx?file={1}&AuthId={2}", systemInfo.WebPlayerUrl, HttpUtility.UrlEncode(dashboardPath), ctx.AuthId); //string url = string.Format(@"{0}/ViewAnalysis.aspx?file={1}", systemInfo.WebPlayerUrl, HttpUtility.UrlEncode(dashboardPath)); IframeDashboard.Attributes.Add("src", url); } else { divNoAccess.Style.Value = "display:Allow;"; divFrame.Style.Value = "display:none;"; } var workSpace = _parentWorkItem.Workspaces["MainContent"] as MainContentWorkspace; if (workSpace != null) { workSpace.HideTitleBar = true; } HtmlContainerControl localTitle = this.Page.Master.FindControl("localTitle") as HtmlContainerControl; if (localTitle != null) { localTitle.Style.Value = "display:none;"; } }
public AnalyticsController(IScribeDatabase database, IAuthenticationService authenticationService, INotificationHub notificationHub) : base(database, authenticationService) { _notificationHub = notificationHub; _service = new AnalyticsService(Database); }
/// <summary> /// Initializes a new instance of the <see cref="AboutPage"/> class. /// </summary> public AboutPage() { this.InitializeComponent(); AnalyticsService.Log(Constants.Analytics.Events.OpenAbout); }
public async Task TracksStartedTimeEntry() { await interactor.Execute(); AnalyticsService.Received().TrackStartedTimeEntry(TimeEntryStartOrigin.ContinueMostRecent); }
async void Save() { AnalyticsService.TrackEvent(Constants.Analytics.WeightEntryCategory, _isUpdating ? Constants.Analytics.WeightEntry_UpdateWeight : Constants.Analytics.WeightEntry_AddedWeight, 1); // convert entered value to a valid weight decimal weightValue; if (!decimal.TryParse(Weight, out weightValue)) { // show error about invalid value if we can't convert the entered value to a decimal await DialogService.DisplayAlertAsync(Constants.Strings.WeightEntryPage_InvalidWeight_Title, Constants.Strings.WeightEntryPage_InvalidWeight_Message, Constants.Strings.GENERIC_OK); return; } try { IncrementPendingRequestCount(); // see if they already have an entry for this date and if so get them to confirm it being replaced var existingEntry = await DataService.GetWeightEntryForDate(Date); if (existingEntry != null) { // if we aren't updating, and the values aren't equal then show a warning (no need to show warning if the weights are the same) if (!_isUpdating && existingEntry.Weight != weightValue) { // show warning that an existing entry will be updated (is actually deleted and re-added), allow them to cancel var result = await DialogService.DisplayAlertAsync(Constants.Strings.Common_UpdateExistingWeight_Title, string.Format(Constants.Strings.Common_UpdateExistingWeight_Message, existingEntry.Weight, Date, weightValue), Constants.Strings.GENERIC_OK, Constants.Strings.GENERIC_CANCEL); // if they canceled the dialog then return without changing anything if (!result) { return; } } // remove existing weight now that they've confirmed if (!await DataService.RemoveWeightEntryForDate(Date)) { AnalyticsService.TrackError($"{nameof(Save)} - an error occurred trying to remove existing weight entry"); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.WeightEntryPage_Save_RemoveExistingWeightFailed_Message, Constants.Strings.GENERIC_OK); return; } } // create a new weight entry and add it var entry = new WeightEntry(Date, weightValue); if (!await DataService.AddWeightEntry(entry)) { AnalyticsService.TrackError($"{nameof(Save)} - an error occurred trying to add new weight entry"); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.WeightEntryPage_Save_AddingWeightFailed_Message, Constants.Strings.GENERIC_OK); return; } // see if the new weight entered matches the start date of the goal, if so update the goal with the new weight var goal = await DataService.GetGoal(); if (goal != null && goal.StartDate.Date == Date) { var success = true; if (!await DataService.RemoveGoal()) { success = false; } if (success) { if (!await DataService.SetGoal(new WeightLossGoal(goal.StartDate, weightValue, goal.GoalDate, goal.GoalWeight))) { success = false; } } if (!success) { AnalyticsService.TrackError($"{nameof(Save)} - an error occurred trying to update start date of existing goal"); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.WeightEntryPage_Save_RemoveExistingWeightFailed_Message, Constants.Strings.GENERIC_OK); return; } } await NavigationService.GoBackAsync(useModalNavigation : true); // pop the dialog and return home } catch (Exception ex) { AnalyticsService.TrackFatalError($"{nameof(Save)} - an exception occurred.", ex); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.WeightEntryPage_Save_Exception_Message, Constants.Strings.GENERIC_OK); } finally { DecrementPendingRequestCount(); } }
public async Task <IActionResult> Login([FromServices] IGoogleAuthProvider auth) { var cred = await auth.GetCredentialAsync(); var service = new AnalyticsService(new BaseClientService.Initializer { HttpClientInitializer = cred }); // var accessToken = await cred.UnderlyingCredential.GetAccessTokenForRequestAsync(); // WebRequest request = WebRequest.Create($"https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}"); // HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Stream dataStream = response.GetResponseStream(); // StreamReader reader = new StreamReader(dataStream); // string responseFromServer = reader.ReadToEnd(); // var data = JsonConvert.DeserializeObject<GoogleUser>(responseFromServer); // cleaned up above a little bit var accessToken = await cred.UnderlyingCredential.GetAccessTokenForRequestAsync(); WebRequest request = WebRequest.Create($"https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); var json = new JsonTextReader(reader); var data = (new JsonSerializer()).Deserialize <GoogleUser>(json); var user = await context.User.FirstOrDefaultAsync(u => u.GoogleId == data.id); if (user == null) { user = new User(data); await context.User.AddAsync(user); } user.Token = accessToken; await context.SaveChangesAsync(); // clear the "cache" // MATCHING USER ID && ACCOUNT ID var accountsToDelete = context.AccountsCache.Where(w => w.UserId == user.Id); foreach (var account in accountsToDelete) { var filtersToDelete = context.FiltersCache.Where(w => w.AccountsCacheId == account.Id); context.FiltersCache.RemoveRange(filtersToDelete); } context.AccountsCache.RemoveRange(accountsToDelete); await context.SaveChangesAsync(); var accounts = await service.Management.Accounts.List().ExecuteAsync(); foreach (var account in accounts.Items) { var _account = new AccountsCache { GoogleAccountId = account.Id, Name = account.Name, UserId = user.Id }; // save the account await context.AccountsCache.AddAsync(_account); // get the filters var filters = await service.Management.Filters.List(account.Id).ExecuteAsync(); // save the filters var excludeFilters = filters.Items.Where(w => w.ExcludeDetails != null); foreach (var filter in excludeFilters) { var _filter = new FiltersCache { Name = filter.Name, GoogleFilterId = filter.Id, FilterValue = filter.ExcludeDetails.ExpressionValue, AccountsCacheId = _account.Id }; await context.FiltersCache.AddAsync(_filter); } } await context.SaveChangesAsync(); return(Redirect("/app")); }
protected void btnOpenWebPalyer_ClickAction(object sender, EventArgs e) { AnalyticsService srv = new AnalyticsService(); AnalyticsSystemInfo = srv.GetAnalyticsSystemInfo(); var ctx = srv.CreateAuthorizationContext(); string url = string.Format("{0}?AuthId={1}", txtWebPlayerUrl.Text, ctx.AuthId); TestUrl(url); }
public void OnNavigatedTo(NavigationParameters parameters) { AnalyticsService.TrackPageView(Constants.Analytics.Page_About); }
protected void Page_Load(object sender, EventArgs e) { if (!SettingsSEO.GoogleAnalyticsApiEnabled || SettingsSEO.GoogleAnalyticsNumber.IsNullOrEmpty() || SettingsSEO.GoogleAnalyticsClientID.IsNullOrEmpty() || SettingsSEO.GoogleAnalyticsClientSecret.IsNullOrEmpty()) { lnkGoSettings.Visible = true; return; } var _authenticator = CreateAuthenticator(); var _service = new AnalyticsService(_authenticator); // check if OAuth2 authentication code was passed if (HttpContext.Current.Request["code"] != null) { _authenticator.LoadAccessToken(); Response.Redirect("default.aspx"); } if (!IsPostBack) { Profiles myProfiles; try { // get analytics profiles in account myProfiles = _service.Management.Profiles.List("~all", "~all").Fetch(); } catch (Exception ex) { Debug.LogError(ex, false); return; } var profile = myProfiles != null && myProfiles.Items != null ? myProfiles.Items.FirstOrDefault(item => item.WebPropertyId == "UA-" + SettingsSEO.GoogleAnalyticsNumber) : null; if (profile == null) { return; } if (myProfiles.Items.Count > 0) { // get sample statistics for first profile found var request = _service.Data.Ga.Get( "ga:" + profile.Id, DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"), "ga:pageviews,ga:visitors,ga:visits" ); request.Dimensions = "ga:date"; request.StartIndex = 1; request.MaxResults = 500; GaData results = request.Fetch(); lblViewPagesToday.Text = results.Rows[results.Rows.Count - 1][1]; lblVisitorsToday.Text = results.Rows[results.Rows.Count - 1][2]; lblVisitsToday.Text = results.Rows[results.Rows.Count - 1][3]; lblViewPagesYesterday.Text = results.Rows[results.Rows.Count - 2][1]; lblVisitorsYesterday.Text = results.Rows[results.Rows.Count - 2][2]; lblVisitsYesterday.Text = results.Rows[results.Rows.Count - 2][3]; var pagesChart = string.Empty; var visitorsChart = string.Empty; var visitsChart = string.Empty; foreach (var row in results.Rows) { var datetime = Convert.ToDateTime(row[0].Substring(0, 4) + '.' + row[0].Substring(4, 2) + '.' + row[0].Substring(6, 2)); pagesChart += "[" + GetTimestamp(datetime) + "," + row[1] + "],"; visitorsChart += "[" + GetTimestamp(datetime) + "," + row[2] + "],"; visitsChart += "[" + GetTimestamp(datetime) + "," + row[3] + "],"; } chartData = string.Format( "[{{label: '{0}', data:[{1}]}}, {{label: '{2}', data:[{3}]}}, {{label: '{4}', data:[{5}]}}]", Resources.Resource.Admin_Statistics_PageViews, pagesChart, Resources.Resource.Admin_Statistics_Visitors, visitorsChart, Resources.Resource.Admin_Statistics_Visits, visitsChart); } } }
private void LoadView() { IAnalayticsService srv = new AnalyticsService(); AnalyticsSystemInfo = srv.GetAnalyticsSystemInfo(); txtSystemUrl.Text = AnalyticsSystemInfo.URL; txtWebPlayerUrl.Text = AnalyticsSystemInfo.WebPlayerUrl; LoadDashboards(); }
private void LoadDashboards() { IList<IAnalyticsDashboard> dashboards = new List<IAnalyticsDashboard>(); AnalyticsService srv = new AnalyticsService(); dashboards = srv.GetAnalyticsDashboards(); AnalyticsSystemInfo = srv.GetAnalyticsSystemInfo(); grdDashboards.DataSource = dashboards; grdDashboards.DataBind(); }
private void AddDashbaordActions(IRole role) { AnalyticsService srv = new AnalyticsService(); IList<IAnalyticsDashboard> dashboards = srv.GetAnalyticsDashboards(); foreach (IAnalyticsDashboard dashboard in dashboards) { string actionKey = string.Format(@"AdvancedAnalytics/Dashboard/{0}", dashboard.DashboardName); AddAction(actionKey, dashboard.DisplayName, role); } }
private void AddDashbaord(string dashboardName, string displayName, string path) { AnalyticsService srv = new AnalyticsService(); IAnalyticsDashboard dashboard = srv.GetAnalyticsDashboard(dashboardName); if (dashboard == null) { dashboard = Sage.Platform.EntityFactory.Create<IAnalyticsDashboard>(); dashboard.DashboardName = dashboardName; dashboard.DisplayName = displayName; dashboard.Path = path; dashboard.Save(); } }
protected void TestDashboard(IAnalyticsDashboard dashbaord) { AnalyticsService srv = new AnalyticsService(); AnalyticsSystemInfo = srv.GetAnalyticsSystemInfo(); var ctx = srv.CreateAuthorizationContext(); string dashboardPath = dashbaord.Path; string url = string.Format(@"{0}/SLXDashboard.aspx?file={1}&AuthId={2}", AnalyticsSystemInfo.WebPlayerUrl, HttpUtility.UrlEncode(dashboardPath), ctx.AuthId); TestUrl(url); }
protected void btnSave_ClickAction(object sender, EventArgs e) { IAnalayticsService srv = new AnalyticsService(); AnalyticsSystemInfo = srv.GetAnalyticsSystemInfo(); AnalyticsSystemInfo.URL = txtSystemUrl.Text; AnalyticsSystemInfo.WebPlayerUrl = txtWebPlayerUrl.Text; AnalyticsSystemInfo.Save(); }
async void Save() { AnalyticsService.TrackEvent(Constants.Analytics.SetGoalCategory, Constants.Analytics.SetGoal_SavedGoal, 1); // convert entered value to a valid weight bool parsedWeightFields = true; decimal startWeight = 0; decimal goalWeight = 0; if (ShowStonesEntryFields) { var startWeightStoneFields = GetStartWeightInStones(); var goalWeightStoneFields = GetGoalWeightInStones(); if (startWeightStoneFields == null || goalWeightStoneFields == null) { parsedWeightFields = false; } else { startWeight = startWeightStoneFields.ToPoundsDecimal(); goalWeight = goalWeightStoneFields.ToPoundsDecimal(); } } else { if (!decimal.TryParse(StartWeight, NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out startWeight) || !decimal.TryParse(GoalWeight, NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out goalWeight)) { parsedWeightFields = false; } } if (!parsedWeightFields) { // show error about invalid value if we can't convert the entered value to a decimal await DialogService.DisplayAlertAsync(Constants.Strings.SetGoalPage_InvalidWeight_Title, Constants.Strings.SetGoalPage_InvalidWeight_Message, Constants.Strings.Generic_OK); return; } // give warning if goal weight is greater than start weight // NOTE:: we don't prevent this scenario as I have had friends intentionally use the previous version of line diet for // tracking weight gain during pregnancy or muscle building - so we just give a warning. We also don't prevent equal // start and goal weights in case they just want a line to show a maintenance weight they are trying to stay at if (goalWeight > startWeight) { // TODO:: analytics var result = await DialogService.DisplayAlertAsync(Constants.Strings.SetGoalPage_GoalWeightGreaterThanStartWeight_Title, Constants.Strings.SetGoalpage_GoalWeightGreaterThanStartWeight_Message, Constants.Strings.Generic_OK, Constants.Strings.Generic_Cancel); if (!result) { return; } } try { IncrementPendingRequestCount(); // see if they've entered a different weight already for this date, if so warn them about it being updated var existingEntry = await DataService.GetWeightEntryForDate(StartDate); if (existingEntry != null) { if (existingEntry.Weight != startWeight) { // show different message for stones/pounds string warningMessage; if (ShowStonesEntryFields) { var existingWeightInStones = existingEntry.Weight.ToStonesAndPounds(); var startWeightInStones = startWeight.ToStonesAndPounds(); warningMessage = string.Format(Constants.Strings.Common_UpdateExistingWeight_Message, string.Format(Constants.Strings.Common_Stones_WeightFormat, existingWeightInStones.Stones, existingWeightInStones.Pounds), StartDate, string.Format(Constants.Strings.Common_Stones_WeightFormat, startWeightInStones.Stones, startWeightInStones.Pounds)); } else { warningMessage = string.Format(Constants.Strings.Common_UpdateExistingWeight_Message, existingEntry.Weight, StartDate, startWeight); } // show warning that an existing entry will be updated (is actually deleted and re-added), allow them to cancel var result = await DialogService.DisplayAlertAsync(Constants.Strings.Common_UpdateExistingWeight_Title, warningMessage, Constants.Strings.Generic_OK, Constants.Strings.Generic_Cancel); // if they canceled the dialog then return without changing anything if (!result) { return; } } // remove existing weight if (!await DataService.RemoveWeightEntryForDate(StartDate)) { AnalyticsService.TrackError($"{nameof(Save)} - Error when trying to remove existing weight entry for start date"); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.SetGoalPage_Save_RemoveExistingWeightFailed_Message, Constants.Strings.Generic_OK); return; } } var addStartWeightResult = await DataService.AddWeightEntry(new WeightEntry(StartDate, startWeight, SettingsService.WeightUnit)); if (!addStartWeightResult) { AnalyticsService.TrackError($"{nameof(Save)} - Error when trying to add weight entry for start date"); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.SetGoalPage_Save_AddingWeightFailed_Message, Constants.Strings.Generic_OK); return; } var weightLossGoal = new WeightLossGoal(StartDate, startWeight, GoalDate.Date, goalWeight, SettingsService.WeightUnit); if (!await DataService.SetGoal(weightLossGoal)) { AnalyticsService.TrackError($"{nameof(Save)} - Error when trying to save new weight loss goal"); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.SetGoalPage_Save_AddingGoalFailed_Message, Constants.Strings.Generic_OK); return; } await NavigationService.GoBackAsync(useModalNavigation : true); } catch (Exception ex) { AnalyticsService.TrackFatalError($"{nameof(Save)} - an exception occurred.", ex); await DialogService.DisplayAlertAsync(Constants.Strings.Common_SaveError, Constants.Strings.SetGoalPage_Save_Exception_Message, Constants.Strings.Generic_OK); } finally { DecrementPendingRequestCount(); } }
public override void OnBackPressed() { base.OnBackPressed(); AnalyticsService.TrackEvent(AnalyticsService.Event.ReturnBackToImageInputPage); }
public void TracksSignupEvent() { AnalyticsService .Received() .TrackSignUpEvent(AuthenticationMethod.EmailAndPassword); }
async void ShowAddWeightScreen() { AnalyticsService.TrackEvent(Constants.Analytics.DailyInfoCategory, Constants.Analytics.DailyInfo_LaunchedAddWeight, 1); await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{nameof(WeightEntryPage)}", useModalNavigation : true); }
public AnalyticsController(IRefinedDataRepository dataRepository, AnalyticsService analyticsService) { this.repository = dataRepository; this.analyticsService = analyticsService; }
public void InitializeGameAnalytics() { if (!base.Inited) { AnalyticsService analytics = PersistentSingleton <AnalyticsService> .Instance; IAPService instance = PersistentSingleton <IAPService> .Instance; AdService instance2 = PersistentSingleton <AdService> .Instance; SessionService sessionService = PersistentSingleton <SessionService> .Instance; PlayerData playerData = PlayerData.Instance; instance.IAPCompleted.Subscribe(delegate(IAPTransactionState iapCompleted) { analytics.TrackEvent("IAP_Complete", iapCompleted.asDictionary(), string.Empty); }); instance.IAPNotCompleted.Subscribe(delegate(IAPNotCompleted iapNotCompleted) { analytics.TrackEvent("IAP_Not_Complete", iapNotCompleted.asDictionary(), string.Empty); }); instance.IAPValidated.Subscribe(delegate(IAPTransactionState iapValidated) { analytics.TrackEvent("IAP_Validated", iapValidated.asDictionary(), string.Empty); }); instance2.AdStarted.Subscribe(delegate(AdWatched adStarted) { analytics.TrackEvent("Ad_Started", adStarted.asDictionary(), string.Empty); }); (from adResult in instance2.AdResults where adResult.result == AdService.V2PShowResult.Finished select adResult).Subscribe(delegate(AdWatched adWatched) { analytics.TrackEvent("Ad_Watched", adWatched.asDictionary(), "fb_mobile_content_view"); }); (from adResult in instance2.AdResults where adResult.result == AdService.V2PShowResult.Failed || adResult.result == AdService.V2PShowResult.Skipped select adResult).Subscribe(delegate(AdWatched adFailed) { analytics.TrackEvent("Ad_Failed", adFailed.asDictionary(), string.Empty); }); (from a in instance2.AdLoadRequests select a.asDictionary(ServerTimeService.NowTicks())).Subscribe(delegate(Dictionary <string, string> adLoadRequest) { analytics.TrackEvent("Ad_Load", adLoadRequest, string.Empty); }); (from isNewUser in sessionService.newUser where isNewUser select isNewUser).Subscribe(delegate { analytics.TrackEvent("New_User", new Dictionary <string, string>(), string.Empty); }); playerData.SessionNumber.Subscribe(delegate { analytics.TrackEvent("Session_Started", new Dictionary <string, string> { { "LastSavedBy", playerData.LastSavedBy }, { "HoursSinceLastSession", ((int)TimeSpan.FromTicks(sessionService.TicksSinceLastSave()).TotalHours).ToString() }, { "Lifetime_BlocksDestroyed", CountLifetimeBlocksDestroyed() } }, string.Empty); }); playerData.SessionNumber.Subscribe(delegate { analytics.TrackEvent("Session_Balance", new Dictionary <string, string> { { "Material_Grass", playerData.BlocksCollected[0].Value.ToString() }, { "Material_Dirt", playerData.BlocksCollected[1].Value.ToString() }, { "Material_Wood", playerData.BlocksCollected[2].Value.ToString() }, { "Material_Stone", playerData.BlocksCollected[3].Value.ToString() }, { "Material_Metal", playerData.BlocksCollected[4].Value.ToString() }, { "Material_Gold", playerData.BlocksCollected[5].Value.ToString() }, { "Material_Jelly", playerData.BlocksCollected[6].Value.ToString() } }, string.Empty); }); (from ord in PrestigeTriggered where ord == PrestigeOrder.PrestigeStart select ord).Subscribe(delegate { analytics.TrackEvent("Prestige", new Dictionary <string, string> { { "Material_Grass", ((double)playerData.BlocksInBackpack[0].Value * Singleton <CumulativeBonusRunner> .Instance.BonusMult[13].Value.ToDouble()).ToString() }, { "Material_Dirt", ((double)playerData.BlocksInBackpack[1].Value * Singleton <CumulativeBonusRunner> .Instance.BonusMult[14].Value.ToDouble()).ToString() }, { "Material_Wood", ((double)playerData.BlocksInBackpack[2].Value * Singleton <CumulativeBonusRunner> .Instance.BonusMult[15].Value.ToDouble()).ToString() }, { "Material_Stone", ((double)playerData.BlocksInBackpack[3].Value * Singleton <CumulativeBonusRunner> .Instance.BonusMult[16].Value.ToDouble()).ToString() }, { "Material_Metal", ((double)playerData.BlocksInBackpack[4].Value * Singleton <CumulativeBonusRunner> .Instance.BonusMult[17].Value.ToDouble()).ToString() }, { "Material_Gold", ((double)playerData.BlocksInBackpack[5].Value * Singleton <CumulativeBonusRunner> .Instance.BonusMult[18].Value.ToDouble()).ToString() }, { "Material_Jelly", ((double)playerData.BlocksInBackpack[6].Value * Singleton <CumulativeBonusRunner> .Instance.BonusMult[19].Value.ToDouble()).ToString() } }, string.Empty); }); playerData.TutorialStep.Skip(1).Subscribe(delegate(int step) { analytics.TrackEvent("FTUE_Stage_Done", new Dictionary <string, string> { { "FTUE_Stage", Singleton <TutorialGoalCollectionRunner> .Instance.GetOrCreatePlayerGoalRunner(step - 1).GoalConfig.ID }, { "FTUE_Stage_ID", (step - 1).ToString() } }, (step < Singleton <EconomyHelpers> .Instance.GetTutorialGoalAmount() - 1) ? string.Empty : "fb_mobile_tutorial_completion"); }); playerData.TutorialStep.Skip(1).Subscribe(delegate(int step) { Analytics.CustomEvent("FTUE_Stage_Done", new Dictionary <string, object> { { "FTUE_Stage", Singleton <TutorialGoalCollectionRunner> .Instance.GetOrCreatePlayerGoalRunner(step - 1).GoalConfig.ID }, { "FTUE_Stage_ID", (step - 1).ToString() } }); }); GemTransactions.Subscribe(delegate(GemTransaction transaction) { analytics.TrackEvent("Gem_Transaction", transaction.asDictionary(), (!(transaction.transaction == "spendFunds")) ? string.Empty : "fb_mobile_spent_credits", transaction.amount); }); ChestTransactions.Subscribe(delegate(ChestTransaction transaction) { analytics.TrackEvent("Chest_Transaction", transaction.asDictionary(), string.Empty); }); KeyTransactions.Subscribe(delegate(KeyTransaction transaction) { analytics.TrackEvent("Key_Added", transaction.asDictionary(), string.Empty); }); BerryTransaction.Subscribe(delegate(BerryTransaction transaction) { analytics.TrackEvent("Berry_Added", transaction.asDictionary(), string.Empty); }); PopupDecisions.Subscribe(delegate(PopupDecision decision) { analytics.TrackEvent("Popup_Decision", decision.asDictionary(), string.Empty); }); (from coins in playerData.LifetimeCoins.Pairwise() where coins.Previous.exponent != coins.Current.exponent select coins).Subscribe(delegate { analytics.TrackEvent("New_LTE_Digit", new Dictionary <string, string>(), string.Empty); }); playerData.LifetimeChunk.Skip(1).Subscribe(delegate { analytics.TrackEvent("New_Max_Chunk", new Dictionary <string, string>(), string.Empty); }); playerData.LifetimeCreatures.Skip(1).Subscribe(delegate { analytics.TrackEvent("New_Max_Companions", new Dictionary <string, string>(), string.Empty); }); HeroStateFactory.GetOrCreateHeroState(0).LifetimeLevel.Skip(1).Subscribe(delegate { analytics.TrackEvent("New_Max_Hero_Level", new Dictionary <string, string>(), string.Empty); }); GoalCompleted.Subscribe(delegate(PlayerGoalRunner goal) { analytics.TrackEvent("Achievement_Completed", new Dictionary <string, string> { { "Goal_ID", goal.GoalConfig.ID } }, "fb_mobile_achievement_unlocked"); }); NewBundle.Subscribe(delegate(IAPProductEnum bundle) { analytics.TrackEvent("Offer_Given", new Dictionary <string, string> { { "Offer", bundle.ToString() } }, string.Empty); }); GearUpgraded.Subscribe(delegate(GearRunner gear) { analytics.TrackEvent("Gear_Upgrade", new Dictionary <string, string> { { "GearLevel", gear.Level.ToString() }, { "GearID", gear.GearIndex.ToString() } }, string.Empty); }); SkillUsed.Subscribe(delegate(SkillsEnum skill) { analytics.TrackEvent("Skill_Used", new Dictionary <string, string> { { "Skill", skill.ToString() }, { "Lifetime_Used", playerData.SkillStates[(int)skill].LifetimeUsed.Value.ToString() } }, string.Empty); }); BossBattleResult.Skip(1).Subscribe(delegate(bool result) { analytics.TrackEvent("BossBattleResult", new Dictionary <string, string> { { "Result", result.ToString() }, { "Current_Chunk", playerData.MainChunk.Value.ToString() } }, string.Empty); }); ObjectTapped.Subscribe(delegate(string obj) { analytics.TrackEvent("Object_Tapped", new Dictionary <string, string> { { "Object_Tapped", obj } }, string.Empty); }); /*XPromoPlugin.XPromoActions.Subscribe(delegate(XPromoAction XPromoAction) * { * analytics.TrackEvent("X_Promo_Action", XPromoAction.asDictionary(), string.Empty); * });*/ PersistentSingleton <ARService> .Instance.LevelEditorEvent.Subscribe(delegate(string editorEvent) { analytics.TrackEvent("Level_Editor", new Dictionary <string, string> { { "Event", editorEvent } }, string.Empty); }); PersistentSingleton <AnalyticsService> .Instance.FortunePodsResult.Subscribe(delegate(FortunePodResult result) { analytics.TrackEvent("Fortune_Pod_Result", result.asDictionary(), string.Empty); }); (from chunk in playerData.MainChunk.Skip(1) where chunk == 22 && PlayerData.Instance.LifetimePrestiges.Value == 0 && !Singleton <QualitySettingsRunner> .Instance.LowFPS.Value select chunk).Subscribe(delegate { SceneLoader.Instance.StartCoroutine(TrackFpsRuotine()); }); (from hr in playerData.HasReviewed.Skip(1) where hr select hr).Subscribe(delegate { analytics.TrackEvent("fb_mobile_rate", new Dictionary <string, string> { { "fb_max_rating_value", "5" } }, "fb_mobile_rate", 5f); }); playerData.Trophies.Skip(1).Subscribe(delegate(int trophies) { AnalyticsService analyticsService = analytics; Dictionary <string, string> dictionary = new Dictionary <string, string>(); Dictionary <string, string> dictionary2 = dictionary; TournamentTier tournamentTier = (TournamentTier)trophies; dictionary2.Add("RewardType", tournamentTier.ToString()); analyticsService.TrackEvent("TournamentReward", dictionary, string.Empty); }); (from tour in TournamentEvent where tour select tour).Subscribe(delegate { analytics.TrackEvent("TournamentStarted", new Dictionary <string, string> { { "Current_Chunk", playerData.MainChunk.Value.ToString() } }, string.Empty); }); (from tour in TournamentEvent where !tour select tour).Subscribe(delegate { analytics.TrackEvent("TournamentEnded", new Dictionary <string, string> { { "Current_Chunk", playerData.MainChunk.Value.ToString() }, { "Highest_Chunk_Reached", Singleton <TournamentRunner> .Instance.PlayerHighestWorld.Value.ToString() }, { "Position", Singleton <TournamentRunner> .Instance.PlayerRank.Value.ToString() } }, string.Empty); }); (from p in Observable.EveryApplicationPause() where !p && FB.IsInitialized select p).Subscribe(delegate { FB.ActivateApp(); }); FirebaseAnalytics.SetUserId(playerData.PlayerId); FirebaseAnalytics.SetUserProperty("AppGenuine", (!Application.genuineCheckAvailable) ? "N/A" : Application.genuine.ToString()); FirebaseAnalytics.SetUserProperty("Build_Number", Application.version); subscribeToUserProperty("Days_Retained", playerData.DaysRetained); // FirebaseAnalytics.SetUserProperty("Games_Installed", XPromoPlugin.InstalledApps()); FirebaseAnalytics.SetUserProperty("Friends_Giftable", PersistentSingleton <FacebookAPIService> .Instance.FBPlayers.Count.ToString()); FirebaseAnalytics.SetUserProperty("Friends_Playing", PersistentSingleton <FacebookAPIService> .Instance.FBPlayers.Values.Count((FBPlayer p) => p.Playing).ToString()); subscribeToUserProperty("Has_Reviewed", playerData.HasReviewed); FirebaseAnalytics.SetUserProperty("Hours_In_Lifetime", ((int)TimeSpan.FromTicks(sessionService.TicksPlayedInLifetime()).TotalHours).ToString()); FirebaseAnalytics.SetUserProperty("Segments", string.Join(",", PersistentSingleton <GameSettings> .Instance.Segments.ToArray())); subscribeToUserProperty("Music", MusicVolume); subscribeToUserProperty("Notifications_Decided", playerData.NotificationDecision); subscribeToUserProperty("Online", ConnectivityService.InternetConnectionAvailable); subscribeToUserProperty("Review_State", playerData.ReviewState); subscribeToUserProperty("Sound", SFXVolume); subscribeToUserProperty("AR_Editor_Supported", ARSupported); FirebaseAnalytics.SetUserProperty("Language", playerData.Language); FirebaseAnalytics.SetUserProperty("PFID", playerData.PFId.Value); FirebaseAnalytics.SetUserProperty("FBID", playerData.FBId.Value); base.Inited = true; } }
public async Task ResetsTheAppCenterId() { await interactor.Execute(); AnalyticsService.Received().ResetAppCenterUserId(); }
public void Setup() { _shareRepoMoq = new Mock <IShareRepository>(); _analyticsService = new AnalyticsService(_shareRepoMoq.Object); }
public async Task <ActionResult> DisplayChartByDept(FormCollection formCollection, string sessionId) { int month = monthsInInt[formCollection["month"]]; int year = int.Parse(formCollection["year"]); ViewData["monthsInInt"] = monthsInInt; ViewData["month"] = month; ViewData["year"] = year; ViewData["monthsToDisplay"] = monthsToDisplay; ViewData["department"] = formCollection["department"]; List <RequisitionDetails> reqs = AnalyticsService.GetRequisitionsByDept(formCollection["department"]); //Export reqs to CSV //StringWriter sw = new StringWriter(); //sw.WriteLine("\"monthOfRequest\",\"yearOfRequest\",\"quantity\""); //Response.ClearContent(); //Response.AddHeader("content-disposition", "attachment;filename=dept_reqs.csv"); //Response.ContentType = "text/csv"; //foreach (var req in reqs) //{ // sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"", // req.MonthOfRequest, // req.YearOfRequest, // req.Quantity)); //} //Response.Write(sw.ToString()); //Response.End(); Dictionary <Tuple <int, int>, int> totalQuantitiesByMonthAndYear = AnalyticsService.GetTotalQuantitiesByMonthAndYear(reqs); //For months with no value, to fill it with 0. Dictionary <string, int> monthsAndQuantitiesForChart = AnalyticsService.FillEmptyData(totalQuantitiesByMonthAndYear, months, month, year); //Contact Python API to get predictions for next 3 months for only English Dept, Commerce Dept and Computer Science string data; string[] preds = new string[] { }; if (formCollection["department"] == "English Dept" || formCollection["department"] == "Commerce Dept" || formCollection["department"] == "Computer Science") { data = await AnalyticsService.GetRequest("http://127.0.0.1:5000/" + formCollection["department"]); preds = data.Split(new char[] { ',', '[', ']' }, StringSplitOptions.RemoveEmptyEntries); } //Put predictions in dictionary for displaying if (month == currentMonth && (formCollection["department"] == "English Dept" || formCollection["department"] == "Commerce Dept" || formCollection["department"] == "Computer Science")) { if (month == 12) { monthsAndQuantitiesForChart[months[month] + " " + year + " (Predicted)"] = (int)Math.Round(double.Parse(preds[0])); monthsAndQuantitiesForChart[months[1] + " " + (year + 1) + " (Predicted)"] = (int)Math.Round(double.Parse(preds[1])); monthsAndQuantitiesForChart[months[2] + " " + (year + 1) + " (Predicted)"] = (int)Math.Round(double.Parse(preds[2])); } else if (month == 11) { monthsAndQuantitiesForChart[months[month] + " " + year + " (Predicted)"] = (int)Math.Round(double.Parse(preds[0])); monthsAndQuantitiesForChart[months[month + 1] + " " + year + " (Predicted)"] = (int)Math.Round(double.Parse(preds[1])); monthsAndQuantitiesForChart[months[1] + " " + (year + 1) + " (Predicted)"] = (int)Math.Round(double.Parse(preds[2])); } else { monthsAndQuantitiesForChart[months[month] + " " + year + " (Predicted)"] = (int)Math.Round(double.Parse(preds[0])); monthsAndQuantitiesForChart[months[month + 1] + " " + year + " (Predicted)"] = (int)Math.Round(double.Parse(preds[1])); monthsAndQuantitiesForChart[months[month + 2] + " " + year + " (Predicted)"] = (int)Math.Round(double.Parse(preds[2])); } } ViewData["monthsAndQuantitiesForChart"] = monthsAndQuantitiesForChart; ViewData["sessionId"] = sessionId; return(View()); }
public override void ViewDidLoad() { base.ViewDidLoad(); AnalyticsService.TrackEvent(AnalyticsService.Event.ResultsPageViewed); //Programmatically add a back button and an arrow UIImage backArrowImage = UIImage.FromBundle("back-arrow"); UIButton backButton = new UIButton(UIButtonType.Custom); backButton.SetImage(backArrowImage, UIControlState.Normal); backButton.SetTitle("Back", UIControlState.Normal); backButton.ImageEdgeInsets = new UIEdgeInsets(0.0f, -12.5f, 0.0f, 0.0f); backButton.AddTarget((sender, e) => { AnalyticsService.TrackEvent(AnalyticsService.Event.ReturnBackToCroppingPage); this.NavigationController?.PopViewController(true); }, UIControlEvent.TouchUpInside); this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(backButton); UIButton newSession = new UIButton(UIButtonType.Custom); newSession.SetTitle("New Session", UIControlState.Normal); newSession.AddTarget((sender, e) => { AnalyticsService.TrackEvent(AnalyticsService.Event.ReturnBackToImageInputPage); this.NavigationController?.PopToRootViewController(true); }, UIControlEvent.TouchUpInside); this.NavigationItem.RightBarButtonItem = new UIBarButtonItem(newSession); // Set nav bar attributes NavigationControllerUtil.SetNavigationBarAttributes(this.NavigationController.NavigationBar); NavigationControllerUtil.SetNavigationTitle(this.NavigationItem, NavBarTitle); InputImage = InputImage.Scale(new CoreGraphics.CGSize(LoadImageWidth, LoadImageHeight)); // Initialize UIImageView imageView = new UIImageView(); imageView.Frame = new CGRect(0, 0, InputImage.Size.Width, InputImage.Size.Height); imageView.Image = InputImage; imageView.UserInteractionEnabled = true; // Initialize original imageview originalImageView = new UIImageView(); originalImageView.Frame = new CGRect(0, 0, InputImage.Size.Width, InputImage.Size.Height); originalImageView.Image = InputImage; originalImageView.UserInteractionEnabled = true; // Initialize meta-data display string filename; DateTime?time; try { filename = GetFileString(ImageUrl, DefaultFileStringForCamera); time = GetDate(ImageUrl); } catch (NullReferenceException ex) { filename = DefaultFileStringForCamera; time = DateTime.Now; } AnalyzedImageFileNameLabel.Text = filename; AnalyzedImageDateLabel.Text = time.HasValue ? time.Value.ToShortDateString() : DefaultNoDateDisplay; OriginalImageFileNameLabel.Text = filename; OriginalImageDateLabel.Text = time.HasValue ? time.Value.ToShortDateString() : DefaultNoDateDisplay; // Add all original labels to List<UILabel> originalLabels = new List <UILabel>(); originalLabels.Add(OriginalImageDateLabel); originalLabels.Add(OriginalImageDateHeaderLabel); originalLabels.Add(OriginalImageFileNameLabel); originalLabels.Add(OriginalImageFileNameHeaderLabel); // Toggle accessibilty off for all original labels (they are initially hidden) EnableVoiceOverForViews(originalLabels.ToArray(), false); SetDisplayBorders(); // Retrieve the shared AI Client that was loaded by the AppDelegate aiClient = ((AppDelegate)UIApplication.SharedApplication.Delegate).AIClient; System.Diagnostics.Debug.WriteLine("AI Client retrieved from AppDelegate"); }
static void Main(string[] args) { System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); // Adding JSON file into IConfiguration. IConfiguration config = new ConfigurationBuilder().AddJsonFile("config/appsettings.json", true, true).Build(); string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data var keyFilePath = "config/analytics.p12"; // Downloaded from https://console.developers.google.com var serviceAccountEmail = config["ServiceAccountEmail"]; // found https://console.developers.google.com //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Analytics API Sample", }); while (true) { try { DataResource.RealtimeResource.GetRequest realtimeReq = service.Data.Realtime.Get(String.Format("ga:{0}", config["GAID"]), "rt:activeUsers"); realtimeReq.Dimensions = "rt:country,rt:region,rt:city,rt:deviceCategory,rt:latitude,rt:longitude"; realtimeReq.Sort = "rt:activeUsers"; DataResource.RealtimeResource.GetRequest realtimePageViewsReq = service.Data.Realtime.Get(String.Format("ga:{0}", config["GAID"]), "rt:pageviews"); realtimePageViewsReq.Dimensions = "rt:country,rt:region,rt:city,rt:deviceCategory,rt:latitude,rt:longitude"; realtimePageViewsReq.Sort = "rt:pageviews"; RealtimeData realtime = realtimeReq.Execute(); RealtimeData realtimePageViews = realtimePageViewsReq.Execute(); Console.WriteLine(DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss")); Console.WriteLine("Total Active Users: " + realtime.TotalsForAllResults.FirstOrDefault().Value); Console.WriteLine("Total Page Views: " + realtimePageViews.TotalsForAllResults.FirstOrDefault().Value); Console.WriteLine("-----------------------------------------"); var userData = CreateData("RealtimeActiveUsers", realtime); var pageData = CreateData("RealtimePageViews", realtimePageViews); using (var webClient = new WebClient()) { webClient.Headers.Add("content-type", "application/json"); webClient.UploadString(config["ElasticSearchUrl"], String.Join("\r\n", userData) + "\r\n"); webClient.Headers.Add("content-type", "application/json"); webClient.UploadString(config["ElasticSearchUrl"], String.Join("\r\n", pageData) + "\r\n"); } } catch (Exception e) { Console.WriteLine("Error:" + e.Message); } Thread.Sleep(Convert.ToInt32(config["IntervalMs"])); } }
internal AnalyticsManagementEndpoint(AnalyticsService service) { Service = service; }
public void OnNavigatedTo(INavigationParameters parameters) { AnalyticsService.TrackPageView(Constants.Analytics.Page_GettingStarted); }
/// <summary> /// Returns full list from the MetaData API /// Documentation: https://developers.google.com/analytics/devguides/reporting/metadata/v3/reference/metadata/columns/list /// </summary> /// <param name="service">Valid Analytics Service</param> /// <returns></returns> public static Columns MetaDataList(AnalyticsService service) { return(service.Metadata.Columns.List("ga").Execute()); }
public ActionResult Analytics(int?duration) { CacheContext.InvalidateOn(TriggerFrom.Any <SiteSettings>()); var settings = _siteSettingsService.GetSettings(); if (string.IsNullOrEmpty(settings.AnalyticsToken)) { const string scope = "https://www.google.com/analytics/feeds/"; var next = Url.Absolute(Url.AnalyticsWidget().AuthResponse()); var auth = new Authorize { Url = AuthSubUtil.getRequestUrl(next, scope, false, true) }; return(View("AnalyticsAuthorize", auth)); } if (string.IsNullOrEmpty(settings.AnalyticsProfileId)) { var config = new Config { Accounts = GetAccounts(settings), Profiles = GetProfiles(settings) }; return(View("AnalyticsConfig", config)); } duration = duration ?? 30; var model = new ViewModels.Widgets.Analytics { Duration = duration.Value, Start = DateTime.Today.AddDays(-1 * duration.Value), End = DateTime.Now, Visits = new Dictionary <DateTime, int>(), PageViews = new Dictionary <string, int>(), PageTitles = new Dictionary <string, string>(), TopReferrers = new Dictionary <string, int>(), TopSearches = new Dictionary <string, int>() }; if (model.Start > model.End) { var tempDate = model.Start; model.Start = model.End; model.End = tempDate; } var profiles = GetProfiles(settings); var profile = profiles.SingleOrDefault(x => x.Id == settings.AnalyticsProfileId); if (profile == null) { throw new Exception("Unable to find the specified analytics profile: " + settings.AnalyticsProfileId); } model.Profile = profile; var authFactory = new GAuthSubRequestFactory("analytics", "MvcKickstart") { Token = settings.AnalyticsToken }; var analytics = new AnalyticsService(authFactory.ApplicationName) { RequestFactory = authFactory }; var profileId = "ga:" + settings.AnalyticsProfileId; // Get from All Visits var visits = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits", Dimensions = "ga:date", Sort = "ga:date" }; var count = 0; foreach (DataEntry entry in analytics.Query(visits).Entries) { var value = entry.Metrics.First().IntegerValue; model.Visits.Add(model.Start.AddDays(count++), value); } // Get Site Usage var siteUsage = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits,ga:pageviews,ga:percentNewVisits,ga:avgTimeOnSite,ga:entranceBounceRate,ga:exitRate,ga:pageviewsPerVisit,ga:avgPageLoadTime" }; var siteUsageResult = (DataEntry)analytics.Query(siteUsage).Entries.FirstOrDefault(); if (siteUsageResult != null) { foreach (var metric in siteUsageResult.Metrics) { switch (metric.Name) { case "ga:visits": model.TotalVisits = metric.IntegerValue; break; case "ga:pageviews": model.TotalPageViews = metric.IntegerValue; break; case "ga:percentNewVisits": model.PercentNewVisits = metric.FloatValue; break; case "ga:avgTimeOnSite": model.AverageTimeOnSite = TimeSpan.FromSeconds(metric.FloatValue); break; case "ga:entranceBounceRate": model.EntranceBounceRate = metric.FloatValue; break; case "ga:exitRate": model.PercentExitRate = metric.FloatValue; break; case "ga:pageviewsPerVisit": model.PageviewsPerVisit = metric.FloatValue; break; case "ga:avgPageLoadTime": model.AveragePageLoadTime = TimeSpan.FromSeconds(metric.FloatValue); break; } } } // Get Top Pages var topPages = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:pageviews", Dimensions = "ga:pagePath,ga:pageTitle", Sort = "-ga:pageviews", NumberToRetrieve = 20 }; foreach (DataEntry entry in analytics.Query(topPages).Entries) { var value = entry.Metrics.First().IntegerValue; var url = entry.Dimensions.Single(x => x.Name == "ga:pagePath").Value.ToLowerInvariant(); var title = entry.Dimensions.Single(x => x.Name == "ga:pageTitle").Value; if (!model.PageViews.ContainsKey(url)) { model.PageViews.Add(url, 0); } model.PageViews[url] += value; if (!model.PageTitles.ContainsKey(url)) { model.PageTitles.Add(url, title); } } // Get Top Referrers var topReferrers = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits", Dimensions = "ga:source,ga:medium", Sort = "-ga:visits", Filters = "ga:medium==referral", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topReferrers).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:source").Value.ToLowerInvariant(); model.TopReferrers.Add(source, visitCount); } // Get Top Searches var topSearches = new DataQuery(profileId, model.Start, model.End) { Metrics = "ga:visits", Dimensions = "ga:keyword", Sort = "-ga:visits", Filters = "ga:keyword!=(not set);ga:keyword!=(not provided)", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topSearches).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:keyword").Value.ToLowerInvariant(); model.TopSearches.Add(source, visitCount); } return(View(model)); }
public void OnNavigatedTo(NavigationParameters parameters) { AnalyticsService.TrackPageView(Constants.Analytics.Page_SetGoal); TryLoadExistingGoal(); }
public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args) { var ioc = TinyIoC.TinyIoCContainer.Current; //Setup Logger for API APIConfiguration.Logger = new APILogListener(); //Application.EnableVisualStyles(); var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; var culture = CultureInfo.CreateSpecificCulture("en"); CultureInfo.DefaultThreadCurrentCulture = culture; Thread.CurrentThread.CurrentCulture = culture; AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler; Console.Title = @"NecroBot2 Loading"; Console.CancelKeyPress += (sender, eArgs) => { QuitEvent.Set(); eArgs.Cancel = true; }; // Command line parsing var commandLine = new Arguments(args); // Look for specific arguments values if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0) { _subPath = commandLine["subpath"]; } if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0) { switch (commandLine["jsonvalid"]) { case "true": _enableJsonValidation = true; break; case "false": _enableJsonValidation = false; break; } } if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0) { switch (commandLine["killswitch"]) { case "true": _ignoreKillSwitch = false; break; case "false": _ignoreKillSwitch = true; break; } } bool excelConfigAllow = false; if (commandLine["provider"] != null && commandLine["provider"] == "excel") { excelConfigAllow = true; } // Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath); Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath); Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath); var profilePath = Path.Combine(Directory.GetCurrentDirectory(), _subPath); var profileConfigPath = Path.Combine(profilePath, "config"); var configFile = Path.Combine(profileConfigPath, "config.json"); var excelConfigFile = Path.Combine(profileConfigPath, "config.xlsm"); GlobalSettings settings; var boolNeedsSetup = false; if (File.Exists(configFile)) { // Load the settings from the config file settings = GlobalSettings.Load(_subPath, _enableJsonValidation); if (excelConfigAllow) { if (!File.Exists(excelConfigFile)) { Logger.Write( "Migrating existing json confix to excel config, please check the config.xlsm in your config folder" ); ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile); } else { settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile); } Logger.Write("Bot will run with your excel config, loading excel config"); } } else { settings = new GlobalSettings { ProfilePath = profilePath, ProfileConfigPath = profileConfigPath, GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"), ConsoleConfig = { TranslationLanguageCode = strCulture } }; boolNeedsSetup = true; } if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0) { var crds = commandLine["latlng"].Split(','); try { var lat = double.Parse(crds[0]); var lng = double.Parse(crds[1]); settings.LocationConfig.DefaultLatitude = lat; settings.LocationConfig.DefaultLongitude = lng; } catch (Exception) { // ignored } } var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { // Values are available here if (options.Init) { settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password); } } var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini"); if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition) { var text = File.ReadAllText(lastPosFile); var crds = text.Split(':'); try { var lat = double.Parse(crds[0]); var lng = double.Parse(crds[1]); //If lastcoord is snipe coord, bot start from default location if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000) { settings.LocationConfig.DefaultLatitude = lat; settings.LocationConfig.DefaultLongitude = lng; } } catch (Exception) { // ignored } } if (!_ignoreKillSwitch) { if (CheckMKillSwitch() || CheckKillSwitch()) { return; } } var logicSettings = new LogicSettings(settings); var translation = Translation.Load(logicSettings); TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation); if (settings.GPXConfig.UseGpxPathing) { var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile); var readgpx = new GpxReader(xmlString, translation); var nearestPt = readgpx.Tracks.SelectMany( (trk, trkindex) => trk.Segments.SelectMany( (seg, segindex) => seg.TrackPoints.Select( (pt, ptindex) => new { TrackPoint = pt, TrackIndex = trkindex, SegIndex = segindex, PtIndex = ptindex, Latitude = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture), Longitude = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture), Distance = LocationUtils.CalculateDistanceInMeters( settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude, Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture), Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture) ) } ) ) ) .OrderBy(pt => pt.Distance) .FirstOrDefault(pt => pt.Distance <= 5000); if (nearestPt != null) { settings.LocationConfig.DefaultLatitude = nearestPt.Latitude; settings.LocationConfig.DefaultLongitude = nearestPt.Longitude; settings.LocationConfig.ResumeTrack = nearestPt.TrackIndex; settings.LocationConfig.ResumeTrackSeg = nearestPt.SegIndex; settings.LocationConfig.ResumeTrackPt = nearestPt.PtIndex; } } IElevationService elevationService = new ElevationService(settings); if (boolNeedsSetup) { //validation auth.config AuthAPIForm form = new AuthAPIForm(true); if (form.ShowDialog() == DialogResult.OK) { settings.Auth.APIConfig = form.Config; } _session = new Session(settings, new ClientSettings(settings, elevationService), logicSettings, elevationService, translation); StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile); if (configForm.ShowDialog() == DialogResult.OK) { var fileName = Assembly.GetEntryAssembly().Location; Process.Start(fileName); Environment.Exit(0); } //if (GlobalSettings.PromptForSetup(_session.Translation)) //{ // _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile); // var fileName = Assembly.GetExecutingAssembly().Location; // Process.Start(fileName); // Environment.Exit(0); //} } else { _session = new Session(settings, new ClientSettings(settings, elevationService), logicSettings, elevationService, translation); var apiCfg = settings.Auth.APIConfig; if (apiCfg.UsePogoDevAPI || apiCfg.UseCustomAPI) { if (string.IsNullOrEmpty(apiCfg.AuthAPIKey)) { Logger.Write( "You have selected PogoDev API but you have not provided an API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error ); Console.ReadKey(); Environment.Exit(0); } try { HttpClient client = new HttpClient(); string urlcheck = null; client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey); var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4); if (settings.Auth.APIConfig.UseCustomAPI) { urlcheck = $"{settings.Auth.APIConfig.UrlHashServices}{settings.Auth.APIConfig.EndPoint}"; } else { urlcheck = $"https://pokehash.buddyauth.com/{Constants.ApiEndPoint}"; } Logger.Write($"Hash End-Point Set to '{urlcheck}'", LogLevel.Info, ConsoleColor.Blue); HttpResponseMessage response = client.PostAsync(urlcheck, null).Result; string AuthKey = response.Headers.GetValues("X-AuthToken").FirstOrDefault(); string MaxRequestCount = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault(); DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault())).ToLocalTime(); TimeSpan Expiration = AuthTokenExpiration - DateTime.Now; string Result = $"Key: {maskedKey} RPM: {MaxRequestCount} Expires in: {Expiration.Days - 1} days ({AuthTokenExpiration})"; Logger.Write(Result, LogLevel.Info, ConsoleColor.Green); } catch { Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct your auth.json, \r\nThe PogoDev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error); Console.ReadKey(); Environment.Exit(0); } } //GlobalSettings.Load(_subPath, _enableJsonValidation); //Logger.Write("Press a Key to continue...", // LogLevel.Warning); //Console.ReadKey(); //return; if (excelConfigAllow) { ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile); } } ioc.Register <ISession>(_session); Logger.SetLoggerContext(_session); MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots); ioc.Register(accountManager); if (boolNeedsSetup) { StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile); if (configForm.ShowDialog() == DialogResult.OK) { var fileName = Assembly.GetEntryAssembly().Location; Process.Start(fileName); Environment.Exit(0); } //if (GlobalSettings.PromptForSetup(_session.Translation)) //{ // _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile); // var fileName = Assembly.GetExecutingAssembly().Location; // Process.Start(fileName); // Environment.Exit(0); //} else { GlobalSettings.Load(_subPath, _enableJsonValidation); Logger.Write("Press a Key to continue...", LogLevel.Warning); Console.ReadKey(); return; } if (excelConfigAllow) { ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile); } } ProgressBar.Start("NecroBot2 is starting up", 10); ProgressBar.Fill(20); var machine = new StateMachine(); var stats = _session.RuntimeStatistics; ProgressBar.Fill(30); var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4); stats.DirtyEvent += () => { GetPlayerResponse x = _session.Client.Player.GetPlayer().Result; string warn = x.Warn ? "*(Flagged)*-" : null; Console.Title = $"[NecroBot2 v{strVersion}] Team: {x.PlayerData.Team} - {warn}" + stats.GetTemplatedStats( _session.Translation.GetTranslation(TranslationString.StatsTemplateString), _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString)); }; ProgressBar.Fill(40); var aggregator = new StatisticsAggregator(stats); onBotStarted?.Invoke(_session, aggregator); ProgressBar.Fill(50); var listener = new ConsoleEventListener(); ProgressBar.Fill(60); var snipeEventListener = new SniperEventListener(); _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session); _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session); _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session); ProgressBar.Fill(70); machine.SetFailureState(new LoginState()); ProgressBar.Fill(80); ProgressBar.Fill(90); _session.Navigation.WalkStrategy.UpdatePositionEvent += (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = lat, Longitude = lng, Speed = speed }); _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk; ProgressBar.Fill(100); if (settings.WebsocketsConfig.UseWebsocket) { var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session); _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session); } var bot = accountManager.GetStartUpAccount(); _session.ReInitSessionWithNextBot(bot); machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow); try { Console.Clear(); } catch (IOException) { } if (settings.TelegramConfig.UseTelegramAPI) { _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session); } if (_session.LogicSettings.EnableHumanWalkingSnipe && _session.LogicSettings.HumanWalkingSnipeUseFastPokemap) { HumanWalkSnipeTask.StartFastPokemapAsync(_session, _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live } if (_session.LogicSettings.UseSnipeLocationServer || _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder) { SnipePokemonTask.AsyncStart(_session); } if (_session.LogicSettings.DataSharingConfig.EnableSyncData) { BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey); _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session); } settings.CheckProxy(_session.Translation); if (_session.LogicSettings.ActivateMSniper) { ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; //temporary disable MSniper connection because site under attacking. //MSniperServiceTask.ConnectToService(); //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt); } // jjskuld - Don't await the analytics service since it starts a worker thread that never returns. #pragma warning disable 4014 _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token); #pragma warning restore 4014 _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session); var trackFile = Path.GetTempPath() + "\\NecroBot2.io"; if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1)) { Thread.Sleep(10000); Thread mThread = new Thread(delegate() { var infoForm = new InfoForm(); infoForm.ShowDialog(); }); File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString()); mThread.SetApartmentState(ApartmentState.STA); mThread.Start(); } QuitEvent.WaitOne(); }
public ActionResult AnalyticsSummary() { var to = DateTime.Today.AddDays(-1); var from = to.AddDays(-30); var model = new AnalyticsSummary { Visits = new List <int>(), PageViews = new Dictionary <string, int>(), PageTitles = new Dictionary <string, string>(), TopReferrers = new Dictionary <string, int>(), TopSearches = new Dictionary <string, int>() }; var settings = RavenSession.Load <Settings>(Settings.DefaultId); var authFactory = new GAuthSubRequestFactory("analytics", ApplicationName) { Token = settings.SessionToken }; var analytics = new AnalyticsService(authFactory.ApplicationName) { RequestFactory = authFactory }; // Get from All Visits var visits = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits", Dimensions = "ga:date", Sort = "ga:date" }; foreach (DataEntry entry in analytics.Query(visits).Entries) { var value = entry.Metrics.First().IntegerValue; model.Visits.Add(value); } // Get Site Usage var siteUsage = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits,ga:pageviews,ga:percentNewVisits,ga:avgTimeOnSite,ga:entranceBounceRate,ga:exitRate,ga:pageviewsPerVisit,ga:avgPageLoadTime" }; var siteUsageResult = (DataEntry)analytics.Query(siteUsage).Entries.FirstOrDefault(); if (siteUsageResult != null) { foreach (var metric in siteUsageResult.Metrics) { switch (metric.Name) { case "ga:visits": model.TotalVisits = metric.IntegerValue; break; case "ga:pageviews": model.TotalPageViews = metric.IntegerValue; break; case "ga:percentNewVisits": model.PercentNewVisits = metric.FloatValue; break; case "ga:avgTimeOnSite": model.AverageTimeOnSite = TimeSpan.FromSeconds(metric.FloatValue); break; case "ga:entranceBounceRate": model.EntranceBounceRate = metric.FloatValue; break; case "ga:exitRate": model.PercentExitRate = metric.FloatValue; break; case "ga:pageviewsPerVisit": model.PageviewsPerVisit = metric.FloatValue; break; case "ga:avgPageLoadTime": model.AveragePageLoadTime = TimeSpan.FromSeconds(metric.FloatValue); break; } } } // Get Top Pages var topPages = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:pageviews", Dimensions = "ga:pagePath,ga:pageTitle", Sort = "-ga:pageviews", NumberToRetrieve = 20 }; foreach (DataEntry entry in analytics.Query(topPages).Entries) { var value = entry.Metrics.First().IntegerValue; var url = entry.Dimensions.Single(x => x.Name == "ga:pagePath").Value.ToLowerInvariant(); var title = entry.Dimensions.Single(x => x.Name == "ga:pageTitle").Value; if (!model.PageViews.ContainsKey(url)) { model.PageViews.Add(url, 0); } model.PageViews[url] += value; if (!model.PageTitles.ContainsKey(url)) { model.PageTitles.Add(url, title); } } // Get Top Referrers var topReferrers = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits", Dimensions = "ga:source,ga:medium", Sort = "-ga:visits", Filters = "ga:medium==referral", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topReferrers).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:source").Value.ToLowerInvariant(); model.TopReferrers.Add(source, visitCount); } // Get Top Searches var topSearches = new DataQuery(settings.SiteId, from, to) { Metrics = "ga:visits", Dimensions = "ga:keyword", Sort = "-ga:visits", Filters = "ga:keyword!=(not set);ga:keyword!=(not provided)", NumberToRetrieve = 5 }; foreach (DataEntry entry in analytics.Query(topSearches).Entries) { var visitCount = entry.Metrics.First().IntegerValue; var source = entry.Dimensions.Single(x => x.Name == "ga:keyword").Value.ToLowerInvariant(); model.TopSearches.Add(source, visitCount); } return(View(model)); }
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); } }
// GET: Analysis 可使用三種權限取得analysis資訊 public ActionResult Index() { //自己service 版本 //將自己的驗證json檔放到app_data string[] scopes = new string[] { AnalyticsService.Scope.AnalyticsReadonly }; // view and manage your Google Analytics data var keyFilePath = HttpContext.Server.MapPath("~/App_Data/6c7504a5781f.p12"); // Downloaded from https://console.developers.google.com var serviceAccountEmail = "*****@*****.**"; // found https://console.developers.google.com //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); //需要授權的版本 //string[] scopes = new string[] { // AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data // AnalyticsService.Scope.AnalyticsEdit, // Edit and manage Google Analytics Account // AnalyticsService.Scope.AnalyticsManageUsers, // Edit and manage Google Analytics Users // AnalyticsService.Scope.AnalyticsReadonly}; // View Google Analytics Data //var clientId = "385316856762-m2rkgg70628r406pqbv9qvkb9s345c2f.apps.googleusercontent.com"; // From https://console.developers.google.com //var clientSecret = "mhZFbaucc40BdXushfG6KIC9"; // From https://console.developers.google.com // // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% //var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets //{ // ClientId = clientId, // ClientSecret = clientSecret //}, //scopes, //Environment.UserName, //CancellationToken.None, //new FileDataStore("Daimto.GoogleAnalytics.Auth.Store")).Result; var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Analytics API Sample", }); //AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer() //{ // ApiKey = "AIzaSyD8BPsvUGtt_OMt_DTAvEkcnyYyAIrVQPQ", // from https://console.developers.google.com (Public API access) // ApplicationName = "Analytics API Sample", //}); ManagementResource.AccountSummariesResource.ListRequest list = service.Management.AccountSummaries.List(); list.MaxResults = 1000; // Maximum number of Account Summaries to return per request. AccountSummaries feed = list.Execute(); List<AccountSummary> allRows = new List<AccountSummary>(); //// Loop through until we arrive at an empty page while (feed.Items != null) { allRows.AddRange(feed.Items); // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (feed.NextLink == null) { break; } // Prepare the next page of results list.StartIndex = feed.StartIndex + list.MaxResults; // Execute and process the next page request feed = list.Execute(); } feed.Items = allRows; // feed.Items not contains all of the rows even if there are more then 1000 //Get account summary and display them. foreach (AccountSummary account in feed.Items) { // Account Console.WriteLine("Account: " + account.Name + "(" + account.Id + ")"); foreach (WebPropertySummary wp in account.WebProperties) { // Web Properties within that account Console.WriteLine("\tWeb Property: " + wp.Name + "(" + wp.Id + ")"); //Don't forget to check its not null. Believe it or not it could be. if (wp.Profiles != null) { foreach (ProfileSummary profile in wp.Profiles) { // Profiles with in that web property. Console.WriteLine("\t\tProfile: " + profile.Name + "(" + profile.Id + ")"); } } } } return View(); }
public ReportingClient(BaseClientService.Initializer initializer) { _service = new AnalyticsService(initializer); }
public void TracksTheLoginEvent() { ViewModel.Login(); AnalyticsService.Received().Login.Track(AuthenticationMethod.EmailAndPassword); }
public async Task RegistersTheEventAsATimerEventIfManualModeIsDisabled() { await CallInteractor(CreatePrototype(ValidTime, ValidDescription, true, ProjectId)); AnalyticsService.Received().TrackStartedTimeEntry(TimeEntryStartOrigin.Timer); }
async void ShowSetGoalScreen() { AnalyticsService.TrackEvent(Constants.Analytics.DailyInfoCategory, Constants.Analytics.DailyInfo_LaunchedSetGoal, 1); await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{nameof(SetGoalPage)}", useModalNavigation : true); }
protected void btnOpenSystem_ClickAction(object sender, EventArgs e) { AnalyticsService srv = new AnalyticsService(); AnalyticsSystemInfo = srv.GetAnalyticsSystemInfo(); string url = string.Format("{0}", txtSystemUrl.Text); TestUrl(url); }