Example #1
0
        public string CreateZipFile(string fileName)
        {
            loggerService.StartMethod();
            try
            {
                var logsDirPath = logPathService.LogsDirPath;
                var logFiles    = Directory.GetFiles(logsDirPath, logPathService.LogFileWildcardName);
                if (logFiles.Length == 0)
                {
                    return(null);
                }

                var zipFilePath = Path.Combine(logPathService.LogUploadingTmpPath, fileName);
                ZipFile.CreateFromDirectory(logsDirPath, zipFilePath);

                return(zipFilePath);
            }
            catch (Exception exception)
            {
                loggerService.Exception("Failed to create uploading file", exception);
                return(null);
            }
            finally
            {
                loggerService.EndMethod();
            }
        }
Example #2
0
        private void MigrateDateTimeToEpoch(string dateTimeKey, string epochKey, TimeSpan differential, DateTime fallbackDateTime)
        {
            string dateTimeStr = _preferencesService.GetValue(dateTimeKey, fallbackDateTime.ToString());

            DateTime dateTime;

            try
            {
                dateTime = DateTime.SpecifyKind(DateTime.Parse(dateTimeStr), DateTimeKind.Utc);
            }
            catch (FormatException exception)
            {
                _loggerService.Exception($"Parse dateTime FormatException occurred. {dateTimeStr}", exception);
                dateTime = fallbackDateTime;
            }

            try
            {
                dateTime += differential;
            }
            catch (ArgumentOutOfRangeException exception)
            {
                _loggerService.Exception($"{dateTimeStr} {differential} The added or subtracted value results in an un-representable DateTime.", exception);
            }

            _preferencesService.SetValue(epochKey, dateTime.ToUnixEpoch());
            _preferencesService.RemoveValue(dateTimeKey);
        }
Example #3
0
        private async Task GetExposureNotificationConfig()
        {
            loggerService.StartMethod();
            try
            {
                string     container  = AppSettings.Instance.BlobStorageContainerName;
                string     url        = AppSettings.Instance.CdnUrlBase + $"{container}/Configration.json";
                HttpClient httpClient = httpClientService.Create();
                Task <HttpResponseMessage> response = httpClient.GetAsync(url);
                HttpResponseMessage        result   = await response;
                if (result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    loggerService.Info("Success to download configuration");
                    var content = await result.Content.ReadAsStringAsync();

                    preferencesService.SetValue(PreferenceKey.ExposureNotificationConfiguration, content);
                }
                else
                {
                    loggerService.Error("Fail to download configuration");
                }
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed download of exposure notification configuration.", ex);
            }
            finally
            {
                loggerService.EndMethod();
            }
        }
Example #4
0
        public async Task <bool> StartExposureNotification()
        {
            loggerService.StartMethod();
            try
            {
                var enabled = await Xamarin.ExposureNotifications.ExposureNotification.IsEnabledAsync();

                if (!enabled)
                {
                    await Xamarin.ExposureNotifications.ExposureNotification.StartAsync();
                }
                await EnabledAsync();

                loggerService.EndMethod();
                return(true);
            }
            catch (Exception ex)
            {
                await DisabledAsync();

                loggerService.Exception("Error enabling notifications.", ex);
                loggerService.EndMethod();
                return(false);
            }
            finally
            {
            }
        }
Example #5
0
        // POST /api/Register - Register User
        public async Task <bool> PostRegisterUserAsync()
        {
#if TEST_BACKTASK
            loggerService.StartMethod();
            loggerService.Debug(" skip /register ");
            loggerService.EndMethod();
            return(true);
#endif

            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 (HttpRequestException ex)
            {
                loggerService.Exception("Failed to register user.", ex);
            }

            loggerService.EndMethod();
            return(false);
        }
