private async void ResetSettings_Click(object sender, RoutedEventArgs e) { MessageDialog md = new MessageDialog("重置默认设置吗?", "消息提示"); md.Commands.Add(new UICommand("确定", cmd => { }, "重置")); md.Commands.Add(new UICommand("取消", cmd => { })); var result = await md.ShowAsync(); if (result.Id as string == "重置") { App.Rules = await LocalObjectStorageHelper.ReadFileAsync <Rules>("rules_origin"); await LocalObjectStorageHelper.SaveFileAsync("rules", App.Rules); LocalObjectStorageHelper.Save("settings", App.Rules.GetSettings()); } md = new MessageDialog("是否重启应用?", "重启应用后设置才能生效"); md.Commands.Add(new UICommand("确定", cmd => { }, "重启")); md.Commands.Add(new UICommand("取消", cmd => { })); result = await md.ShowAsync(); if (result.Id as string == "重启") { await CoreApplication.RequestRestartAsync(string.Empty); } }
protected override void OnApiModeChanged(ApiConfig config) { //This needs UI context since we're dealing with ObservableCollection rebuildForumListAsync(config); // Task.Run(async() => { //nothing big deal, thread pool should suffice await _storageHelper.SaveFileAsync(forum_cache_key, new List <Forum>()); _storageHelper.Save(current_api_key, config); }); }
public async Task SaveTransactionsAsync(IEnumerable <FinanceAccount> accountsToSave, IDictionary <string, IEnumerable <Transaction> > accountTransactions) { // Saves each list of transactions in parallel // to speed up things up. The transaction saving operations are mutually exclusive. Parallel.ForEach(accountsToSave, async(account) => { string accountName = account.Name; IEnumerable <Transaction> transactionsToSave = accountTransactions[accountName]; await _objectHelper.SaveFileAsync($"{accountName}{AccountTransactionExtension}", transactionsToSave); }); await _objectHelper.SaveFileAsync(AccountsFileName, accountsToSave); }
private async Task WirelessLogin() { var response = await NetHelper.LoginAsync(currentAccount.Username, currentAccount.Password); if (response == "Login is successful.") { SetLoginButtonAnimation(); } else if (response == "IP has been online, please logout.") { SetLoginButton(); } else if (response == "E2532: The two authentication interval cannot be less than 3 seconds.") { await Task.Delay(3500); await LoginNetworkIfFavoriteAsync(); } else if (response == "E2553: Password is error.") { CredentialHelper.RemoveAccount(App.Accounts[0].Username); App.Accounts.RemoveAt(0); var localHelper = new LocalObjectStorageHelper(); await localHelper.SaveFileAsync("Accounts", App.Accounts); var rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(WelcomePage)); } }
private void StartObserveDataChanged() { DataChangedDisposable.Disposable = Observable.Merge(DocumentsSource.CollectionChangedAsObservable().ToUnit(), DocumentsSource.ObserveElementObservableProperty(x => x.Title).ToUnit(), DocumentsSource.ObserveElementObservableProperty(x => x.Content).ToUnit()) .Throttle(TimeSpan.FromSeconds(5)) .Subscribe(async _ => await LocalObjectStorageHelper.SaveFileAsync("docs.json", DocumentsSource.ToArray())); }
public async Task RunAsync(IBackgroundTaskInstance taskInstance) { // Create services var localObjectStorageHelper = new LocalObjectStorageHelper(); // Check if notifications are enabled var notificationsEnabled = localObjectStorageHelper.Read(LocalStorageConstants.EnableNewEpisodeNotificationsOption, true); if (!notificationsEnabled) { return; } // Retrieve token to access API string token = RetrieveToken(); // Create services (2) var tvshowtimeApiService = new TVShowTimeApiService(token); // Retrieve episodes from the agenda (episodes that will be aired soon) var agendaResponse = await tvshowtimeApiService.GetAgendaAsync(); if (agendaResponse.Result == "OK") { // Retrieve list of episodes already notified var newEpisodesIdsNotified = new List <long>(); if (await localObjectStorageHelper.FileExistsAsync(LocalStorageConstants.NewEpisodesIdsNotified)) { newEpisodesIdsNotified = await localObjectStorageHelper .ReadFileAsync(LocalStorageConstants.NewEpisodesIdsNotified, new List <long>()); } var episodesInAgenda = agendaResponse.Episodes; foreach (var episode in episodesInAgenda) { var timeSpanDiff = episode.AirDate.Value.Subtract(DateTime.Now.ToUniversalTime()); if (episode.AirTime.HasValue) { timeSpanDiff = timeSpanDiff .Add(TimeSpan.FromHours(episode.AirTime.Value.DateTime.Hour)); timeSpanDiff = timeSpanDiff .Add(TimeSpan.FromMinutes(episode.AirTime.Value.DateTime.Minute)); } if (newEpisodesIdsNotified.All(id => episode.Id != id) && timeSpanDiff.TotalDays <= 0) { // Create Toast notification when a new episode is out GenerateToastNotification(episode); newEpisodesIdsNotified.Add(episode.Id); } } // Save the updated list in local storage await localObjectStorageHelper.SaveFileAsync(LocalStorageConstants.NewEpisodesIdsNotified, newEpisodesIdsNotified); } }
public async static void GetLatestRules() { Rules Rules; using (HttpClient HttpClient = new HttpClient()) { HttpClient.Timeout = TimeSpan.FromSeconds(10); var HttpResopnse = await HttpClient.GetAsync(UpdateRulesUri); if (HttpResopnse.StatusCode == HttpStatusCode.OK) { string StringRules = await HttpResopnse.Content.ReadAsStringAsync(); Rules = JsonConvert.DeserializeObject <Rules>(StringRules); if (Rules == null) { return; } if (Rules.version > App.Rules.version) { LocalObjectStorageHelper LocalObjectStorageHelper = new LocalObjectStorageHelper(); await LocalObjectStorageHelper.SaveFileAsync("rules_origin", Rules); await LocalObjectStorageHelper.SaveFileAsync("rules", Rules); var NewSettings = Rules.GetSettings(); var OldSettings = App.Rules.GetSettings(); foreach (var Item in OldSettings) { if (NewSettings.ContainsKey(Item.Key)) { NewSettings[Item.Key] = Item.Value; } } LocalObjectStorageHelper.Save("settings", NewSettings); Rules.SetSettings(NewSettings); App.Rules = Rules; } } } }
private async void InitRules() { LocalObjectStorageHelper LocalObjectStorageHelper = new LocalObjectStorageHelper(); if (!await LocalObjectStorageHelper.FileExistsAsync("rules_origin")) { var Folder = await Package.Current.InstalledLocation.GetFolderAsync("Data"); var FileRules = await Folder.GetFileAsync("rules.json"); string StringRules = await FileIO.ReadTextAsync(FileRules); var TempRules = JsonConvert.DeserializeObject <Rules>(StringRules); await LocalObjectStorageHelper.SaveFileAsync("rules_origin", TempRules); } if (!await LocalObjectStorageHelper.FileExistsAsync("rules")) { var Folder = await Package.Current.InstalledLocation.GetFolderAsync("Data"); var FileRules = await Folder.GetFileAsync("rules.json"); string StringRules = await FileIO.ReadTextAsync(FileRules); Rules = JsonConvert.DeserializeObject <Rules>(StringRules); await LocalObjectStorageHelper.SaveFileAsync("rules", Rules); } else { Rules = await LocalObjectStorageHelper.ReadFileAsync <Rules>("rules"); } if (!LocalObjectStorageHelper.KeyExists("settings")) { LocalObjectStorageHelper.Save("settings", Rules.GetSettings()); } else { var settings = LocalObjectStorageHelper.Read <Dictionary <string, bool> >("settings"); Rules.SetSettings(settings); } }
private async Task <object> storeAmazonItemsAsync() { /* * StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("AmazonItems.txt", CreationCollisionOption.ReplaceExisting); * await Windows.Storage.FileIO.WriteTextAsync(sampleFile, JsonConvert.SerializeObject(AmazonItems)); */ var helper = new LocalObjectStorageHelper(); await helper.SaveFileAsync("AmazonItems", AmazonItems); return(null); }
private Task <string> GetFriendsActivitiesWeb(int page, int pageSize) { return(Task.Run(async() => { //await Task.Delay(3000); string activities = await _stravaService.GetFriendActivityDataAsync(page, pageSize); if (page == 1) //TODO: Glenn - we only cache the first page ( these are always the newest items ) { await _storageHelper.SaveFileAsync(StorageKeys.ACTIVITIESALL, activities); } return activities; })); }
private async Task GetUsageChartSourceAsync() { await UseregHelper.LoginAsync(currentAccount.Username, currentAccount.Password); DetailUsage = await UseregHelper.GetDetailUsageForChart(); if (DetailUsage != null) { var localHelper = new LocalObjectStorageHelper(); await localHelper.SaveFileAsync("DetailUsage", DetailUsage); (DetailUsageChart.Series[0] as LineSeries).ItemsSource = DetailUsage; SetChartAxis(); } }
private async Task WiredLogin(Windows.Security.Credentials.PasswordCredential credential) { var response = await AuthHelper.LoginAsync(4, currentAccount.Username, credential.Password); if (response == null) { return; } if (response.Contains("login_ok")) { SetLoginButtonAnimation(); await GetConnectionStatusAsync(); var response6 = await AuthHelper.LoginAsync(6, currentAccount.Username, credential.Password); if (response6 != null && response6.Contains("login_error")) { await Task.Delay(10100); await AuthHelper.LoginAsync(6, currentAccount.Username, credential.Password); } } else if (response == "ip_already_online_error") { SetLoginButton(); } else if (response == "not_online_error") { await WirelessLogin(); } else if (response.Contains("login_error")) { await Task.Delay(10100); await LoginNetworkIfFavoriteAsync(); } else { CredentialHelper.RemoveAccount(App.Accounts[0].Username); App.Accounts.RemoveAt(0); var localHelper = new LocalObjectStorageHelper(); await localHelper.SaveFileAsync("Accounts", App.Accounts); var rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(WelcomePage)); } }
public static async Task <StatusCode> SaveDataAsync() { try { StorageFile data = await localFolder.CreateFileAsync("data.txt", CreationCollisionOption.ReplaceExisting); var helper = new LocalObjectStorageHelper(); await helper.SaveFileAsync(keyLargeObject, proj); return(StatusCode.Success); } catch (Exception) { return(StatusCode.StorageError); } }
private async void LogOut_Click(object sejnder, RoutedEventArgs e) { LoginModel EmptyLoginResponseObj = new LoginModel { UserName = null, Name = null, surName = null, Email = null, role = null, Token = null, IsLoged = false }; await helper.SaveFileAsync("response", EmptyLoginResponseObj); Frame.Navigate(typeof(LoginPage), null, new DrillInNavigationTransitionInfo()); }
private async Task GetConnectionStatusAsync() { var status = await NetHelper.GetStatusAsync(); if (status != null) { ConnectionStatus.Usage = Utility.GetUsageDescription((long)status["total_usage"]); ConnectionStatus.Balance = Utility.GetBalanceDescription(Convert.ToDouble(status["balance"])); ConnectionStatus.Username = status["username"] as string; var sessionNumber = await UseregHelper.GetSessionNumberAsync(currentAccount.Username, currentAccount.Password); ConnectionStatus.Session = sessionNumber == -1 ? "--" : sessionNumber.ToString(); var localHelper = new LocalObjectStorageHelper(); await localHelper.SaveFileAsync("ConnectionStatus", ConnectionStatus); } }
public static async void Save <T>(List <T> list, string filename) { var helper = new LocalObjectStorageHelper(); if (list.Count != 0) { await helper.SaveFileAsync(filename, list); } else { if (await StorageFileHelper.FileExistsAsync(ApplicationData.Current.LocalFolder, filename)) { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename); await file.DeleteAsync(); } } }
private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { AccountDialog accountDialog = sender as AccountDialog; var username = accountDialog.UsernameTextBox.Text; var originalPassword = accountDialog.PasswordBox.Password; var password = Utility.ComputeMD5(originalPassword); Account newAccount = new Account { Username = username, Password = password }; var duplicatedAccounts = App.Accounts.Where(u => u.Username == newAccount.Username).ToList(); if (duplicatedAccounts.Count > 0) { duplicatedAccounts.Single().Username = newAccount.Username; duplicatedAccounts.Single().Password = newAccount.Password; } else { if (await UseregHelper.LoginAsync(newAccount.Username, newAccount.Password) == "ok") { App.Accounts.Add(newAccount); var localHelper = new LocalObjectStorageHelper(); await localHelper.SaveFileAsync("Accounts", App.Accounts); CredentialHelper.AddAccount(username, originalPassword); } else { var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView(); ContentDialog contentDialog = new ContentDialog() { Title = resourceLoader.GetString("Error"), Content = resourceLoader.GetString("AccountValidationFail"), PrimaryButtonText = resourceLoader.GetString("Ok") }; await contentDialog.ShowAsync(); } } }
private async void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { Busy.SetBusy(true, "Checking Usage"); var dataList = await Pronto.DataUsage(); if (dataList.errorList.Count == 0) { dataLimit.Text = dataList.planList[0].ToString(); dataStartDate.Text = dataList.planList[1].ToString(); dataEndDate.Text = dataList.planList[2].ToString(); dataTime.Text = dataList.usageList[0].ToString(); dataUploaded.Text = dataList.usageList[1].ToString(); dataDownloaded.Text = dataList.usageList[2].ToString(); dataTotal.Text = dataList.usageList[3].ToString(); Busy.SetBusy(false); StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile sampleFile = await localFolder.CreateFileAsync("dataUsage.txt", CreationCollisionOption.ReplaceExisting); ////Read the first line of dataFile.txt in LocalFolder and store it in a String //StorageFile sampleFiile = await localFolder.GetFileAsync("dataFittlee.txt"); //IList<string> fileContent = await FileIO.ReadLinesAsync(sampleFiile); // Read complex/large objects var helper = new LocalObjectStorageHelper(); await helper.SaveFileAsync(keyLargeObject, dataList); Pronto.ValueTileUpdater(dataList.usageList[2].ToString()); } else { Busy.SetBusy(false); MainPage.ShowDialog(dataList.errorList[0]); } } catch (System.Exception) { Busy.SetBusy(false); return; } }
public async void OnClick_NewConnection(Object sender, RoutedEventArgs e) { ContentDialogResult result = await newConnectionDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { if (currentConnectionString != defaultString) { var newConnection = new ConnectionString { connectionString = currentConnectionString, nickname = currentNick }; recentConnectionStrings.Add(newConnection); UpdateMenuItems(); currentConnection = newConnection; await storageHelper.SaveFileAsync(connectionStore, recentConnectionStrings); } } else { } }
private async void SignIn_Button(object sejnder, RoutedEventArgs e) { SubmitButton.IsEnabled = false; if (!string.IsNullOrEmpty(password.Password) && TextBoxRegex.GetIsValid(email) && NetworkInterface.GetIsNetworkAvailable()) { SignInModel loginObj = new SignInModel { Email = email.Text, Password = password.Password, }; string json = JsonConvert.SerializeObject(loginObj); ConnectionModel IP = new ConnectionModel(); RestClient client = new RestClient(IP.Adress); RestRequest request = new RestRequest("Account/login", Method.POST); _ = request.AddParameter("application/json", json, ParameterType.RequestBody); IRestResponse response = client.Execute(request); if (response.StatusCode != System.Net.HttpStatusCode.InternalServerError && response.StatusCode != System.Net.HttpStatusCode.NotFound && response.StatusCode != System.Net.HttpStatusCode.BadGateway && response.StatusCode != System.Net.HttpStatusCode.BadRequest && response.StatusCode != 0) { LoginModel tokenObj = JsonConvert.DeserializeObject <LoginModel>(response.Content); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); SecurityToken jsonToken = handler.ReadToken(tokenObj.Token); LoginModel tokenvalidateObj = new LoginModel { UserName = ((JwtSecurityToken)jsonToken).Payload["userName"].ToString(), Name = ((JwtSecurityToken)jsonToken).Payload["name"].ToString(), surName = ((JwtSecurityToken)jsonToken).Payload["sureName"].ToString(), Email = ((JwtSecurityToken)jsonToken).Payload["email"].ToString(), role = ((JwtSecurityToken)jsonToken).Payload["role"].ToString(), Token = tokenObj.Token, IsLoged = true }; if (response.StatusCode == System.Net.HttpStatusCode.OK) { _ = await helper.SaveFileAsync("response", tokenvalidateObj); SubmitButton.IsEnabled = true; _ = Frame.Navigate(typeof(MainPage), null, new DrillInNavigationTransitionInfo()); } else { _ = await new CustomDialog("Wystąpił błąd podczas komunikacji z serwerem.", response.StatusCode.ToString(), CustomDialog.Type.Error).ShowAsync(); SubmitButton.IsEnabled = true; } } else { _ = await new CustomDialog("Konto o podanym loginie/haśle nie istnieje lub brak połączenia z serwerem.", response.StatusCode.ToString(), CustomDialog.Type.Error).ShowAsync(); SubmitButton.IsEnabled = true; } } else { _ = await new CustomDialog("Wprowadzono błędne dane lub brak połączenia z internetem.", null, CustomDialog.Type.Warning).ShowAsync(); SubmitButton.IsEnabled = true; } }
private async void UpdateSettings_Click(object sender, RoutedEventArgs e) { Rules Rules; using (HttpClient HttpClient = new HttpClient()) { HttpClient.Timeout = TimeSpan.FromSeconds(10); var HttpResopnse = await HttpClient.GetAsync(Utils.UpdateRulesUri); if (HttpResopnse.StatusCode == HttpStatusCode.OK) { string StringRules = await HttpResopnse.Content.ReadAsStringAsync(); Rules = JsonConvert.DeserializeObject <Rules>(StringRules); if (Rules == null) { MessageDialog md = new MessageDialog("未知错误", "更新失败"); md.Commands.Add(new UICommand("确定", cmd => { })); await md.ShowAsync(); return; } if (Rules.version > App.Rules.version) { MessageDialog md = new MessageDialog("请问是否更新?", "已检测到新的更新"); md.Commands.Add(new UICommand("确定", cmd => { }, "更新")); md.Commands.Add(new UICommand("取消", cmd => { })); var result = await md.ShowAsync(); if (result.Id as string == "更新") { LocalObjectStorageHelper LocalObjectStorageHelper = new LocalObjectStorageHelper(); await LocalObjectStorageHelper.SaveFileAsync("rules_origin", Rules); await LocalObjectStorageHelper.SaveFileAsync("rules", Rules); var NewSettings = Rules.GetSettings(); var OldSettings = App.Rules.GetSettings(); foreach (var Item in OldSettings) { if (NewSettings.ContainsKey(Item.Key)) { NewSettings[Item.Key] = Item.Value; } } LocalObjectStorageHelper.Save("settings", NewSettings); Rules.SetSettings(NewSettings); App.Rules = Rules; md = new MessageDialog("某些设置将在重启后生效", "更新成功!"); md.Commands.Add(new UICommand("确定", cmd => { })); await md.ShowAsync(); } } else { MessageDialog md = new MessageDialog("您无需更新", "已经是最新版本了"); md.Commands.Add(new UICommand("确定", cmd => { })); await md.ShowAsync(); } } else { MessageDialog md = new MessageDialog("请检查您的网络", "更新失败"); md.Commands.Add(new UICommand("确定", cmd => { })); await md.ShowAsync(); } } }