Exemplo n.º 1
0
Arquivo: Save.cs Projeto: joeshizzy/CR
        public async Task <string> CheckFile(string foldername, string filename, string json)
        {
            try
            {
                IFolder folder         = FileSystem.Current.LocalStorage;
                var     checkExistence = await folder.CheckExistsAsync(foldername);

                if (checkExistence != ExistenceCheckResult.FolderExists)
                {
                    return("KO");
                }
                else
                {
                    folder = await folder.CreateFolderAsync(foldername, CreationCollisionOption.OpenIfExists);

                    IFile file3;
                    var   t = await folder.CheckExistsAsync(filename);

                    if (t == ExistenceCheckResult.FileExists)
                    {
                        return("OK");
                    }
                    else
                    {
                        return("KO");
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message.ToString());
            }
        }
Exemplo n.º 2
0
        protected async Task <string> GetImagePath(string codart)
        {
            if (!string.IsNullOrWhiteSpace(codart))
            {
                IFolder rootFolder   = FileSystem.Current.LocalStorage;
                IFolder imagesFolder = await rootFolder.CreateFolderAsync("images", CreationCollisionOption.OpenIfExists);

                String fileName             = codart.Trim() + "_0.PNG";
                ExistenceCheckResult status = await imagesFolder.CheckExistsAsync(fileName);

                if (status == ExistenceCheckResult.FileExists)
                {
                    return(rootFolder.Path + "/images/" + fileName);
                }
                fileName = codart.Trim() + "_0.JPG";
                status   = await imagesFolder.CheckExistsAsync(fileName);

                if (status == ExistenceCheckResult.FileExists)
                {
                    return(rootFolder.Path + "/images/" + fileName);
                }
            }
            return("header_wallpaper.jpg");
            //return (null);
        }
Exemplo n.º 3
0
        public async Task <string> DataLoadAsync( )
        {
            string name;
            ExistenceCheckResult res = await rootFolder.CheckExistsAsync("name.txt");

            if (res == ExistenceCheckResult.FileExists)
            {
                IFile file = await rootFolder.GetFileAsync("name.txt");

                name = await file.ReadAllTextAsync();

                //return name;
            }
            else
            {
                //ファイル作成
                IFile file = await rootFolder.CreateFileAsync("name.txt", CreationCollisionOption.ReplaceExisting);

                await file.WriteAllTextAsync(entry.Text);

                //ファイル読み込み
                file = await rootFolder.GetFileAsync("name.txt");

                name = await file.ReadAllTextAsync();

                //return name;
                await DisplayAlert("Error", "File is not found", "OK");

                //await DisplayAlert("Error1", "File is not found", "OK");
                //return Convert.ToString(file);
                //return name;
            }
            return(name);
        }
Exemplo n.º 4
0
        public async Task <bool> IsFolderIsExistAsync(string folderName)
        {
            ExistenceCheckResult folderExist = await folder.CheckExistsAsync(folderName);

            if (folderExist == ExistenceCheckResult.FolderExists)
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 5
0
 private async void LoadClicked(object sender, EventArgs e)
 {
     ExistenceCheckResult res = await rootFolder.CheckExistsAsync("name.txt");
     if (res == ExistenceCheckResult.FileExists)
     {
         IFile file = await rootFolder.GetFileAsync("name.txt");
         string name = await file.ReadAllTextAsync();
         loadedLabel.Text = name;
     }
     else
     {
         await DisplayAlert("Error", "File is not found", "OK");
     }
 }
Exemplo n.º 6
0
Arquivo: Save.cs Projeto: joeshizzy/CR
        public async Task <string> WriteFile(string foldername, string filename, string json)
        {
            try
            {
                IFolder folder         = FileSystem.Current.LocalStorage;
                var     checkExistence = await folder.CheckExistsAsync(foldername);

                if (checkExistence != ExistenceCheckResult.FolderExists)
                {
                    folder = await folder.CreateFolderAsync(foldername, CreationCollisionOption.ReplaceExisting);

                    IFile file3;
                    var   t = await folder.CheckExistsAsync(filename);

                    if (t == ExistenceCheckResult.FileExists)
                    {
                        //file3 = await file3.OpenAsync(filename, CreationCollisionOption.ReplaceExisting);
                    }
                    IFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                    await file.WriteAllTextAsync(json);

                    var y = await file.ReadAllTextAsync();

                    return("OK");
                }
                else
                {
                    folder = await folder.CreateFolderAsync(foldername, CreationCollisionOption.OpenIfExists);

                    IFile file3;
                    var   t = await folder.CheckExistsAsync(filename);

                    if (t == ExistenceCheckResult.FileExists)
                    {
                    }
                    IFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                    await file.WriteAllTextAsync(json);

                    var y = await file.ReadAllTextAsync();

                    return("OK");
                }
            }
            catch (Exception ex)
            {
                return(ex.Message.ToString());
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// SQLiteデータベースへのコネクションを取得する。
        /// 取得したコネクションは取得した側で正しくクローズ処理すること。
        /// </summary>
        /// <returns></returns>
        private async Task <SQLiteConnection> CreateConnection()
        {
            const string DatabaseFileName = "item.db3";
            // ルートフォルダを取得する
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            // DBファイルの存在チェックを行う
            var result = await rootFolder.CheckExistsAsync(DatabaseFileName);

            if (result == ExistenceCheckResult.NotFound)
            {
                // 存在しなかった場合、新たにDBファイルを作成しテーブルも併せて新規作成する
                IFile file = await rootFolder.CreateFileAsync(DatabaseFileName, CreationCollisionOption.ReplaceExisting);

                var connection = new SQLiteConnection(file.Path);
                connection.CreateTable <Item>();
                return(connection);
            }
            else
            {
                // 存在した場合、そのままコネクションを作成する
                IFile file = await rootFolder.CreateFileAsync(DatabaseFileName, CreationCollisionOption.OpenIfExists);

                return(new SQLiteConnection(file.Path));
            }
        }
Exemplo n.º 8
0
        public static async void Load()
        {
            dic.Load();
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            IFolder folder     = await rootFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

            if ((await folder.CheckExistsAsync(fileName)) == ExistenceCheckResult.FileExists)
            {
                IFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                //structures = JsonConvert.DeserializeObject<List<string>>(await file.ReadAllTextAsync());
            }
            else
            {
                structures = new List <PoemStructure> {
                    new PoemStructure("%nnp %tnc the %nnp %mvi %pr the %ep like the %dp %ep %pr the %epo %nn %ati the %nnp of %th ."),
                    new PoemStructure("%nn %tn the %nnp %mvi %pr the %ad %ep like the %dp %ep %pr the %ep %ati the %nn of %th ."),
                    new PoemStructure("the %nnp , the %nnp , and the %nnp %mvp %pr the %ad %ep and these %tnp the %nnp %ati %nnp and %ad %nnp . It %tn the %ep ."),
                    new PoemStructure("%am %nnp %mvp %pr %ad %nnp ."),
                    new PoemStructure("%am %nnp %mvp %dr as they could have %mvp ."),
                    new PoemStructure("because it %tnf the %ad and %ad %nn ."),
                    new PoemStructure("%mvi , %mva %nn %tn %dpa %nn %ati the %ad %nn ."),
                    new PoemStructure("And %pn , the %nn , %pr %ad %nn ."),
                    new PoemStructure("%nna %tn %nnp %mvi %pr %epa %adl .")
                };
            }
        }
Exemplo n.º 9
0
        public static async Task <Word> LoadWordAsync(Language lang)
        {
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            var     fileName   = string.Format(CacheFileFormat, lang.ToString());

            var exists = await rootFolder.CheckExistsAsync(fileName);

            if (exists == ExistenceCheckResult.FileExists)
            {
                //read contents
                var file = await rootFolder.GetFileAsync(fileName);

                var json = await file.ReadAllTextAsync();

                var cachedWord  = JsonConvert.DeserializeObject <Word> (json);
                var cachedDate  = cachedWord.Date.Date;
                var currentDate = DateTime.Now.Date;

                if (cachedDate == currentDate)
                {
                    //date same, so just return cached word.
                    return(cachedWord);
                }
            }

            //file doesn't exist or needs updating, so return null.
            return(null);
        }
Exemplo n.º 10
0
        public async Task LoadLocations()
        {
            string  fileName            = "settings.xml";
            IFolder folder              = FileSystem.Current.LocalStorage;
            ExistenceCheckResult result = await folder.CheckExistsAsync(fileName);

            if (result == ExistenceCheckResult.FileExists)
            {
                try
                {
                    IFile file = await folder.GetFileAsync(fileName);

                    string text = await file.ReadAllTextAsync();

                    using (var reader = new StringReader(text))
                    {
                        var          serializer = new XmlSerializer(typeof(SaveLocation));
                        SaveLocation settings   = (SaveLocation)serializer.Deserialize(reader);
                        for (int i = 0; i < settings.Savelocation.Count; i++)
                        {
                            listLocations.Add(new ListLocation {
                                Id        = settings.Savelocation[i].Id,
                                Locations = settings.Savelocation[i].Locations, NameList = settings.Savelocation[i].NameList
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error reading settings: {ex.Message}");
                }
            }
        }
        private async void TreeView_ItemTapped(object sender, Syncfusion.XForms.TreeView.ItemTappedEventArgs e)
        {
            string filename = "";

            try
            {
                var selficha = (e.Node.Content) as SubFolder;
                if (selficha != null)
                {
                    filename = selficha.SubFolderName + ".pdf";

                    IFolder rootFolder = await FileSystem.Current.GetFolderFromPathAsync("/storage/emulated/0/Fichas/");

                    ExistenceCheckResult folderexist = await rootFolder.CheckExistsAsync(filename);

                    if (folderexist == ExistenceCheckResult.FileExists)
                    {
                        DependencyService.Get <IFileManager>().OpenFile("/storage/emulated/0/Fichas/" + filename);
                    }
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error", ex.Message, "OK");
            }
        }
Exemplo n.º 12
0
        public async Task UploadResponsedSurveys()
        {
            folder = FileSystem.Current.LocalStorage;
            if (!CheckNetwork.Check_Connectivity())
            {
                return;
            }
            List <Survey>        surveys = new List <Survey>();
            ExistenceCheckResult result  = await folder.CheckExistsAsync("ShareResponsedSurveys");

            if (result == ExistenceCheckResult.FolderExists)
            {
                folder = await folder.CreateFolderAsync("ShareResponsedSurveys", CreationCollisionOption.OpenIfExists);

                file = await folder.CreateFileAsync("ShareResponsedSurveys", CreationCollisionOption.OpenIfExists);

                string Content = await file.ReadAllTextAsync();

                if (String.IsNullOrEmpty(Content) || String.IsNullOrWhiteSpace(Content))
                {
                    return;
                }
                surveys = Serializable_Survey.deserialize(Content).ToList();
                foreach (Survey S in surveys)
                {
                    SurveysServices S_S = new SurveysServices();
                    S_S.Set_UrlApi("ShareResponsedSurveys/");
                    await S_S.PostSurveysAsync(S);
                }
                file = await folder.GetFileAsync("ShareResponsedSurveys");

                await file.DeleteAsync();
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Reading Values from the Storage...
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <returns></returns>
        public async Task <Set1> Get_Value <T>(String filename)
        {
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            IFolder folder     = await rootFolder.CreateFolderAsync("Set1",
                                                                    CreationCollisionOption.OpenIfExists);

            ExistenceCheckResult isFileExisting = await folder.CheckExistsAsync(filename);

            if (!isFileExisting.ToString().Equals("NotFound"))
            {
                try
                {
                    IFile file = await folder.CreateFileAsync(filename,
                                                              CreationCollisionOption.OpenIfExists);

                    String languageString = await file.ReadAllTextAsync();

                    XmlSerializer oXmlSerializer = new XmlSerializer(typeof(T));
                    return((Set1)oXmlSerializer.Deserialize(new StringReader(languageString)));
                }
                catch (Exception ex)
                {
                    var message = ex.Message;
                    return(default(Set1));
                }
            }

            return(default(Set1));
        }
Exemplo n.º 14
0
        public static void LoadAppSettings()
        {
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            var     x          = rootFolder.CheckExistsAsync("Settings").Result;

            if (x.Equals(ExistenceCheckResult.FileExists))
            {
                IFile file = rootFolder.GetFileAsync("Settings").Result;
                if (file != null)
                {
                    string serializedSettings = file.ReadAllTextAsync().Result;
                    if (serializedSettings != null && !serializedSettings.Equals(string.Empty))
                    {
                        AppSettings = JsonConvert.DeserializeObject <Settings>(serializedSettings);
                    }
                    else
                    {
                        AppSettings = new Settings("2", "1", "10", "10");
                    }
                }
            }
            else
            {
                AppSettings = new Settings("2", "1", "10", "10");
            }
        }
Exemplo n.º 15
0
        public static async Task DownloadImage(string url, string name)
        {
            try
            {
                IFolder rootfolder         = FileSystem.Current.LocalStorage;
                ExistenceCheckResult exist = await rootfolder.CheckExistsAsync(name);

                if (exist == ExistenceCheckResult.NotFound)
                {
                    GemWriteLine("DOWNLOADING... " + url);

                    Uri uri    = new Uri(url);
                    var client = new HttpClient();

                    IFile file = await rootfolder.CreateFileAsync(name, CreationCollisionOption.OpenIfExists);

                    using (var fileHandler = await file.OpenAsync(FileAccess.ReadAndWrite))
                    {
                        var httpResponse = await client.GetAsync(uri);

                        byte[] dataBuffer = await httpResponse.Content.ReadAsByteArrayAsync();

                        await fileHandler.WriteAsync(dataBuffer, 0, dataBuffer.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                GemWriteLine("DownloadImage", ex.Message);
            }
        }
Exemplo n.º 16
0
        private async void CheckDatabase()
        {
            // IFolder interface comes from PCLStorage, check if database file is there
            IFolder rootFolder          = FileSystem.Current.LocalStorage;
            ExistenceCheckResult exists = await rootFolder.CheckExistsAsync(DatabaseName + ".db3");

            if (exists == ExistenceCheckResult.FileExists)
            {
                DisplayMainPage();

                return;
            }

            byte[] bytes;

            // DOWNLOADING THE DATABASE OR...
            //bytes = await GetRemoteDatabase(DatabaseName);

            // SHIPPING THE DATABASE ORIGINAL
            bytes = GetShippedDatabase(DatabaseName);

            await UnpackZipFile(bytes).ContinueWith(async(antecedent) =>
            {
                await CreateStorehouseAsync();

                DisplayMainPage();
            });
        }
Exemplo n.º 17
0
        private async void btnLogout_Clicked(object sender, EventArgs e)
        {
            if (await this.DisplayYesNoAlert("Are you sure you want to logout? Any work not syched will be lost?"))
            {
                App.DB.DropAndCreateDatabase();
                Settings.LoggedIn         = false;
                Settings.OfficerCode      = string.Empty;
                Settings.Password         = string.Empty;
                Settings.AuthToken        = string.Empty;
                Settings.FullName         = string.Empty;
                Settings.ClearUsername    = string.Empty;
                Settings.EmailAddress     = string.Empty;
                Settings.UserSites        = string.Empty;
                Settings.LastBaseDataSync = DateTime.MinValue;
                Settings.WifiOnly         = false;
                Settings.IsNewLogin       = true;
                IFolder localStorage        = FileSystem.Current.LocalStorage;
                ExistenceCheckResult exists = await localStorage.CheckExistsAsync(SyncHelper.FormsFolder);

                if (exists == ExistenceCheckResult.FolderExists)
                {
                    IFolder formsFolder = await localStorage.GetFolderAsync(SyncHelper.FormsFolder);

                    if (formsFolder != null)
                    {
                        await formsFolder.DeleteAsync();
                    }
                }
                App.Current.ShowLoginPage();
            }
        }
Exemplo n.º 18
0
        private void OnDelete(object sender, EventArgs e)
        {
            var selected     = (MenuItem)sender;
            var selectedFile = selected.CommandParameter as IFile;

            Device.BeginInvokeOnMainThread(async() =>
            {
                bool answer = await DisplayAlert("Delete File", "Do you want to delete " + selectedFile.Name + " ?", "Yes", "No");
                if (answer)
                {
                    IFolder folder             = FileSystem.Current.LocalStorage;
                    String folderName          = "receipt";
                    ExistenceCheckResult exist = await folder.CheckExistsAsync(folderName);

                    if (exist == ExistenceCheckResult.FolderExists)
                    {
                        IFile file = await folder.GetFileAsync(selectedFile.Name);

                        //	Act
                        await file.DeleteAsync();

                        IList <IFile> files     = await folder.GetFilesAsync();
                        pdfListView.ItemsSource = files;
                    }
                }
            });
        }
Exemplo n.º 19
0
        /// <summary>
        /// get image from local. (wait)
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private static async Task <byte[]> getImageByteFromLocal(string fileName, string containerName)
        {
            ///// 1. get image from local. (wait)
            // Access the file system for the current platform.
            IFileSystem fileSystem = FileSystem.Current;
            // Get the root directory of the file system for our application.
            IFolder rootFolder = fileSystem.LocalStorage;
            // Create another folder, if one doesn't already exist.
            IFolder photosFolder = await rootFolder.CreateFolderAsync(containerName, CreationCollisionOption.OpenIfExists);

            // Get File
            var checkResult = await photosFolder.CheckExistsAsync(fileName);

            if (checkResult == ExistenceCheckResult.FileExists)
            {
                IFile file = await photosFolder.GetFileAsync(fileName);

                if (file != null)
                {
                    using (System.IO.Stream stream = await file.OpenAsync(PCLStorage.FileAccess.Read))
                    {
                        return(Utils.ReadStram(stream));
                    }
                }
            }

            return(null);
        }
        private async void LoadFile()
        {
            string  folderName          = "orders";
            IFolder folder              = PCLStorage.FileSystem.Current.LocalStorage;
            ExistenceCheckResult result = await folder.CheckExistsAsync(folderName);

            if (result == ExistenceCheckResult.FolderExists)
            {
                try
                {
                    IFolder orderFolder = await folder.GetFolderAsync(folderName);

                    IList <IFile> files = await orderFolder.GetFilesAsync();

                    OrderLists = new ObservableCollection <OrderList>();
                    foreach (var item in files)
                    {
                        string text = await item.ReadAllTextAsync();

                        using (var reader = new StringReader(text))
                        {
                            var       serializer = new XmlSerializer(typeof(OrderList));
                            OrderList orderList  = (OrderList)serializer.Deserialize(reader);
                            this.Name  = orderList.Name;
                            this.Price = orderList.Price;
                            OrderLists.Add(orderList);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error reading location: {ex.Message}");
                }
            }
        }
Exemplo n.º 21
0
        private void RetrieveSessionStorage()
        {
            string sessionString = null;

#if PCL
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            if (ExistenceCheckResult.FileExists == rootFolder.CheckExistsAsync(_sessionStorageFileFullPath).Result)
            {
                IFile file = rootFolder.GetFileAsync(_sessionStorageFileFullPath).Result;
                sessionString = file.ReadAllTextAsync().Result;
            }
#elif BCL
            if (File.Exists(_sessionStorageFileFullPath))
            {
                using (var sessionFile = new System.IO.StreamReader(_sessionStorageFileFullPath))
                {
                    sessionString = sessionFile.ReadToEnd();
                    sessionFile.Close();
                }
                _logger.DebugFormat("Mobile Analytics retrieves session info: {0}", sessionString);
            }
            else
            {
                _logger.DebugFormat("Mobile Analytics session file does not exist.");
            }
#endif
            if (!string.IsNullOrEmpty(sessionString))
            {
                _sessionStorage = JsonMapper.ToObject <SessionStorage>(sessionString);
            }
        }
Exemplo n.º 22
0
        async void Start()
        {
            ExistenceCheckResult QuotesDataFolderExist = await LocalStorageFolder.CheckExistsAsync(quotefolderName); // check if quote folder exist

            if (QuotesDataFolderExist != ExistenceCheckResult.FolderExists)
            {
                IFolder CraeteQuotesFolder = await LocalStorageFolder.CreateFolderAsync(quotefolderName,
                                                                                        CreationCollisionOption.OpenIfExists); // creates quotes folder in local storage .. localstorage/../quotesfolder

                IFile CreateQuotesFile = await CraeteQuotesFolder.CreateFileAsync(quoteFileName,
                                                                                  CreationCollisionOption.OpenIfExists); // creates quotes file in local storage .. localstorage /../ quotesfolder/quotes.txt

                IFolder GetQuotesDataFolder = await LocalStorageFolder.GetFolderAsync(quotefolderName);                  // gets folder that contains "quotes.txt"

                IFile GetQuotesFile = await GetQuotesDataFolder.GetFileAsync(quoteFileName);                             // gets file that contains jsonified quotes

                string preData = "{\"quoteDetails\":{\"quoteContent\":[\"I LOVE Microsoft\",\"life is like a bowl of soup and im a fork\",\"HTML is a programming language\",\"you'll have to speak up iam wearing a towel\",\"is mayonnaise an instrument\"],\"quoteAuthor\":[\"Steve Jobs\",\"Donald Trump\",\"Me last year\",\"Homer Simpson\",\"Patrick Star\"]}}";

                await GetQuotesFile.WriteAllTextAsync(preData);
            }

            if (QuotesDataFolderExist == ExistenceCheckResult.FolderExists)
            {
                // go to folder
                IFolder GetQuotesDataFolder = await LocalStorageFolder.GetFolderAsync(quotefolderName); // gets folder that contains "quotes.txt"

                IFile GetQuotesFile = await GetQuotesDataFolder.GetFileAsync(quoteFileName);            // gets file that contains jsonified quotes
            }
        }
Exemplo n.º 23
0
        private async void LoadFile()
        {
            string  fileName            = "products.xml";
            IFolder folder              = PCLStorage.FileSystem.Current.LocalStorage;
            ExistenceCheckResult result = await folder.CheckExistsAsync(fileName);

            if (result == ExistenceCheckResult.FileExists)
            {
                try
                {
                    IFile file = await folder.GetFileAsync(fileName);

                    string text = await file.ReadAllTextAsync();

                    using (var reader = new StringReader(text))
                    {
                        var     serializer = new XmlSerializer(typeof(Product));
                        Product product    = (Product)serializer.Deserialize(reader);
                        this.currentSubCategory.Products.Add(product);
                        //this.Products.Add(product);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error reading location: {ex.Message}");
                }
            }
        }
Exemplo n.º 24
0
        public async Task Read()
        {
            Items = null;
            try
            {
                if (await Folder.CheckExistsAsync(FileName) == ExistenceCheckResult.FileExists)
                {
                    var File = await Folder.GetFileAsync(FileName);

                    var itemsAsString = await File.ReadAllTextAsync();

                    Items = JsonConvert.DeserializeObject <List <SettingValues> >(itemsAsString);
                }
            }
            catch (Exception ex)
            {
                Items = null;
                Debug.WriteLine(ex.ToString());
            }
            if (Items == null || Items.Count == 0)
            {
                LoadDefaults();
            }

            ChangAndRebuild();
        }
Exemplo n.º 25
0
        //Try to open and find the user's current quiz.
        async void GetCurrentUserDetails()
        {
            //Only registered users can resume unfinished quizzes.
            if (!Current_Data.isGuest)
            {
                try
                {
                    //Get the folder and file name
                    string folder_name = Current_Data.Username + "ongoing_files";    //The folder name for the specific user's saved ongoing quizzes.
                    string filename    = Current_Data.Username + "_ongoingQuiz.txt"; //This will create/overwrite the specific user's local file.

                    //First, get the folder.
                    IFolder read_folder = await Current_Data.root_folder.GetFolderAsync(folder_name);

                    //Check whether the file exists.
                    ExistenceCheckResult file_exist = await read_folder.CheckExistsAsync(filename);

                    string content = null;
                    //Read from the file if it exists.
                    if (file_exist == ExistenceCheckResult.FileExists)
                    {
                        //Once the file is found, get the .json string from it.
                        IFile read_file = await read_folder.GetFileAsync(filename);

                        content = await read_file.ReadAllTextAsync();

                        //Then, deserialize it.
                        List <Results> base_ongoing_quiz = new List <Results>();
                        base_ongoing_quiz = JsonConvert.DeserializeObject <List <Results> >(content);

                        //Lastly, extract the data. (Should only be 1 'object')
                        foreach (Results q in base_ongoing_quiz)
                        {
                            Current_Data.ongoing_Quiz = q;

                            //Next, get the current quiz.
                            foreach (RootQuiz quiz in Current_Data.all_quizzes)
                            {
                                if (Current_Data.ongoing_Quiz.quiz_id == quiz.id)
                                {
                                    Current_Data.selected_Quiz = quiz;
                                }
                            }
                        }

                        Current_Data.ongoingQuiz = true;
                    }
                    //If not, throw an exception.
                    else
                    {
                        throw new Exception("The user's file in the 'ongoing_files' folder cannot be found");
                    }
                }
                catch (Exception e)
                {
                    Current_Data.ongoingQuiz = false;
                    Debug.WriteLine("Extract File Error:" + e.Message.ToString());
                }
            }
        }
Exemplo n.º 26
0
        public async void OnNavigatedTo(NavigationParameters parameters)
        {
            if (parameters.ContainsKey("title"))
            {
                Title = (string)parameters["title"] + " and Prism";
            }

            try
            {
                // 取得這個應用程式的所在目錄
                IFolder rootFolder = FileSystem.Current.LocalStorage;
                // 取得要讀取資料的資料夾目錄
                IFolder sourceFolder = await rootFolder.GetFolderAsync("MyDatas");

                // 判斷這個資料夾內是否有這個檔案存在
                if (await sourceFolder.CheckExistsAsync("使用這登入資訊紀錄.dat") == ExistenceCheckResult.FileExists)
                {
                    // 開啟這個檔案
                    IFile sourceFile = await sourceFolder.GetFileAsync("使用這登入資訊紀錄.dat");

                    // 將檔案內的文字都讀出來
                    string foo使用這登入資訊紀錄 = await sourceFile.ReadAllTextAsync();

                    // 將 Json 文字反序列會成為 .NET 物件
                    var bar使用這登入資訊紀錄 = JsonConvert.DeserializeObject <使用這登入資訊>(foo使用這登入資訊紀錄);

                    // 將讀出的物件,設定到檢視模型內的屬性上
                    YourName     = bar使用這登入資訊紀錄.姓名;
                    YourPassword = bar使用這登入資訊紀錄.密碼;
                    YourAccount  = bar使用這登入資訊紀錄.帳號;
                }
            }
            catch { }
        }
Exemplo n.º 27
0
        public static async Task GetSchedule()
        {
            folder = await FileSystem.Current.LocalStorage.CreateFolderAsync("Schedule", CreationCollisionOption.OpenIfExists);

            path = folder.Path;
            try
            {
                if (url != null && url != "")
                {
                    var webClient = new WebClient();
                    webClient.DownloadFile(new Uri(url), PortablePath.Combine(path, file));
                }
                else
                {
                    DependencyService.Get <IMessage>().ShortAlert("Нет URL.");
                }
            }
            catch (Exception)
            {
                DependencyService.Get <IMessage>().ShortAlert("Нет интернета.");
            }
            finally
            {
                var check = await folder.CheckExistsAsync(file);

                if (check == ExistenceCheckResult.FileExists)
                {
                    ReadFile();
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Create a folder from the full folder path if it does not exist
        /// Throws exception if acess to the path is denied
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        private static async Task CreateFolderRecursive(string folderPath)
        {
            string[] segments = new Uri(folderPath).Segments;

            string path = segments[0];

            for (int i = 0; i < segments.Length - 1; i++)
            {
                try
                {
#if __DROID__ || __IOS__
                    IFolder folder = await FileSystem.Current.GetFolderFromPathAsync(path, CancellationToken.None);
#else
                    IFolder folder = await FileSystem.Current.GetFolderFromPathAsync(path.Replace('/', '\\'), CancellationToken.None);
#endif
                    var res = await folder.CheckExistsAsync(segments[i + 1]);

                    if (res != ExistenceCheckResult.FolderExists)
                    {
                        await folder.CreateFolderAsync(segments[i + 1], CreationCollisionOption.OpenIfExists);
                    }
                }
                catch (Exception)
                {
                    // ignore
                }

                path = Path.Combine(path, segments[i + 1]);
            }
        }
Exemplo n.º 29
0
        public void DeleteJob(object sender, EventArgs args)
        {
            IFolder root = PCLStorage.FileSystem.Current.LocalStorage;

            var check = root.CheckExistsAsync("jobs.txt");

            if (check.Result == ExistenceCheckResult.NotFound)
            {
                Console.WriteLine($"Check: {check.Result}");
            }
            else
            {
                var      file    = root.GetFileAsync("jobs.txt");
                string   ids     = (file.Result.ReadAllTextAsync()).Result;
                string[] id      = ids.Split(';');
                string   new_ids = "";
                foreach (string i in id)
                {
                    if (!i.Equals(gid))
                    {
                        new_ids += i + ";";
                    }
                }
                file.Result.WriteAllTextAsync(new_ids);

                DeleteJob();
            }
        }
Exemplo n.º 30
0
        public static async Task <bool> Exists()
        {
            IFolder rootFolder = FileSystem.Current.LocalStorage;
            var     exists     = await rootFolder.CheckExistsAsync(CERT_FILE);

            return(exists == ExistenceCheckResult.FileExists);
        }
Exemplo n.º 31
0
 private static async Task<bool> FileExists(IFolder folder, String fileName)
 {
     var existStatus = await folder.CheckExistsAsync(fileName);
     return existStatus != ExistenceCheckResult.NotFound;
 }