Example #6
0
        //public bool HasSecret() => secret != null;


        // POST /api/Register - Register User
        public async Task <UserDataModel> 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)
                {
                    var registerResult = Utils.DeserializeFromJson <RegisterResultModel>(result);

                    UserDataModel userData = new UserDataModel();
                    userData.Secret             = registerResult.Secret;
                    userData.UserUuid           = registerResult.UserUuid;
                    userData.JumpConsistentSeed = registerResult.JumpConsistentSeed;
                    userData.IsOptined          = true;
                    Application.Current.Properties["Secret"] = registerResult.Secret;
                    await Application.Current.SavePropertiesAsync();

                    SetSecret();

                    loggerService.EndMethod();
                    return(userData);
                }
            }
            catch (HttpRequestException ex) {
                loggerService.Exception("Failed to register user.", ex);
            }

            loggerService.EndMethod();
            return(null);
        }
Example #7
0
        // POST /api/Register - Register User
        public async Task <bool> PostRegisterUserAsync()
        {
            loggerService.StartMethod();
            try
            {
                await serverConfigurationRepository.LoadAsync();

                string url     = serverConfigurationRepository.UserRegisterApiEndpoint;
                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);
        }
Example #8
0
        // this will be called when they keys need to be collected from the server
        public async Task FetchExposureKeyBatchFilesFromServerAsync(Func <IEnumerable <string>, Task> submitBatches, CancellationToken cancellationToken)
        {
            loggerService.StartMethod();
            // This is "default" by default
            var rightNow = DateTimeOffset.UtcNow;

            try
            {
                foreach (var serverRegion in AppSettings.Instance.SupportedRegions)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    loggerService.Info("Start download files");
                    var(batchNumber, downloadedFiles) = await DownloadBatchAsync(serverRegion, cancellationToken);

                    loggerService.Info("End to download files");
                    loggerService.Info($"Batch number: {batchNumber}, Downloaded files: {downloadedFiles.Count}");

                    if (batchNumber == 0)
                    {
                        continue;
                    }

                    if (downloadedFiles.Count > 0)
                    {
                        loggerService.Info("C19R Submit Batches");
                        await submitBatches(downloadedFiles);

                        // delete all temporary files
                        foreach (var file in downloadedFiles)
                        {
                            try
                            {
                                File.Delete(file);
                            }
                            catch (Exception ex)
                            {
                                // no-op
                                loggerService.Exception("Fail to delete downloaded files", ex);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // any expections, bail out and wait for the next time
                loggerService.Exception("Fail to download files", ex);
            }
            loggerService.EndMethod();
        }
Example #9
0
        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);
        }
Example #10
0
        public override void Schedule()
        {
            _loggerService.StartMethod();

            var result = BGTaskScheduler.Shared.Register(BGTASK_IDENTIFIER, null, task =>
            {
                _loggerService.Info("Background task has been started.");

                ScheduleBgTask();

                var cancellationTokenSource = new CancellationTokenSource();
                task.ExpirationHandler      = cancellationTokenSource.Cancel;

                _ = Task.Run(async() =>
                {
                    try
                    {
                        await ExposureDetectionAsync(cancellationTokenSource);
                        task.SetTaskCompleted(true);
                    }
                    catch (OperationCanceledException exception)
                    {
                        _loggerService.Exception($"Background task canceled.", exception);
                        task.SetTaskCompleted(false);
                    }
                    catch (Exception exception)
                    {
                        _loggerService.Exception($"Exception", exception);
                        task.SetTaskCompleted(false);
                    }
                    finally
                    {
                        cancellationTokenSource.Dispose();
                    }
                }, cancellationTokenSource.Token);
            });

            if (result)
            {
                _loggerService.Debug("BGTaskScheduler.Shared.Register succeeded.");
            }
            else
            {
                _loggerService.Info("BGTaskScheduler.Shared.Register failed.");
            }

            ScheduleBgTask();

            _loggerService.EndMethod();
        }
Example #11
0
        public async Task <TermsUpdateInfoModel> GetTermsUpdateInfo()
        {
            loggerService.StartMethod();

            var uri = AppResources.UrlTermsUpdate;

            using (var client = new HttpClient())
            {
                try
                {
                    var json = await client.GetStringAsync(uri);

                    loggerService.Info($"uri: {uri}");
                    loggerService.Info($"TermsUpdateInfo: {json}");

                    var deserializedJson = Utils.DeserializeFromJson <TermsUpdateInfoModel>(json);

                    loggerService.EndMethod();

                    return(deserializedJson);
                }
                catch (Exception ex)
                {
                    loggerService.Exception("Failed to get terms update info.", ex);
                    loggerService.EndMethod();

                    return(new TermsUpdateInfoModel());
                }
            }
        }
Example #12
0
        public async Task <bool> IsUpdateVersionExistAsync()
        {
            _loggerService.StartMethod();

            var uri = AppResources.UrlVersion;

            try
            {
                var json = await _httpClient.GetStringAsync(uri);

                var key           = _essentialsService.IsIos ? "ios" : "android";
                var versionString = JObject.Parse(json).Value <string>(key);

                return(new Version(versionString).CompareTo(new Version(_essentialsService.AppVersion)) > 0);
            }
            catch (Exception ex)
            {
                _loggerService.Exception("Failed to check version.", ex);
            }
            finally
            {
                _loggerService.EndMethod();
            }

            return(false);
        }
Example #13
0
        public async Task <bool> UploadAsync(string zipFilePath, string sasToken)
        {
            loggerService.StartMethod();

            var result = false;

            try
            {
                // Upload to storage.
                var logTmpPath = logPathService.LogUploadingTmpPath;

                var setting     = AppSettings.Instance;
                var endpoint    = setting.LogStorageEndpoint;
                var uploadPath  = setting.LogStorageContainerName;
                var accountName = setting.LogStorageAccountName;

                var uploadResult = await storageService.UploadAsync(endpoint, uploadPath, accountName, sasToken, zipFilePath);

                if (!uploadResult)
                {
                    throw new Exception("Failed to upload to storage.");
                }

                result = true;
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed upload.", ex);
            }

            loggerService.EndMethod();
            return(result);
        }
Example #14
0
        public async Task <HttpStatusCode> RegisterUserAsync()
        {
            loggerService.StartMethod();
            try
            {
                var resultStatusCode = await httpDataService.PostRegisterUserAsync();

                if (resultStatusCode == HttpStatusCode.OK)
                {
                    loggerService.Info("Success register");
                    userDataRepository.SetStartDate(DateTime.UtcNow);
                }
                else
                {
                    loggerService.Info("Failed register");
                }

                loggerService.EndMethod();
                return(resultStatusCode);
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed to register user.", ex);
                loggerService.EndMethod();
                throw;
            }
        }
Example #15
0
        private void MigrateDateTimeToEpoch(string dateTimeKey, string epochKey, TimeZoneInfo?timeZoneInfo, DateTime fallbackDateTime)
        {
            string dateTimeStr = _preferencesService.GetStringValue(dateTimeKey, fallbackDateTime.ToString());

            /// **Note**
            /// `dateTime` still can be `0001/01/01 00:00:00` (= UNIX Epoch:`-62135596800`).
            /// For compatibility reasons, do not change this behavior.
            DateTime dateTime;

            try
            {
                dateTime = DateTime.Parse(dateTimeStr);

                if (timeZoneInfo is null)
                {
                    dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
                }
                else
                {
                    dateTime = TimeZoneInfo.ConvertTimeToUtc(
                        DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified),
                        timeZoneInfo
                        );
                }
            }
            catch (FormatException exception)
            {
                _loggerService.Exception($"Parse dateTime FormatException occurred. {dateTimeStr}", exception);
                dateTime = fallbackDateTime;
            }

            _preferencesService.SetLongValue(epochKey, dateTime.ToUnixEpoch());
            _preferencesService.RemoveValue(dateTimeKey);
        }
