//private static OfflineService instance; //public static OfflineService Instance //{ // get // { // if (instance == null) // { // instance = new OfflineService(); // } // return instance; // } //} public static async Task Write <T>(T result, string fileName, IFolder folder) { string Itemcreds = Newtonsoft.Json.JsonConvert.SerializeObject(result); await PCLHelper.CreateFile(fileName, folder); await PCLHelper.WriteTextAllAsync(fileName, Itemcreds, folder); }
private async void teste22(object sender, EventArgs e) { try { var mi = ((MenuItem)sender); Tuple <String, String, int, int> behis = (Tuple <String, String, int, int>)mi.CommandParameter; int aux2 = behis.Item3; Conteste = await dataService.GetContentByIdAsync(aux2); // DisplayAlert("OK", "ve " + Conteste.contentmsg.ToString(), "Ok"); String aux = Historico2.Text; String[] auxNelson = Historico2.Text.Split('-'); bool existe = await PCLHelper.ArquivoExisteAsync(ficheiro); if (existe != true) { await PCLHelper.CriarArquivo(ficheiro); Historico2.Text = ""; aux = Conteste.contentmsg.ToString(); await PCLHelper.WriteTextAllAsync(ficheiro, aux); LeInfoUsuario111(ficheiro); } else { if (!auxNelson.Contains(Conteste.contentmsg.ToString())) { if (aux == "") { aux = Conteste.contentmsg.ToString(); } else { aux = aux + "-" + Conteste.contentmsg.ToString(); } } await PCLHelper.WriteTextAllAsync(ficheiro, aux); //await DisplayAlert("Login", "já existe", "OK"); LeInfoUsuario111(ficheiro); } auxNelson = null; Historico2.Text = ""; AtualizaDados(a); } catch (Exception ex) { await DisplayAlert("Erro", ex.Message, "OK"); } }
public async Task SaveToPCL() { if (!await PCLHelper.IsFileExistAsync(ConfigFileName)) { await PCLHelper.CreateFile(ConfigFileName); } var configJson = JsonConvert.SerializeObject(_sharedViewModel.ApplicationConfiguration); await PCLHelper.WriteTextAllAsync(ConfigFileName, configJson); }
public static async Task <T> Read <T>(string fileName, IFolder folder) { if (await PCLHelper.IsFileExistAsync(fileName)) { string content = await PCLHelper.ReadAllTextAsync(fileName, folder); return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(content)); } return(default(T)); }
public DictViewModel() { Title = Language.txtTitleDictation; ButtonEnabled = true; lstSpecialWords = new List <SpecialWords>(); ShuffleCommand = new Command(new Action(ShuffleCommandAction)); SayCommand = new Command(new Action <object>(SayItCommandAction), CanSayItCommandAction); CheckCommand = new Command(new Action <object>(CheckCommandAction), new Func <object, bool>(CanCheckCommandAction)); wordDetails = new WordDetails(); wordDetails.TypingWordFinished += Wp_TypingWordFinished; wordDetails.TypingCancelled += Wp_TypingCancelled; SayCommand.ChangeCanExecute(); var assembly = IntrospectionExtensions.GetTypeInfo(typeof(DictViewModel)).Assembly; Stream stream = assembly.GetManifestResourceStream("MultiplicationTable.XMLText.xml"); txtXml = string.Empty; using (var reader = new System.IO.StreamReader(stream)) { txtXml = reader.ReadToEnd(); } xDoc = XDocument.Parse(txtXml); //CHECK IF USER ADDED USER DEFINED DICTATIONS Task t = new Task(async() => { try { IFolder folder = PCLStorage.FileSystem.Current.LocalStorage; if (await PCLHelper.IsFolderExistAsync("UserXML", folder)) { IFolder destFolder = await folder.GetFolderAsync("UserXML"); if (await PCLHelper.IsFileExistAsync("UserDict.xml", destFolder)) { IFile file = await destFolder.GetFileAsync("UserDict.xml"); string content = await file.ReadAllTextAsync(); if (!string.IsNullOrEmpty(content)) { xDocUser = XDocument.Parse(content); } } } } catch (Exception ex) { UserDialogs.Instance.Alert(Language.txtErrLoadingUserData + " " + ex.Message, Language.btnOk); } }); t.RunSynchronously(); }
private async void OnDeletar(object sender, EventArgs e) { try { Device.BeginInvokeOnMainThread(async() => { var result = await this.DisplayAlert("Delete!", "Are you sure you want to delete this registry?", "Yes", "No"); if (result) { var mi = ((MenuItem)sender); Tuple <String, String, int, int> behis = (Tuple <String, String, int, int>)mi.CommandParameter; // HistoricoModel historicoUtilizador = (HistoricoModel)mi.CommandParameter; int aux2 = behis.Item3; //historicoUtilizador.contentID; Conteste = await dataService.GetContentByIdAsync(aux2); string[] words = Historico2.Text.Split('-'); int conta = 0; String texto = ""; for (int i = 0; i < words.Length; i++) { if (words[i].Equals(Conteste.contentmsg.ToString())) { continue; } else { if (conta == 0) { texto = words[i]; conta++; } else { texto = texto + "-" + words[i]; conta++; } } } Historico2.Text = ""; await PCLHelper.WriteTextAllAsync(ficheiro, texto); await dataService.DeletaHitoricAsync(behis.Item4); LeInfoUsuario111(ficheiro); } }); } catch (Exception ex) { await DisplayAlert("Erro", ex.Message, "OK"); } }
private async Task GetUserData(string fileName) { try { SetWaiting(true); IFolder folder = PCLStorage.FileSystem.Current.LocalStorage; if (!(await PCLHelper.IsFolderExistAsync("UserXML", folder))) { UserDialogs.Instance.Alert(Language.txtUserDataNoDataUploaded, Language.txtErrorTitle); } else { IFolder destFolder = await folder.GetFolderAsync("UserXML"); if (!await PCLHelper.IsFileExistAsync(fileName, destFolder)) { UserDialogs.Instance.Alert(Language.txtUserDataNoDataUploaded + " " + fileName, Language.txtErrorTitle); } else { string fileContent = await PCLHelper.ReadAllTextAsync(fileName, destFolder); IFileSave DocLibrary = DependencyService.Get <IFileSave>(); bool res = await DocLibrary.SaveXml(fileContent, fileName); if (res) { UserDialogs.Instance.Alert(Language.txtUserDataLoaded + " " + fileName, Language.txtDictOk); } else { UserDialogs.Instance.Alert(Language.txtErrLoadingUserData + " " + fileName, Language.txtDictOk); } } } SetWaiting(false); } catch (Exception ex) { SetWaiting(false); UserDialogs.Instance.Alert(Language.txtErrLoadingUserData + " " + ex.Message, Language.txtErrorTitle); } finally { await Task.CompletedTask; } }
public async void LeInfoUsuario111(string arquivo) { Historico2.Text = ""; string conteudo = await PCLHelper.ReadAllTextAsync(arquivo); Historico2.Text = conteudo.ToString(); words = Historico2.Text.Split('-'); teste.ItemsSource = conteudo.ToString().Split('-'); //DisplayAlert("tps", "todos " + conteudo.ToString(), "asd"); AtualizaDados(a); //await DisplayAlert("KSADJF", "asd:> " + conteudo.ToString(), "okok"); }
private async void GetBudgetInformation() { var info = await PCLHelper.ReadAllTextAsync("Budget.txt"); var b = JsonConvert.DeserializeObject <Budget>(info.ToString()); sBudget.Text = $"Budget: {b.TotalBudget}"; currentBalance.Text = $"Balance: {b.CurrentBudget}"; model.CurrentBudget = b.CurrentBudget; model.TotalBudget = b.TotalBudget; model.DateModified = DateTime.Now; model.DateCreated = b.DateCreated; model.SelectedMonth = b.SelectedMonth; model.Description = null; }
protected async Task <byte[]> GetResourceBDAsync(string namefile) { try { bool isexist = await PCLHelper.IsFileExistAsync(namefile); if (isexist) { return(await PCLHelper.LoadImage(namefile)); } return(null); } catch (Exception ex) { return(null); } }
public async void LeInfoUsuario111(string arquivo) { string conteudo = await PCLHelper.ReadAllTextAsync(arquivo); if (conteudo.Equals("")) { EmtHist.IsVisible = true; } else { EmtHist.IsVisible = false; } Historico2.Text = conteudo.ToString(); words = Historico2.Text.Split('-'); teste.ItemsSource = words; //await DisplayAlert("KSADJF", "asd:> " + conteudo.ToString(), "okok"); }
private async void SetBudget(object sender, EventArgs e) { var _setBudget = new Budget { TotalBudget = decimal.Parse(budgetAmount.Text), CurrentBudget = decimal.Parse(budgetAmount.Text), DateCreated = DateTime.Now, DateModified = DateTime.Now, Spent = 0, Description = null, SelectedMonth = monthPicker.SelectedItem.ToString() }; var _writeToFile = JsonConvert.SerializeObject(_setBudget); //check if folder exists if (await PCLHelper.IsFolderExistAsync("AppContent")) { //now check if file exist if (await PCLHelper.IsFileExistAsync("Budget.txt")) { //write await PCLHelper.WriteTextAllAsync("Budget.txt", _writeToFile); } else { //create file and write await PCLHelper.CreateFile("Budget.txt"); await PCLHelper.WriteTextAllAsync("Budget.txt", _writeToFile); } } else { //create folder await PCLHelper.CreateFolder("AppContent"); await PCLHelper.CreateFile("Budget.txt"); await PCLHelper.WriteTextAllAsync("Budget.txt", _writeToFile); } await Navigation.PushAsync(new CurrentBudgetInfo()); }
private async void Guardar() { bool existe = await PCLHelper.ArquivoExisteAsync("User.txt"); if (existe != true) { flag = true; //await PCLHelper.CriarArquivo("User.txt"); //await PCLHelper.WriteTextAllAsync(fichPermi, aux); } else { String utilizadorRegistado = await PCLHelper.ReadAllTextAsync("User.txt"); await Navigation.PushAsync(new Historico(utilizadorRegistado)); } //DisplayAlert("ok", "mandie " + isToggled.ToString(), "ok"); }
public async Task <ApplicationConfiguration> GetConfigurationFromPCL() { if (!await PCLHelper.IsFileExistAsync(ConfigFileName)) { return(new ApplicationConfiguration() { DeskViewSettings = new DeskViewSettings() { PanelName = "West Bollsta - meeting room", CurrentBackgroundImage = "Background_Blue.jpg" } }); } var content = PCLHelper.ReadAllTextAsync(ConfigFileName); var config = JsonConvert.DeserializeObject <ApplicationConfiguration>(content); return(config); }
private async void Lixo2(object sender, EventArgs e) { //DisplayAlert("OK", "ENJREi", "ok"); var mi = ((MenuItem)sender); String ver = (String)mi.CommandParameter; //Tem o do historico string[] words = Historico2.Text.Split('-'); int conta = 0; String texto = ""; for (int i = 0; i < words.Length; i++) { if (words[i].Equals(ver)) { continue; } else { if (conta == 0) { texto = words[i]; conta++; } else { if (!texto.Contains(words[i])) { texto = texto + "-" + words[i]; conta++; } } } } Historico2.Text = ""; await PCLHelper.WriteTextAllAsync(ficheiro, texto); // DisplayAlert("OK", "tenho " + ver.ToString(), "OK"); LeInfoUsuario111(ficheiro); }
private async void Lixo(object sender, EventArgs e) { try { if (Historico2.Text != "") { Device.BeginInvokeOnMainThread(async() => { var result = await this.DisplayAlert("Delete!", "Are you sure you want to delete this registry?", "Yes", "No"); if (result) { await PCLHelper.WriteTextAllAsync(ficheiro, ""); Historico2.Text = ""; LeInfoUsuario111(ficheiro); await PCLHelper.DeleteFile(ficheiro); } }); } LeInfoUsuario111(ficheiro); } catch (Exception ola) { } // await PCLHelper.WriteTextAllAsync(ficheiro, ""); }
public async Task <string> GetUserLogoImageWithPath(User user) { try { var folder = await PCLHelper.GetFolder(Settings.profileFolder); if (folder != null && user != null && !string.IsNullOrEmpty(user.UserLogo)) { var logofileName = user.UserLogo.Replace('-', '_'); var filePath = await PCLHelper.GetFilePathAsync(logofileName, folder); if (filePath != null) { return(filePath.ToString()); } } return(null); }catch (Exception e) { return(null); } }
public async new Task Add(User user) { if (!string.IsNullOrEmpty(user.UserLogo) && !string.IsNullOrEmpty(user.UserLogoContent)) { try { //var base64Image = user.UserLogoContent.Replace(/^ data:image\/[a - z] +; base64,/, ""); /*var regex = new Regex(@"data:(?<mime>[\w/\-\.]+);(?<encoding>\w+),(?<data>.*)"); * * var match = regex.Match(user.UserLogoContent); * * var mime = match.Groups["mime"].Value; * var encoding = match.Groups["encoding"].Value;*/ var imgData = user.UserLogoContent.Substring(user.UserLogoContent.IndexOf(",") + 1); byte[] imageBytes = Convert.FromBase64String(imgData); var folder = await PCLHelper.GetFolder(Settings.profileFolder); if (folder != null) { //var logofile = await PCLHelper.CreateFile(user.UserLogo, folder); var logofileName = user.UserLogo.Replace('-', '_'); var logofile = await PCLHelper.WriteTextAllAsync(logofileName, imageBytes.ToString(), folder); //await logofile.WriteAllTextAsync(content); } } catch (Exception e) { // skip the image } } user.UserLogoContent = ""; await Connection.InsertOrReplaceAsync(user); }
public async void AddExpenditure(object sender, EventArgs e) { decimal expense = 0m; decimal.TryParse(expenditure.Text, out expense); var result = await BalanceAfterExpenditure(model.CurrentBudget, expense); currentBalance.Text = result.ToString(); //now update file var newBudget = new Budget { TotalBudget = model.TotalBudget, CurrentBudget = result, DateCreated = model.DateCreated, DateModified = model.DateModified, SelectedMonth = model.SelectedMonth, }; var json = JsonConvert.SerializeObject(newBudget); await PCLHelper.WriteTextAllAsync("Budget.txt", json.ToString()); expenditure.Text = null; }
async Task <bool> ParsingAllFiles() { // Get file content json var fileContent = await PCLHelper.ReadAllTextAsync("1.json", new FileSystemFolder(Path.Combine(localAppData, "1"))); if (fileContent.Length != 0) { // Dico full JSON Dictionary <string, object> dicoJSON = JsonConvert.DeserializeObject <Dictionary <string, object> >(fileContent); foreach (KeyValuePair <string, object> keyValuePairJSON in dicoJSON) { // Process keys fiches if (keyValuePairJSON.Key == "pathologies") { Dictionary <string, object> dicoGrouping = JsonConvert.DeserializeObject <Dictionary <string, object> >(keyValuePairJSON.Value.ToString()); if (keyValuePairJSON.Key == "pathologies") { dicoPathologies = new Dictionary <string, dynamic>(dicoGrouping); InitPathologies(); } } // Process ressources key if (keyValuePairJSON.Key == "ressources") { List <Dictionary <string, object> > dico = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(keyValuePairJSON.Value.ToString()); InitRessources(dico); } } return(true); } return(false); }
private async void Login(object sender, EventArgs e) { bool a = verificaInter(); bool testar = true; if (txtPassword.Text == null || txtUsername.Text == null) { if (txtPassword.Text == null && txtUsername.Text == null) { await DisplayAlert("Error", "Please enter the username and password", "Ok"); } else if (txtUsername.Text == null) { await DisplayAlert("Error", "Please enter the username or email", "Ok"); } else if (txtPassword.Text == null) { await DisplayAlert("Error", "Please enter the password", "Ok"); } a = false; testar = false; } if (a == true) { String auxilia = sha256_hash(txtPassword.Text); var res = await dataService.GetLogin(txtUsername.Text, auxilia); // DisplayAlert("Error3", "entrou " + txtUsername.Text, "Ok"); try { switch (Device.RuntimePlatform) { case Device.iOS: //padding = 10; break; case Device.Android: //padding = 0; ble = CrossBluetoothLE.Current; adapter = CrossBluetoothLE.Current.Adapter; VerEstado(); break; case Device.UWP: //padding = 0; //DisplayAlert("OIOI","OLA N","ASD"); break; default: //DisplayAlert("DEF", "FED", "ASD"); break; } if (res == true) { String a1 = txtUsername.Text; if (a1.Contains("@") == true) { //DisplayAlert("Error", "entrou "+txtUsername.ToString(), "Ok"); try { MyProgressBar.IsVisible = true; Regis.IsEnabled = false; Log.IsEnabled = false; txtUsername.IsEnabled = false; txtPassword.IsEnabled = false; await MyProgressBar.ProgressTo(0.9, 500, Easing.SpringIn); if (flag == true) { await PCLHelper.CriarArquivo("User.txt"); } await PCLHelper.WriteTextAllAsync("User.txt", a1); await Navigation.PushAsync(new Historico(a1)); txtPassword.Text = ""; } finally { Regis.IsEnabled = true; Log.IsEnabled = true; txtUsername.IsEnabled = true; txtPassword.IsEnabled = true; MyProgressBar.IsVisible = false; MyProgressBar.Progress = 0; } } else { Utilizador auxiliar = await dataService.GetUtilizadorByusernameAsync(a1); try { MyProgressBar.IsVisible = true; Regis.IsEnabled = false; Log.IsEnabled = false; await MyProgressBar.ProgressTo(0.9, 500, Easing.SpringIn); if (flag == true) { await PCLHelper.CriarArquivo("User.txt"); } await PCLHelper.WriteTextAllAsync("User.txt", auxiliar.email); await Navigation.PushAsync(new Historico(auxiliar.email)); txtPassword.Text = ""; } finally { Regis.IsEnabled = true; Log.IsEnabled = true; MyProgressBar.IsVisible = false; MyProgressBar.Progress = 0; } } } else { await DisplayAlert("Error", "User or Password Wrong", "Ok"); } } catch (Exception ex) { //DisplayAlert("Error2", "User or Password Wrong", "Ok"); //Debug.WriteLine("Answer: " + ex); // DisplayAlert("Alert", "User or password wrong", "Ok"); } } else { if (testar == true) { DisplayAlert("Internet", "Connect your device to the internet", "OK"); } } }
private async Task UpdateUserData(string fileName) { try { SetWaiting(true); var resultPrompt = await UserDialogs.Instance.ConfirmAsync(new ConfirmConfig { Message = Language.txtUserDataPrompt, OkText = Language.txtDictOk, CancelText = Language.btnCancel }); if (resultPrompt) { var result = await Plugin.FilePicker.CrossFilePicker.Current.PickFile(); if (result != null) { XDocument xDocument = XDocument.Parse(Encoding.UTF8.GetString(result.DataArray)); IFolder folder = PCLStorage.FileSystem.Current.LocalStorage; IFolder destFolder = null; if (!(await PCLHelper.IsFolderExistAsync("UserXML", folder))) { destFolder = await PCLHelper.CreateFolder("UserXML"); } else { destFolder = await folder.GetFolderAsync("UserXML"); } if (await PCLHelper.IsFileExistAsync(fileName)) { await PCLHelper.DeleteFile(fileName); } IFile tFile = await PCLHelper.CreateFile(fileName, destFolder); await tFile.WriteAllTextAsync(xDocument.ToString()); SetWaiting(false); UserDialogs.Instance.Alert(Language.txtUserDataUpdated, Language.txtMultOk); } else { SetWaiting(false); UserDialogs.Instance.Alert(Language.txtErrLoadingUserData, Language.txtErrorBtn); } } else { SetWaiting(false); } } catch (Exception ex) { SetWaiting(false); UserDialogs.Instance.Alert(Language.txtErrLoadingUserData + " " + ex.Message, Language.txtErrorTitle); } finally { await Task.CompletedTask; } }
private void ReadDataFromSource() { Task.Run(() => { try { SetFormState(false); var assembly = IntrospectionExtensions.GetTypeInfo(typeof(DictViewModel)).Assembly; Stream stream = assembly.GetManifestResourceStream("MultiplicationTable.LanguageWords.xml"); string txtXml = string.Empty; using (var reader = new System.IO.StreamReader(stream)) { txtXml = reader.ReadToEnd(); } XDocument xDoc = XDocument.Parse(txtXml); CategoriesSource = new ObservableCollection <string>(); LearningWords = new ObservableCollection <LearningWord>(); IEnumerable <XElement> de = from el in xDoc.Descendants() select el; foreach (XElement el in de) { if (el.Name == "Word") { IEnumerable <XElement> desc = from elDesc in el.Descendants() select elDesc; LearningWord lw = new LearningWord(); foreach (XElement elDescendant in desc) { if (elDescendant.Name == "en") { lw.English = elDescendant.Value; } if (elDescendant.Name == "pl") { lw.Polish = elDescendant.Value; } if (elDescendant.Name == "category_pl") { if (CategoriesSource.Where(q => q == elDescendant.Value).FirstOrDefault() == null) { MainThread.BeginInvokeOnMainThread(() => { //UWAGA -> na androidzie działa to inaczej !!, to jest wykonywane PO FAKCIE if (!CategoriesSource.Contains(elDescendant.Value)) { CategoriesSource.Add(elDescendant.Value); } }); } lw.PolishCategory = elDescendant.Value; } if (elDescendant.Name == "category_en") { lw.EnglishCategory = elDescendant.Value; } } MainThread.BeginInvokeOnMainThread(() => { LearningWords.Add(lw); }); } } //LOAD USER DATA XML IFolder folder = PCLStorage.FileSystem.Current.LocalStorage; if (PCLHelper.IsFolderExistAsync("UserXML", folder).GetAwaiter().GetResult()) { IFolder destFolder = folder.GetFolderAsync("UserXML").GetAwaiter().GetResult(); if (PCLHelper.IsFileExistAsync("UserWord.xml", destFolder).GetAwaiter().GetResult()) { IFile file = destFolder.GetFileAsync("UserWord.xml").GetAwaiter().GetResult(); string content = file.ReadAllTextAsync().GetAwaiter().GetResult(); XDocument xDocUser = XDocument.Parse(content); IEnumerable <XElement> deUser = from el in xDocUser.Descendants() select el; foreach (XElement el in deUser) { if (el.Name == "Word") { IEnumerable <XElement> desc = from elDesc in el.Descendants() select elDesc; LearningWord lw = new LearningWord(); foreach (XElement elDescendant in desc) { if (elDescendant.Name == "en") { lw.English = elDescendant.Value; } if (elDescendant.Name == "pl") { lw.Polish = elDescendant.Value; } if (elDescendant.Name == "category_pl") { if (!CategoriesSource.Contains(elDescendant.Value)) { MainThread.BeginInvokeOnMainThread(() => { if (!CategoriesSource.Contains(elDescendant.Value)) { CategoriesSource.Add(elDescendant.Value); } }); } lw.PolishCategory = elDescendant.Value; } if (elDescendant.Name == "category_en") { lw.EnglishCategory = elDescendant.Value; } } MainThread.BeginInvokeOnMainThread(() => { LearningWords.Add(lw); }); } } } } SetFormState(true); } catch (Exception ex) { UserDialogs.Instance.Alert(Language.txtErrorMessage + ex.Message, Language.txtErrorTitle); } }); }
private async void LogOff() { await PCLHelper.DeleteFile("User.txt"); CoreApplication.Exit(); }