public async Task Migrate() { await _semaphoreForMigrage.WaitAsync(); loggerService.StartMethod(); try { var userData = GetFromApplicationProperties(); if (userData == null) { return; } if (userData.StartDateTime != null && !userData.StartDateTime.Equals(new DateTime())) { preferencesService.SetValue(PreferenceKey.StartDateTime, userData.StartDateTime); userData.StartDateTime = new DateTime(); loggerService.Info("Migrated StartDateTime"); } if (userData.IsOptined) { await termsUpdateService.Migrate(TermsType.TermsOfService, userData.IsOptined); userData.IsOptined = false; } if (userData.IsPolicyAccepted) { await termsUpdateService.Migrate(TermsType.PrivacyPolicy, userData.IsPolicyAccepted); userData.IsPolicyAccepted = false; } await exposureNotificationService.MigrateFromUserData(userData); Application.Current.Properties.Remove("UserData"); await Application.Current.SavePropertiesAsync(); } catch (Exception ex) { loggerService.Exception("Failed migrate", ex); } finally { _semaphoreForMigrage.Release(); loggerService.EndMethod(); } }
// POST /api/Register - Register User public async Task <bool> PostRegisterUserAsync() { loggerService.StartMethod(); try { string url = AppSettings.Instance.ApiUrlBase + "/register"; var content = new StringContent(string.Empty, Encoding.UTF8, "application/json"); var result = await PostAsync(url, content); if (result != null) { loggerService.EndMethod(); return(true); } } catch (Exception ex) { loggerService.Exception("Failed to register user.", ex); } loggerService.EndMethod(); return(false); }
public static async void CheckVersion(ILoggerService loggerService) { loggerService.StartMethod(); var uri = AppResources.UrlVersion; using (var client = new HttpClient()) { try { var json = await client.GetStringAsync(uri); var versionString = JObject.Parse(json).Value <string>("version"); if (new Version(versionString).CompareTo(new Version(AppInfo.VersionString)) > 0) { await UserDialogs.Instance.AlertAsync(AppResources.AppUtilsGetNewVersionDescription, AppResources.AppUtilsGetNewVersionTitle, Resources.AppResources.ButtonOk); if (Device.RuntimePlatform == Device.iOS) { await Browser.OpenAsync(AppSettings.Instance.AppStoreUrl, BrowserLaunchMode.External); } else if (Device.RuntimePlatform == Device.Android) { await Browser.OpenAsync(AppSettings.Instance.GooglePlayUrl, BrowserLaunchMode.External); } } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); loggerService.Exception("Failed to check version.", ex); } finally { loggerService.EndMethod(); } } }
private async Task <ExposureDataResponse?> UploadExposureDataAsync( ExposureRequest exposureRequest, string exposureDataCollectServerEndpoint ) { _loggerService.StartMethod(); _loggerService.Debug($"exposureDataCollectServerEndpoint: {exposureDataCollectServerEndpoint}"); try { var requestJson = exposureRequest.ToJsonString(); _loggerService.Info(requestJson); var httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); Uri uri = new Uri(exposureDataCollectServerEndpoint); HttpResponseMessage response = await _httpClient.PutAsync(uri, httpContent); if (response.IsSuccessStatusCode) { var responseJson = await response.Content.ReadAsStringAsync(); _loggerService.Debug($"response {responseJson}"); return(JsonConvert.DeserializeObject <ExposureDataResponse>(responseJson)); } else { _loggerService.Info($"UploadExposureDataAsync {response.StatusCode}"); return(null); } } finally { _loggerService.EndMethod(); } }
protected override async void OnInitialized() { InitializeComponent(); LoggerService = Container.Resolve <ILoggerService>(); LoggerService.StartMethod(); LogFileService = Container.Resolve <ILogFileService>(); LogFileService.AddSkipBackupAttribute(); #if USE_MOCK // For debug mode, set the mock api provider to interact // with some fake data Xamarin.ExposureNotifications.ExposureNotification.OverrideNativeImplementation(new Services.TestNativeImplementation()); #endif Xamarin.ExposureNotifications.ExposureNotification.Init(); // Local Notification tap event listener //NotificationCenter.Current.NotificationTapped += OnNotificationTapped; LogUnobservedTaskExceptions(); INavigationResult result = await NavigationService.NavigateAsync("/" + nameof(SplashPage)); if (!result.Success) { LoggerService.Info($"Failed transition."); MainPage = new ExceptionPage { BindingContext = new ExceptionPageViewModel() { Message = result.Exception.Message } }; System.Diagnostics.Debugger.Break(); } LoggerService.EndMethod(); }
public override async void Initialize(INavigationParameters parameters) { base.Initialize(parameters); _loggerService.StartMethod(); _exposureRiskCalculationConfiguration = parameters.GetValue <V1ExposureRiskCalculationConfiguration>(ExposureCheckPage.ExposureRiskCalculationConfigurationKey); ShowExposureRiskCalculationConfiguration(); try { var summaries = await _exposureDataRepository .GetDailySummariesAsync(AppConstants.DaysOfExposureInformationToDisplay); if (0 < summaries.Count()) { IsVisibleLowRiskContact = true; IsVisibleNoRiskContact = false; _ = SetupExposureCheckScoresAsync(summaries); } else { IsVisibleLowRiskContact = false; IsVisibleNoRiskContact = true; } } catch (Exception exception) { _loggerService.Exception("Exception occurred", exception); } finally { _loggerService.EndMethod(); } }
public void OnClickRadioButtonIsTrueCommand(string text) { loggerService.StartMethod(); if (AppResources.NotifyOtherPageRadioButtonYes.Equals(text)) { IsVisibleWithSymptomsLayout = true; IsVisibleNoSymptomsLayout = false; } else if (AppResources.NotifyOtherPageRadioButtonNo.Equals(text)) { IsVisibleWithSymptomsLayout = false; IsVisibleNoSymptomsLayout = true; } else { IsVisibleWithSymptomsLayout = false; IsVisibleNoSymptomsLayout = false; } loggerService.Info($"Is visible with symptoms layout: {IsVisibleWithSymptomsLayout}, Is visible no symptoms layout: {IsVisibleNoSymptomsLayout}"); loggerService.EndMethod(); }
public async Task <bool> UploadAsync(string endpoint, string uploadPath, string accountName, string sasToken, string sourceFilePath) { loggerService.StartMethod(); var result = false; try { var fileName = Path.GetFileName(sourceFilePath); var uri = new UriBuilder(endpoint) { Path = $"{uploadPath.Trim('/')}/{fileName}", Query = sasToken.TrimStart('?') }.Uri; var client = new BlobClient(uri); using (var fileStream = File.OpenRead(sourceFilePath)) { var response = await client.UploadAsync(fileStream); var rawResponse = response.GetRawResponse(); if (rawResponse.Status == (int)HttpStatusCode.Created) { result = true; } } } catch (Exception ex) { loggerService.Error("Failed upload to storage"); System.Diagnostics.Debug.WriteLine($"Exception: {ex}"); } loggerService.EndMethod(); return(result); }
public async Task ExportAsync(string filePath) { _loggerService.StartMethod(); try { long enVersion = await _exposureNotificationApiService.GetVersionAsync(); List <DailySummary> dailySummaryList = await _exposureDataRepository.GetDailySummariesAsync(); List <ExposureWindow> exposureWindowList = await _exposureDataRepository.GetExposureWindowsAsync(); ExposureConfiguration exposureConfiguration = await _exposureConfigurationRepository.GetExposureConfigurationAsync(); var exposureData = new ExposureData( _essentialsService.Platform, _essentialsService.PlatformVersion, _essentialsService.Model, _essentialsService.DeviceType, _essentialsService.AppVersion, _essentialsService.BuildNumber, enVersion.ToString(), dailySummaryList, exposureWindowList, exposureConfiguration ); string exposureDataJson = JsonConvert.SerializeObject(exposureData, Formatting.Indented); await File.WriteAllTextAsync(filePath, exposureDataJson); } finally { _loggerService.EndMethod(); } }
public void RemoveStartDate() { _loggerService.StartMethod(); _preferencesService.RemoveValue(PreferenceKey.StartDateTimeEpoch); _loggerService.EndMethod(); }
private async Task SendExposureDataAsync( string idempotencyKey, ExposureData exposureData ) { _loggerService.StartMethod(); SendEventLogState sendEventLogState = _userDataRepository.GetSendEventLogState(); bool isEnabled = sendEventLogState == SendEventLogState.Enable; if (!isEnabled) { _loggerService.Debug($"Send event-log function is not enabled."); _loggerService.EndMethod(); return; } await _serverConfigurationRepository.LoadAsync(); string exposureDataCollectServerEndpoint = _serverConfigurationRepository.EventLogApiEndpoint; _loggerService.Debug($"exposureDataCollectServerEndpoint: {exposureDataCollectServerEndpoint}"); try { var contentJson = exposureData.ToJsonString(); var eventLog = new V1EventLogRequest.EventLog() { HasConsent = isEnabled, Epoch = _dateTimeUtility.UtcNow.ToUnixEpoch(), Type = "ExposureData", Subtype = "Debug", Content = contentJson, }; var eventLogs = new[] { eventLog }; var request = new V1EventLogRequest() { IdempotencyKey = idempotencyKey, Platform = _essentialsService.Platform, AppPackageName = _essentialsService.AppPackageName, EventLogs = eventLogs, }; request.DeviceVerificationPayload = await _deviceVerifier.VerifyAsync(request); var requestJson = request.ToJsonString(); var httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); Uri uri = new Uri(exposureDataCollectServerEndpoint); HttpResponseMessage response = await _httpClient.PutAsync(uri, httpContent); if (response.IsSuccessStatusCode) { var responseJson = await response.Content.ReadAsStringAsync(); _loggerService.Debug($"{responseJson}"); } else { _loggerService.Info($"UploadExposureDataAsync {response.StatusCode}"); } } finally { _loggerService.EndMethod(); } }
public async Task MigrateFromUserData(UserDataModel userData) { loggerService.StartMethod(); const string ConfigurationPropertyKey = "ExposureNotificationConfigration"; if (userData.LastProcessTekTimestamp != null && userData.LastProcessTekTimestamp.Count > 0) { var stringValue = Utils.SerializeToJson(userData.LastProcessTekTimestamp); preferencesService.SetValue(PreferenceKey.LastProcessTekTimestamp, stringValue); userData.LastProcessTekTimestamp.Clear(); loggerService.Info("Migrated LastProcessTekTimestamp"); } if (applicationPropertyService.ContainsKey(ConfigurationPropertyKey)) { var configuration = applicationPropertyService.GetProperties(ConfigurationPropertyKey) as string; if (!string.IsNullOrEmpty(configuration)) { preferencesService.SetValue(PreferenceKey.ExposureNotificationConfiguration, configuration); } await applicationPropertyService.Remove(ConfigurationPropertyKey); loggerService.Info("Migrated ExposureNotificationConfiguration"); } if (userData.ExposureInformation != null) { secureStorageService.SetValue(PreferenceKey.ExposureInformation, JsonConvert.SerializeObject(userData.ExposureInformation)); userData.ExposureInformation = null; loggerService.Info("Migrated ExposureInformation"); } if (userData.ExposureSummary != null) { secureStorageService.SetValue(PreferenceKey.ExposureSummary, JsonConvert.SerializeObject(userData.ExposureSummary)); userData.ExposureSummary = null; loggerService.Info("Migrated ExposureSummary"); } loggerService.EndMethod(); }
// this configuration should be obtained from a server and it should be cached locally/in memory as it may be called multiple times public Task <Configuration> GetConfigurationAsync() { loggerService.StartMethod(); if (Application.Current.Properties.ContainsKey("ExposureNotificationConfigration")) { loggerService.Info("Get configuration from config"); var configurationJson = Application.Current.Properties["ExposureNotificationConfigration"].ToString(); loggerService.Info($"configuration: {configurationJson}"); loggerService.EndMethod(); return(Task.FromResult(Utils.DeserializeFromJson <Configuration>(configurationJson))); } configuration = new Configuration { MinimumRiskScore = 21, AttenuationWeight = 50, TransmissionWeight = 50, DurationWeight = 50, DaysSinceLastExposureWeight = 50, TransmissionRiskScores = new int[] { 7, 7, 7, 7, 7, 7, 7, 7 }, AttenuationScores = new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, DurationScores = new[] { 0, 0, 0, 0, 1, 1, 1, 1 }, DaysSinceLastExposureScores = new[] { 1, 1, 1, 1, 1, 1, 1, 1 }, DurationAtAttenuationThresholds = new[] { 50, 70 } }; loggerService.Info("Get default configuration"); var defaultConfiguration = Task.FromResult(configuration); loggerService.Info($"configuration: {Utils.SerializeToJson(configuration)}"); loggerService.EndMethod(); return(defaultConfiguration); }
public async Task <(List <DailySummary>, List <ExposureWindow>)> SetExposureDataAsync( List <DailySummary> dailySummaryList, List <ExposureWindow> exposueWindowList ) { _loggerService.StartMethod(); List <DailySummary> existDailySummaryList = await GetDailySummariesAsync(); List <ExposureWindow> existExposureWindowList = await GetExposureWindowsAsync(); List <DailySummary> filteredExistDailySummaryList = new List <DailySummary>(); // Filter and merge DailySummaries that have same DateMillisSinceEpoch value. foreach (var existDailySummary in existDailySummaryList) { var conflictDailySummaryList = dailySummaryList .Where(ds => ds.DateMillisSinceEpoch == existDailySummary.DateMillisSinceEpoch) .ToList(); var conflictDailySummaryListCount = conflictDailySummaryList.Count(); if (conflictDailySummaryListCount == 0) { filteredExistDailySummaryList.Add(existDailySummary); continue; } else if (conflictDailySummaryListCount > 1) { _loggerService.Warning($"The list conflictDailySummaryList count should be 1 but {conflictDailySummaryListCount}." + "conflictDailySummaryList will be sorted and selected first value."); conflictDailySummaryList.Sort(_dailySummaryComparer); } // `conflictDailySummaryList` count must be 1, // because the DailySummary objects that have same DateMillisSinceEpoch value must be saved after merge. DailySummary newDailySummary = conflictDailySummaryList.First(); if (existDailySummary.Equals(newDailySummary)) { filteredExistDailySummaryList.Add(existDailySummary); } else { MergeDailySummarySelectMaxValues(existDailySummary, newDailySummary); } } List <DailySummary> unionDailySummaryList = filteredExistDailySummaryList.Union(dailySummaryList).ToList(); List <ExposureWindow> unionExposureWindowList = existExposureWindowList.Union(exposueWindowList).ToList(); unionDailySummaryList.Sort(_dailySummaryComparer); unionExposureWindowList.Sort(_exposureWindowComparer); await SaveExposureDataAsync(unionDailySummaryList, unionExposureWindowList); List <DailySummary> newDailySummaryList = unionDailySummaryList.Except(filteredExistDailySummaryList).ToList(); List <ExposureWindow> newExposureWindowList = unionExposureWindowList.Except(existExposureWindowList).ToList(); _loggerService.EndMethod(); return(newDailySummaryList, newExposureWindowList); }
private async Task <ExposureConfiguration> GetExposureConfigurationInternalAsync() { _loggerService.StartMethod(); ExposureConfiguration currentExposureConfiguration = null; if (File.Exists(_currentExposureConfigurationPath)) { _loggerService.Debug("ExposureConfiguration file is found."); try { string exposureConfigurationAsJson = await LoadAsync(_currentExposureConfigurationPath); currentExposureConfiguration = JsonConvert.DeserializeObject <ExposureConfiguration>(exposureConfigurationAsJson); _loggerService.Info("Cached:" + exposureConfigurationAsJson); if (!IsDownloadedExposureConfigurationOutdated(AppConstants.ExposureConfigurationFileDownloadCacheRetentionDays)) { _loggerService.EndMethod(); return(currentExposureConfiguration); } else { _loggerService.Info($"ExposureConfiguration is found but the file is outdated."); } } catch (IOException exception) { _loggerService.Exception("IOException. ExposureConfiguration file has been deleted.", exception); RemoveExposureConfigurationInternal(); } catch (JsonException exception) { _loggerService.Exception("JsonException. ExposureConfiguration file has been deleted.", exception); RemoveExposureConfigurationInternal(); } } // Cache not exist (first time. probably...) if (currentExposureConfiguration is null) { currentExposureConfiguration = CreateDefaultConfiguration(); SetExposureConfigurationDownloadedDateTime(_dateTimeUtility.UtcNow); SetIsDiagnosisKeysDataMappingConfigurationUpdated(true); } await _serverConfigurationRepository.LoadAsync(); string url = _serverConfigurationRepository.ExposureConfigurationUrl; ExposureConfiguration newExposureConfiguration = null; var response = await _httpClient.GetAsync(url); if (response.IsSuccessStatusCode) { string exposureConfigurationAsJson = await response.Content.ReadAsStringAsync(); try { newExposureConfiguration = JsonConvert.DeserializeObject <ExposureConfiguration>(exposureConfigurationAsJson); _loggerService.Info("Downloaded:" + exposureConfigurationAsJson); SetExposureConfigurationDownloadedDateTime(_dateTimeUtility.UtcNow); } catch (JsonException exception) { _loggerService.Exception("JsonException.", exception); } } else { _loggerService.Warning($"Download ExposureConfiguration failed from {url}"); } if (newExposureConfiguration is null) { _loggerService.EndMethod(); return(currentExposureConfiguration); } if (IsUpdatedDiagnosisKeysDataMapping(currentExposureConfiguration, newExposureConfiguration)) { if (IsExposureConfigurationOutdated(AppConstants.MinimumDiagnosisKeysDataMappingApplyIntervalDays)) { currentExposureConfiguration = newExposureConfiguration; SetIsDiagnosisKeysDataMappingConfigurationUpdated(true); } else { _loggerService.Info($"DiagnosisKeysDataMappingConfig has been changed but not updated, because current configuration is updated in {AppConstants.MinimumDiagnosisKeysDataMappingApplyIntervalDays} days."); } } else { currentExposureConfiguration = newExposureConfiguration; } string tmpFilePath = Path.Combine(_configDir, Guid.NewGuid().ToString()); try { await SaveAsync( JsonConvert.SerializeObject(currentExposureConfiguration, Formatting.Indented), tmpFilePath ); Swap(tmpFilePath, _currentExposureConfigurationPath); return(currentExposureConfiguration); } finally { File.Delete(tmpFilePath); _loggerService.EndMethod(); } }
private async Task SendAllInternalAsync(long maxSize, int maxRetry) { _loggerService.StartMethod(); try { List <EventLog> eventLogList = await _eventLogRepository.GetLogsAsync(maxSize); if (eventLogList.Count == 0) { _loggerService.Info($"Event-logs not found."); return; } IDictionary <string, SendEventLogState> eventStateDict = new Dictionary <string, SendEventLogState>(); foreach (var eventType in EventType.All) { eventStateDict[eventType.ToString()] = _sendEventLogStateRepository.GetSendEventLogState(eventType); } foreach (var eventLog in eventLogList) { if (eventStateDict[eventLog.GetEventType()] != SendEventLogState.Enable) { eventLog.HasConsent = false; } } string idempotencyKey = Guid.NewGuid().ToString(); List <EventLog> agreedEventLogList = eventLogList.Where(eventLog => eventLog.HasConsent).ToList(); if (agreedEventLogList.Count == 0) { _loggerService.Info($"Agreed event-logs not found."); return; } PolicyResult <bool> policyResult = await Policy .HandleResult <bool>(result => !result) .WaitAndRetryAsync(maxRetry, retryAttempt => { double delay = Math.Pow(2, retryAttempt - 1); _loggerService.Warning($"Event log send failed. retryAttempt:{retryAttempt} delay:{delay}sec"); return(TimeSpan.FromSeconds(delay)); }) .ExecuteAndCaptureAsync(() => SendAsync(idempotencyKey, agreedEventLogList)); if (policyResult.Outcome == OutcomeType.Failure) { _loggerService.Error("Event log send failed all."); return; } _loggerService.Info($"Event log send successful."); _loggerService.Info($"Clean up..."); foreach (var eventLog in eventLogList) { await _eventLogRepository.RemoveAsync(eventLog); } _loggerService.Info($"Done."); } finally { _loggerService.EndMethod(); } }
public bool CreateLogUploadingFileToTmpPath(string logUploadingFileName) { loggerService.StartMethod(); try { var logsDirPath = logPathService.LogsDirPath; var logFiles = Directory.GetFiles(logsDirPath, logPathService.LogFileWildcardName); if (logFiles.Length == 0) { loggerService.EndMethod(); return(false); } ZipFile.CreateFromDirectory(logsDirPath, Path.Combine(logPathService.LogUploadingTmpPath, logUploadingFileName)); loggerService.EndMethod(); return(true); } catch (Exception) { loggerService.Error("Failed to create uploading file"); loggerService.EndMethod(); return(false); } }
private async Task <bool> AddAsyncInternal(EventLog eventLog, long maxSize) { _loggerService.StartMethod(); try { string fileName = GetFileName(eventLog); string filePath = Path.Combine(_basePath, fileName); if (File.Exists(filePath)) { _loggerService.Info($"{filePath} already exist."); return(false); } var serializedJson = JsonConvert.SerializeObject(eventLog); // Check log size. long size = Encoding.UTF8.GetByteCount(serializedJson); if (size > maxSize) { _loggerService.Info($"Log size {size} exceed maxSize {maxSize} bytes."); return(false); } string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); _loggerService.Info($"Directory created. directoryName:{directoryName}"); } await File.WriteAllTextAsync(filePath, serializedJson); _loggerService.Info($"Write event log. filePath:{filePath}"); _backupAttributeService.SetSkipBackupAttributeToEventLogDir(); return(true); } catch (Exception ex) { _loggerService.Exception("Write event log failure.", ex); } finally { _loggerService.EndMethod(); } return(false); }
public T GetValue <T>(string key, T defaultValue) { lock (this) { loggerService.StartMethod(); loggerService.Info($"key={key}, type={typeof(T)}"); if (!ContainsKey(key)) { loggerService.EndMethod(); return(defaultValue); } var context = Android.App.Application.Context; var preference = context.GetSharedPreferences(context.PackageName, Android.Content.FileCreationMode.Private); try { object value = null; if (defaultValue == null) { value = preference.GetString(key, null); return((T)value); } switch (defaultValue) { case int i: value = preference.GetInt(key, i); break; case bool b: value = preference.GetBoolean(key, b); break; case float f: value = preference.GetFloat(key, f); break; case string s: value = preference.GetString(key, s); break; case DateTime d: var valueString = preference.GetString(key, d.ToString()); value = DateTime.Parse(valueString); break; default: loggerService.Info("Type is not supported."); value = defaultValue; break; } loggerService.EndMethod(); return((T)value); } catch (Exception) { loggerService.Error($"Failed to get value of {key}"); loggerService.EndMethod(); return(defaultValue); } } }
private T GetValue <T>(string key, T defaultValue) { lock (this) { loggerService.StartMethod(); loggerService.Info($"key={key}, type={typeof(T)}"); if (!ContainsKey(key)) { loggerService.Info($"{key} is not contained."); loggerService.EndMethod(); return(defaultValue); } var userDefaults = NSUserDefaults.StandardUserDefaults; try { object value = null; if (defaultValue == null) { value = userDefaults.StringForKey(key); return((T)value); } switch (defaultValue) { case int i: value = (int)userDefaults.IntForKey(key); break; case long l: value = (long)userDefaults.IntForKey(key); break; case bool b: value = userDefaults.BoolForKey(key); break; case float f: value = userDefaults.FloatForKey(key); break; case string s: value = userDefaults.StringForKey(key); break; default: loggerService.Info("Type is not supported."); value = defaultValue; break; } loggerService.EndMethod(); return((T)value); } catch (Exception) { loggerService.Error($"Failed to get value of {key}."); loggerService.EndMethod(); return(defaultValue); } } }
protected override async void OnInitialized() { InitializeComponent(); LoggerService = Container.Resolve <ILoggerService>(); LoggerService.StartMethod(); LogFileService = Container.Resolve <ILogFileService>(); LogFileService.AddSkipBackupAttribute(); #if USE_MOCK // For debug mode, set the mock api provider to interact // with some fake data Xamarin.ExposureNotifications.ExposureNotification.OverrideNativeImplementation(new Services.TestNativeImplementation()); #endif Xamarin.ExposureNotifications.ExposureNotification.Init(); // Local Notification tap event listener //NotificationCenter.Current.NotificationTapped += OnNotificationTapped; LogUnobservedTaskExceptions(); INavigationResult result; // Check user data and skip tutorial IUserDataService userDataService = Container.Resolve <IUserDataService>(); if (userDataService.IsExistUserData) { LoggerService.Info("User data exists"); var userData = userDataService.Get(); LoggerService.Info($"userData.IsOptined: {userData.IsOptined}"); LoggerService.Info($"userData.IsPolicyAccepted: {userData.IsPolicyAccepted}"); if (userData.IsOptined && userData.IsPolicyAccepted) { LoggerService.Info($"Transition to SplashPage"); result = await NavigationService.NavigateAsync("/" + nameof(SplashPage)); } else { LoggerService.Info($"Transition to TutorialPage1"); result = await NavigationService.NavigateAsync("/" + nameof(TutorialPage1)); } } else { LoggerService.Info("No user data exists"); LoggerService.Info($"Transition to TutorialPage1"); result = await NavigationService.NavigateAsync("/" + nameof(TutorialPage1)); } if (!result.Success) { LoggerService.Info($"Failed transition."); MainPage = new ExceptionPage { BindingContext = new ExceptionPageViewModel() { Message = result.Exception.Message } }; System.Diagnostics.Debugger.Break(); } LoggerService.EndMethod(); }
public override async void Initialize(INavigationParameters parameters) { base.Initialize(parameters); try { loggerService.StartMethod(); var exposureRiskCalculationConfiguration = await _exposureRiskCalculationConfigurationRepository.GetExposureRiskCalculationConfigurationAsync(preferCache : true); loggerService.Info(exposureRiskCalculationConfiguration.ToString()); var userExposureInformationList = _exposureDataRepository.GetExposureInformationList(AppConstants.TermOfExposureRecordValidityInDays); string contactedNotifyPageCountFormat = AppResources.ContactedNotifyPageCountOneText; if (userExposureInformationList.Count() > 1) { contactedNotifyPageCountFormat = AppResources.ContactedNotifyPageCountText; } var dailySummaryList = await _exposureDataRepository.GetDailySummariesAsync(AppConstants.TermOfExposureRecordValidityInDays); var dailySummaryMap = dailySummaryList.ToDictionary(ds => ds.GetDateTime()); var exposureWindowList = await _exposureDataRepository.GetExposureWindowsAsync(AppConstants.TermOfExposureRecordValidityInDays); int dayCount = 0; long exposureDurationInSec = 0; foreach (var ew in exposureWindowList.GroupBy(exposureWindow => exposureWindow.GetDateTime())) { if (!dailySummaryMap.ContainsKey(ew.Key)) { loggerService.Warning($"ExposureWindow: {ew.Key} found, but that is not contained the list of dailySummary."); continue; } var dailySummary = dailySummaryMap[ew.Key]; RiskLevel riskLevel = _exposureRiskCalculationService.CalcRiskLevel(dailySummary, ew.ToList(), exposureRiskCalculationConfiguration); if (riskLevel >= RiskLevel.High) { exposureDurationInSec += ew.Sum(e => e.ScanInstances.Sum(s => s.SecondsSinceLastScan)); dayCount += 1; } } string contactedNotifyPageExposureDurationFormat = AppResources.ContactedNotifyPageExposureDurationOne; if (dayCount > 1) { contactedNotifyPageExposureDurationFormat = AppResources.ContactedNotifyPageExposureDuration; } TimeSpan timeSpan = TimeSpan.FromSeconds(exposureDurationInSec); var totalMinutes = Math.Ceiling(timeSpan.TotalMinutes); if (userExposureInformationList.Count() > 0 && dayCount > 0) { // Show Headers var beforeDateMillisSinceEpoch = userExposureInformationList.Max(ei => ei.Timestamp.ToUnixEpochMillis()); var afterDateMillisSinceEpoch = dailySummaryList.Min(ds => ds.DateMillisSinceEpoch); var beforeDate = DateTimeOffset.UnixEpoch.AddMilliseconds(beforeDateMillisSinceEpoch).UtcDateTime; var afterDate = DateTimeOffset.UnixEpoch.AddMilliseconds(afterDateMillisSinceEpoch).UtcDateTime; ExposureCount = string.Format(AppResources.ContactedNotifyPageCountHeader, beforeDate.ToString("D")) + "\n" + string.Format(contactedNotifyPageCountFormat, userExposureInformationList.Count()); ExposureDurationInMinutes = string.Format(AppResources.ContactedNotifyPageExposureDurationHeader, afterDate.ToString("D")) + "\n" + string.Format(contactedNotifyPageExposureDurationFormat, dayCount, totalMinutes); } else if (exposureDurationInSec > 0) { ExposureDurationInMinutes = string.Format(contactedNotifyPageExposureDurationFormat, dayCount, totalMinutes); } else if (userExposureInformationList.Count() > 0) { ExposureCount = string.Format(contactedNotifyPageCountFormat, userExposureInformationList.Count()); } } catch (Exception exception) { loggerService.Exception("Failed to Initialize", exception); } finally { loggerService.EndMethod(); } }