Example #16
0
        public override async void Initialize(INavigationParameters parameters)
        {
            loggerService.StartMethod();

            // Check Version
            AppUtils.CheckVersion(loggerService);
            try
            {
                await exposureNotificationService.StartExposureNotification();

                await exposureNotificationService.FetchExposureKeyAsync();

                var statusMessage = await exposureNotificationService.UpdateStatusMessageAsync();

                loggerService.Info($"Exposure notification status: {statusMessage}");

                base.Initialize(parameters);

                loggerService.EndMethod();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());

                loggerService.Exception("Failed to exposure notification status.", ex);
                loggerService.EndMethod();
            }
        }
Example #17
0
        public async Task <TermsUpdateInfoModel> GetTermsUpdateInfo()
        {
            loggerService.StartMethod();

            var uri = AppResources.UrlTermsUpdate;

            try
            {
                var json = await _httpClient.GetStringAsync(uri);

                loggerService.Info($"uri: {uri}");
                loggerService.Info($"TermsUpdateInfo: {json}");

                var deserializedJson = JsonConvert.DeserializeObject <TermsUpdateInfoModel>(json);

                loggerService.EndMethod();

                return(deserializedJson);
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed to get terms update info.", ex);
                loggerService.EndMethod();

                return(new TermsUpdateInfoModel());
            }
        }
        public override async void Initialize(INavigationParameters parameters)
        {
            base.Initialize(parameters);

            _loggerService.StartMethod();

            _exposureRiskCalculationConfiguration
                = parameters.GetValue <V1ExposureRiskCalculationConfiguration>(ExposureCheckPage.ExposureRiskCalculationConfigurationKey);

            if (_exposureRiskCalculationConfiguration is null)
            {
                _exposureRiskCalculationConfiguration
                    = await _exposureRiskCalculationConfigurationRepository.GetExposureRiskCalculationConfigurationAsync(preferCache : true);
            }

            _loggerService.Info(_exposureRiskCalculationConfiguration.ToString());

            ShowExposureRiskCalculationConfiguration();

            try
            {
                // 一時的に閾値未満の内容は表示しないようにするためコメントアウト
                //_ = Setup();
            }
            catch (Exception exception)
            {
                _loggerService.Exception("Exception occurred", exception);
            }
            finally
            {
                _loggerService.EndMethod();
            }
        }
Example #19
0
        public static IList <TemporaryExposureKey> FiilterTemporaryExposureKeys(
            IList <TemporaryExposureKey> temporaryExposureKeys,
            DateTime diagnosisDate,
            int daysToSendTek,
            ILoggerService loggerService
            )
        {
            loggerService.StartMethod();

            List <TemporaryExposureKey> filteredTemporaryExposureKeys = new List <TemporaryExposureKey>();

            try
            {
                var fromDateTime = diagnosisDate.AddDays(daysToSendTek);
                var fromInterval = fromDateTime.ToEnInterval();

                filteredTemporaryExposureKeys.AddRange(temporaryExposureKeys.Where(x => x.RollingStartIntervalNumber >= fromInterval));

                loggerService.Info($"Filter: After {fromInterval}");
            }
            catch (Exception ex)
            {
                loggerService.Exception("Temporary exposure keys filtering failed", ex);
                throw ex;
            }
            finally
            {
                loggerService.Info($"Count: {filteredTemporaryExposureKeys.Count()}");
                loggerService.EndMethod();
            }

            return(filteredTemporaryExposureKeys);
        }
Example #20
0
        private async Task ScheduleLocalNotificationAsync()
        {
            _loggerService.StartMethod();

            try
            {
                var settings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync();

                if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
                {
                    throw new Exception($"UserNotification is not authorized: {settings.AuthorizationStatus}");
                }

                var content = new UNMutableNotificationContent();

                content.Title = AppResources.LocalExposureNotificationTitle;
                content.Body  = AppResources.LocalExposureNotificationContent;

                var request            = UNNotificationRequest.FromIdentifier(NOTIFICATION_ID, content, null);
                var notificationCenter = UNUserNotificationCenter.Current;
                await notificationCenter.AddNotificationRequestAsync(request);
            }
            catch (Exception e)
            {
                _loggerService.Exception("Exception occurred", e);
            }

            _loggerService.EndMethod();
        }
Example #21
0
        public SendEventLogState GetSendEventLogState(EventType eventType)
        {
            string stateString = EMPTY_DICT;

            try
            {
                _loggerService.StartMethod();

                if (!_preferencesService.ContainsKey(PreferenceKey.SendEventLogState))
                {
                    return(SendEventLogState.NotSet);
                }

                stateString = _preferencesService.GetStringValue(
                    PreferenceKey.SendEventLogState,
                    EMPTY_DICT
                    );

                IDictionary <string, int> stateDict
                    = JsonConvert.DeserializeObject <IDictionary <string, int> >(stateString);

                if (!stateDict.ContainsKey(eventType.ToString()))
                {
                    return(SendEventLogState.NotSet);
                }

                int value = stateDict[eventType.ToString()];
                return((SendEventLogState)Enum.ToObject(typeof(SendEventLogState), value));
            }
            catch (JsonReaderException exception)
            {
                _preferencesService.SetStringValue(PreferenceKey.SendEventLogState, EMPTY_DICT);

                _loggerService.Exception($"JsonSerializationException {stateString}", exception);
                _loggerService.Warning($"Preference-key {PreferenceKey.SendEventLogState} has been initialized.");
            }
            finally
            {
                _loggerService.EndMethod();
            }

            return(SendEventLogState.NotSet);
        }
Example #22
0
 public void NavigateAppSettings()
 {
     _loggerService.StartMethod();
     try
     {
         var intent = new Intent();
         intent.SetAction(Android.Provider.Settings.ActionApplicationDetailsSettings);
         intent.SetData(Android.Net.Uri.Parse($"package:{_essentialsService.AppPackageName}"));
         _platformService.CurrentActivity.StartActivity(intent);
     }
     catch (Exception ex)
     {
         _loggerService.Exception("Failed navigate to application settings", ex);
     }
     finally
     {
         _loggerService.EndMethod();
     }
 }
Example #23
0
        private async Task <bool> SendAsync(string idempotencyKey, List <EventLog> eventLogList)
        {
            _loggerService.StartMethod();

            try
            {
                var request = new V1EventLogRequest()
                {
                    IdempotencyKey = idempotencyKey,
                    Platform       = _essentialsService.Platform,
                    AppPackageName = _essentialsService.AppPackageName,
                    EventLogs      = eventLogList,
                };

                // Create device verification payload
                PolicyResult <string> policyResult = await Policy
                                                     .HandleResult <string>(result => _deviceVerifier.IsErrorPayload(result))
                                                     .WaitAndRetryAsync(3, retryAttempt => {
                    double delay = Math.Pow(2, retryAttempt + 1);
                    _loggerService.Warning($"Payload creation failed. retryAttempt:{retryAttempt} delay:{delay}sec");
                    return(TimeSpan.FromSeconds(delay));
                })
                                                     .ExecuteAndCaptureAsync(() => _deviceVerifier.VerifyAsync(request));

                if (policyResult.Outcome == OutcomeType.Failure)
                {
                    _loggerService.Error("Payload creation failed all.");
                    return(false);
                }

                _loggerService.Info("Payload creation successful.");
                request.DeviceVerificationPayload = policyResult.Result;

                ApiResponse <string> response = await _httpDataService.PutEventLog(request);

                _loggerService.Info($"PutEventLog() StatusCode:{response.StatusCode}");

                if (response.StatusCode == (int)HttpStatusCode.Created)
                {
                    _loggerService.Info("Send event log succeeded");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                _loggerService.Exception("Exception occurred, SendAsync", ex);
            }
            finally
            {
                _loggerService.EndMethod();
            }

            _loggerService.Error("Send event log failure");
            return(false);
        }
Example #24
0
        private void HandleSendLogAsync(BGAppRefreshTask task)
        {
            _loggerService.StartMethod();

            ScheduleSendEventLog();

            var cancellationTokenSource = new CancellationTokenSource();

            task.ExpirationHandler = cancellationTokenSource.Cancel;

            _ = Task.Run(async() =>
            {
                _loggerService.Info("HandleSendLogAsync() Task.Run() start");
                try
                {
                    await _eventLogRepository.RotateAsync(
                        AppConstants.EventLogFileExpiredSeconds);

                    await _eventLogService.SendAllAsync(
                        AppConstants.EventLogMaxRequestSizeInBytes,
                        AppConstants.EventLogMaxRetry);
                    task.SetTaskCompleted(true);
                }
                catch (OperationCanceledException exception)
                {
                    _loggerService.Exception($"Background task canceled.", exception);
                    task.SetTaskCompleted(false);
                }
                catch (Exception exception)
                {
                    _loggerService.Exception($"Exception", exception);
                    task.SetTaskCompleted(false);
                }
                finally
                {
                    cancellationTokenSource.Dispose();
                    _loggerService.Info("HandleSendLogAsync() Task.Run() end");
                }
            });

            _loggerService.EndMethod();
        }
Example #25
0
        private async Task StartExposureNotificationAsync()
        {
            loggerService.StartMethod();

            try
            {
                var isSuccess = await exposureNotificationApiService.StartExposureNotificationAsync();

                if (isSuccess)
                {
                    await UpdateView();
                }
            }
            catch (ENException exception)
            {
                loggerService.Exception("Failed to exposure notification start.", exception);
                await UpdateView();
            }
            catch (AndroidGooglePlayServicesApiException exception)
            {
                loggerService.Exception("Failed to exposure notification start.", exception);
                await UpdateView();
            }
            finally
            {
                loggerService.EndMethod();
            }
        }
Example #26
0
        // POST /api/Register - Register User
        public async Task <HttpStatusCode> PostRegisterUserAsync()
        {
            loggerService.StartMethod();
            try
            {
                await serverConfigurationRepository.LoadAsync();

                string url     = serverConfigurationRepository.UserRegisterApiEndpoint;
                var    content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

                HttpResponseMessage result = await httpClient.PostAsync(url, content);

                loggerService.EndMethod();
                return(result.StatusCode);
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed to register user.", ex);
                loggerService.EndMethod();
                throw;
            }
        }
Example #27
0
 public void Rotate()
 {
     loggerService.StartMethod();
     try
     {
         var dateTimes   = Utils.JstDateTimes(14);
         var logsDirPath = logPathService.LogsDirPath;
         var logFiles    = Directory.GetFiles(logsDirPath, logPathService.LogFileWildcardName);
         foreach (string fileName in logFiles)
         {
             if (ShouldDeleteFile(dateTimes, fileName))
             {
                 File.Delete(fileName);
                 loggerService.Info($"Deleted '{Path.GetFileName(fileName)}'");
             }
         }
     }
     catch (Exception ex)
     {
         loggerService.Exception("Failed to log files rotate.", ex);
     }
     loggerService.EndMethod();
 }
        public bool ContainsKey(string key)
        {
            var contains = false;

            lock (this)
            {
                loggerService.StartMethod();
                loggerService.Info($"key={key}");
                try
                {
                    contains = secureStorageDependencyService.ContainsKey(key);
                    loggerService.Info($"contains={contains}");
                }
                catch (Exception ex)
                {
                    loggerService.Exception("Failed existance confirmation.", ex);
                }
                finally
                {
                    loggerService.EndMethod();
                }
            }
            return(contains);
        }
Example #29
0
        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();
            }
        }
Example #30
0
        public async Task <bool> UploadAsync(string zipFileName)
        {
            loggerService.StartMethod();

            var result = false;

            try
            {
                // Get the storage SAS Token for upload.
                var logStorageSasResponse = await httpDataService.GetLogStorageSas();

                if (logStorageSasResponse.StatusCode != (int)HttpStatusCode.OK)
                {
                    throw new Exception("Status is error.");
                }
                if (string.IsNullOrEmpty(logStorageSasResponse.Result.SasToken))
                {
                    throw new Exception("Storage SAS Token is null or empty.");
                }

                // Upload to storage.
                var logTmpPath = logPathService.LogUploadingTmpPath;
                var logZipPath = Path.Combine(logTmpPath, zipFileName);

                var setting     = AppSettings.Instance;
                var endpoint    = setting.LogStorageEndpoint;
                var uploadPath  = setting.LogStorageContainerName;
                var accountName = setting.LogStorageAccountName;
                var sasToken    = logStorageSasResponse.Result.SasToken;

                var uploadResult = await storageService.UploadAsync(endpoint, uploadPath, accountName, sasToken, logZipPath);

                if (!uploadResult)
                {
                    throw new Exception("Failed to upload to storage.");
                }

                result = true;
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed upload.", ex);
            }

            loggerService.EndMethod();
            return(result);
        }