コード例 #1
0
ファイル: App.xaml.cs プロジェクト: toraidl/JPDict
        private async void CopyMainDb()
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            if (await storageFolder.TryGetItemAsync("kanji.db") == null)
            {
                var kanjifile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///kanji.db"));

                await kanjifile.CopyAsync(storageFolder, "kanji.db", NameCollisionOption.ReplaceExisting);
            }
            if (await storageFolder.TryGetItemAsync("kanjirad.db") == null)
            {
                var kanjifile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///kanjirad.db"));

                await kanjifile.CopyAsync(storageFolder, "kanjirad.db", NameCollisionOption.ReplaceExisting);
            }
        }
コード例 #2
0
        public async Task <bool> CacheExist(string filename)
        {
            try
            {
                var f = await _local_folder.TryGetItemAsync("images_cache");

                if (f != null)
                {
                    var f2 = await(f as StorageFolder).TryGetItemAsync(filename);
                    if (f2 == null)
                    {
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
コード例 #3
0
ファイル: Crypto.cs プロジェクト: chriskmps/SecureChat
        //Initialize the new Crypto object (initialized only once per app startup)
        public async void initCrypto()
        {
            this.strAsymmetricAlgName = AsymmetricAlgorithmNames.RsaPkcs1;
            this.asymmetricKeyLength  = 512;

            //Checks SecureChat's folder if a key pair already exists and set keyPairExists boolean
            Windows.Storage.StorageFolder localAppFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            string cryptoFilePrivate = "SecureChatPrivateKeys.sckey";  //STORED AS BYTE DATA
            string cryptoFilePublic  = "SecureChatPublicKey.sckey";    //STORED AS TEXT DATA

            if ((await localAppFolder.TryGetItemAsync(cryptoFilePublic) != null) && (await localAppFolder.TryGetItemAsync(cryptoFilePrivate) != null))
            {
                this.keyPairExists = true;
            }
            else
            {
                this.keyPairExists = false;
            }
            //Load Keys depending on keyPairExists value
            if (this.keyPairExists == true)
            {
                //DIRECT IBUFFER
                //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic);
                //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic);

                //FROM BYTE
                //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync("BytePubKey.sckey");
                //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic);

                //Open Public Key File.  Convert key from STRING to BYTE and then convert to IBUFFER
                StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic);

                String publicKeyStringVersion = await FileIO.ReadTextAsync(loadedCryptoFilePublic);

                this.publicKeyByteVersion = Convert.FromBase64String(publicKeyStringVersion);
                this.buffPublicKey        = this.publicKeyByteVersion.AsBuffer();

                //Open Private Key File
                StorageFile loadedCryptoFilePrivate = await localAppFolder.GetFileAsync(cryptoFilePrivate);

                this.buffPrivateKeyStorage = await FileIO.ReadBufferAsync(loadedCryptoFilePrivate);
            }
            else
            {
                //Generate new key pair
                CryptographicKey temp = this.CreateAsymmetricKeyPair(strAsymmetricAlgName, asymmetricKeyLength, out buffPublicKey, out buffPrivateKeyStorage);

                //Convert public key from IBUFFER type to BYTE type.  Convert from BYTE type to STRING type
                WindowsRuntimeBufferExtensions.CopyTo(this.buffPublicKey, this.publicKeyByteVersion);
                string publicKeyStringVersion = Convert.ToBase64String(this.publicKeyByteVersion);

                //Store keys in appropriate files (Public as PLAIN TEXT, Private as IBUFFER)
                await FileIO.WriteTextAsync((await localAppFolder.CreateFileAsync(cryptoFilePublic)), publicKeyStringVersion);

                await FileIO.WriteBufferAsync((await localAppFolder.CreateFileAsync(cryptoFilePrivate)), this.buffPrivateKeyStorage);
            }
        }
コード例 #4
0
        private async Task CopyMainDb()
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///data.db"));

            if (await storageFolder.TryGetItemAsync("data.db") == null)
            {
                await file.CopyAsync(storageFolder, "data.db");
            }
        }
コード例 #5
0
ファイル: FileUpStream.cs プロジェクト: lefoz/Martj14UWP
        public async Task <bool> isFilePresent(int stage)
        {
            switch (stage)
            {
            case 0:
                var subFile = await _storageFolder.TryGetItemAsync(_submissionsFileName);

                return(subFile != null);

            case 1:
                var serialFile = await _storageFolder.TryGetItemAsync(_serielNumberFileName);

                return(serialFile != null);

            case 2:
                var loginFile = await _storageFolder.TryGetItemAsync(_loginsFileName);

                return(loginFile != null);

            default:
                return(false);
            }
        }
コード例 #6
0
ファイル: MainPage.xaml.cs プロジェクト: Tinh77/asm_c-
        private async void CheckAuthentication()
        {
            // trường hợp chưa có token key trong hệ thống.
            if (Service.ApiHandle.TOKEN_STRING == null)
            {
                // Lấy token từ trong file.
                if (await folder.TryGetItemAsync("token.txt") != null)
                {
                    try
                    {
                        Windows.Storage.StorageFile file = await folder.GetFileAsync("token.txt");

                        string fileContent = await Windows.Storage.FileIO.ReadTextAsync(file);

                        TokenResponse token = JsonConvert.DeserializeObject <TokenResponse>(fileContent);
                        Service.ApiHandle.TOKEN_STRING = token.token;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                }
            }
            // Check tính hợp lệ của token của api.
            if (Service.ApiHandle.TOKEN_STRING != null)
            {
                if (await Service.ApiHandle.GetInformation())
                {
                    isLogged = true;
                    var frame       = Window.Current.Content as Frame;
                    var currentPage = frame.Content as Page;
                    var btnLogin    = currentPage.FindName("LoginBtn") as RadioButton;
                    btnLogin.Visibility = Visibility.Collapsed;
                    var dialog = new Windows.UI.Popups.MessageDialog("Welcome to our app!");
                    dialog.Commands.Add(new Windows.UI.Popups.UICommand("Closed")
                    {
                        Id = 1
                    });
                    dialog.CancelCommandIndex = 1;
                    await dialog.ShowAsync();
                }
            }

            if (!isLogged)
            {
                Login login = new Login();
                await login.ShowAsync();
            }
        }
コード例 #7
0
ファイル: InkUtils.cs プロジェクト: teamneusta/Template10
 public async static Task LoadAsync(this InkCanvas inkCanvas, string fileName, StorageFolder folder = null)
 {
     folder = folder ?? ApplicationData.Current.TemporaryFolder;
     var file = await folder.TryGetItemAsync(fileName) as StorageFile;
     if (file != null)
     {
         try
         {
             using (var stream = await file.OpenSequentialReadAsync())
             {
                 await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);
             }
         }
         catch { }
     }
 }
コード例 #8
0
        private async Task <bool> DoesDbExist(string DatabaseName)
        {
            bool dbexist = true;
            var  file    = await localFolder.TryGetItemAsync(_dbName) as IStorageFile;


            if (file != null)
            {
                dbexist = true; // The file exists, "file" variable contains a reference to it.
            }
            else
            {
                dbexist = false; // The file doesn't exist.
            }

            return(dbexist);
        }
コード例 #9
0
ファイル: FileUtils.cs プロジェクト: hubaishan/quran-phone
        /// <summary>
        /// Deletes folder even if it contains read only files
        /// </summary>
        /// <param name="path"></param>
        public async static Task<bool> DeleteFolder(StorageFolder baseDir, string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return false;
            }

            var folder = await baseDir.TryGetItemAsync(path) as StorageFolder;
            if (folder == null)
            {
                return false;
            }

            foreach (var file in await folder.GetFilesAsync())
            {
                await SafeFileDelete(file.Path);
            }
            await folder.DeleteAsync();
            return true;
        }
コード例 #10
0
        private async Task InitalizeCamStoreAsync()
        {
            Windows.Storage.ApplicationDataContainer localSettings =
                Windows.Storage.ApplicationData.Current.LocalSettings;

            if (localSettings.Values["SmartCard"] == null ||
                (string)localSettings.Values["SmartCard"] == "" ||
                localSettings.Values["PredictionKey"] == null ||
                (string)localSettings.Values["PredictionKey"] == "" ||
                localSettings.Values["PredictionUri"] == null ||
                (string)localSettings.Values["PredictionUri"] == "")
            {
                DisplayNoConfigAsync();
            }
            try
            {
                await InitalizeCamera();
            }
            catch (CameraInUseException cex)
            {
                // Warn about camera already in use
                await DisplayCameraInUseAsync();

                Application.Current.Exit();
            }

            var task      = Task.Run <IStorageItem>(async() => { return(await AppLocalFolder.TryGetItemAsync("store.json")); });
            var storeFile = task.Result;

            if (storeFile != null)
            {
                this.LoadStoreAsync();
            }
            else
            {
                this.Store = new Store()
                {
                    Name = "Store-In-A-Box Prototype"
                };
            }
        }
コード例 #11
0
 public static async Task <bool> ContainsFolderAsync(this StorageFolder storageFolder, string folderName) => null != await storageFolder.TryGetItemAsync(folderName) as StorageFolder;
コード例 #12
0
 public static async Task <bool> ContainsItemAsync(this StorageFolder storageFolder, string name) => null != await storageFolder.TryGetItemAsync(name);
コード例 #13
0
 private static async Task<StorageFolder> _GetFolderAsync(string name, StorageFolder parent)
 {
     var item = await parent.TryGetItemAsync(name).AsTask().ConfigureAwait(false);
     return item as StorageFolder;
 }
コード例 #14
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Tot.Text = "";
            Vot.Text = "";
            Button button = sender as Button;

            button.IsEnabled = false;
            StorageFolder vere = imagefolder;
            StorageFolder hore = imagefolder;

            if (imgfiles == null)
            {
                return;
            }
            //Tot.Text = imagefile.Path;
            Tot.Text = imagefile.FileType;
            //若存在则获取,不存在则新建
            if (null == await imagefolder.TryGetItemAsync("Hor"))
            {
                hore = await imagefolder.CreateFolderAsync("Hor");
            }
            hore = await imagefolder.GetFolderAsync("Hor");

            if (await imagefolder.TryGetItemAsync("Ver") == null)
            {
                vere = await imagefolder.CreateFolderAsync("Ver");
            }
            vere = await imagefolder.GetFolderAsync("Ver");

            int    a = 0;
            int    b = 0;
            float  t = 0;
            float  p = 0;
            double c = 0;

            Tot.Text = a.ToString();
            Vot.Text = b.ToString();
            //Windows.Storage.StorageFolder imgfld = await imagefile.GetParentAsync();
            StorageApplicationPermissions.FutureAccessList.Add(imagefolder);
            IReadOnlyList <StorageFile> filelist = await imagefolder.GetFilesAsync();

            foreach (StorageFile file  in filelist)
            {
                progrb.Visibility = Visibility.Visible;
                p = filelist.Count;
                if (file.FileType == ".jpg" || file.FileType == ".png" || file.FileType == ".bmp")
                {
                    var varfil = await file.GetBasicPropertiesAsync();

                    if (varfil.Size == 0)
                    {
                        continue;
                    }
                    filename    = file.Name;
                    filename    = varfil.Size.ToString();
                    errtag.Text = filename;
                    ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();

                    if (imageProperties.Width >= imageProperties.Height)
                    {
                        if (await hore.TryGetItemAsync(file.Name) != null)
                        {
                            continue;
                        }
                        inputstream = await file.OpenReadAsync();

                        await horbitmap.SetSourceAsync(inputstream);

                        HorImagePlace.Source = horbitmap;
                        await file.CopyAsync(hore);

                        a++;
                    }
                    else
                    {
                        if (await vere.TryGetItemAsync(file.Name) != null)
                        {
                            continue;
                        }
                        inputstream = await file.OpenReadAsync();

                        await verbitmap.SetSourceAsync(inputstream);

                        VerImagePlace.Visibility = Visibility.Visible;
                        VerImagePlace.Source     = verbitmap;
                        await file.CopyAsync(vere);

                        b++;
                    }
                    Tot.Text = a.ToString();
                    Vot.Text = b.ToString();
                }
                Tot.Text        += " Hor Pictures Copyed";
                Vot.Text        += " Ver Pictures Copyed";
                button.IsEnabled = true;
                btnOpn.IsEnabled = true;
                t++;
                c            = t / p;
                progrb.Value = c * 100;
            }
            StorageApplicationPermissions.FutureAccessList.Clear();
        }
コード例 #15
0
ファイル: StorageHelper.cs プロジェクト: haroldma/Audiotica
        public static async Task<StorageFile> GetIfFileExistsAsync(string path, StorageFolder folder)
        {
            var parts = path.Split('/');

            var fileName = parts.Last();

            if (parts.Length > 1)
            {
                folder =
                    await GetFolderAsync(path.Substring(0, path.Length - fileName.Length), folder).ConfigureAwait(false);
            }

            if (folder == null)
            {
                return null;
            }
            return await folder.TryGetItemAsync(fileName).AsTask().DontMarshall() as StorageFile;
        }
コード例 #16
0
ファイル: FileUtils.cs プロジェクト: hubaishan/quran-phone
        public static async Task<bool> FileExists(StorageFolder baseFolder, string fileName)
        {
            if (baseFolder == null || string.IsNullOrWhiteSpace(fileName))
            {
                return false;
            }

            try
            {
                var storageItem = await baseFolder.TryGetItemAsync(fileName);
                return storageItem != null && storageItem.IsOfType(StorageItemTypes.File);
            }
            catch (Exception)
            {
                return false;
            }
        }
コード例 #17
0
 /// <summary>
 /// Try get folder with given <paramref name="name"/> in <paramref name="folder"/>.
 /// </summary>
 /// <param name="folder">Folder of folder.</param>
 /// <param name="name">Name of folder.</param>
 /// <returns>The folder, or <see langword="null"/>, if not found.</returns>
 public static IAsyncOperation <StorageFolder> TryGetFolderAsync(this StorageFolder folder, string name)
 {
     return(Run(async token => await folder.TryGetItemAsync(name) as StorageFolder));
 }
コード例 #18
0
 private static async Task<bool> FileDoesNotExistAsync(string fileName, StorageFolder imagesFolder)
 {
     return await imagesFolder.TryGetItemAsync(fileName) == null;
 }
コード例 #19
0
 public async Task<bool> IfStorageItemExist(StorageFolder folder, string itemName)
 {
     try
     {
         IStorageItem item = await folder.TryGetItemAsync(itemName);
         return (item != null);
     }
     catch (Exception)
     {
         // Should never get here 
         return false;
     }
 } 
コード例 #20
0
ファイル: FileUtils.cs プロジェクト: hubaishan/quran-phone
 public static async Task<bool> DirectoryExists(StorageFolder baseDir, string path)
 {
     try
     {
         return (await baseDir.TryGetItemAsync(path)) != null;
     }
     catch (FileNotFoundException)
     {
         return false;
     }
 }
コード例 #21
0
ファイル: FileUtils.cs プロジェクト: hubaishan/quran-phone
        public static async Task<StorageFile> GetFile(StorageFolder folder, string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return null;
            }

            try
            {
                return await folder.TryGetItemAsync(Path.GetFileName(path)) as StorageFile;
            }
            catch (Exception)
            {
                return null;
            }
        }
コード例 #22
0
 public static async Task <bool> ContainsFileAsync(this StorageFolder storageFolder, string fileName) => null != (await storageFolder.TryGetItemAsync(fileName)) as StorageFile;
コード例 #23
0
		private async Task ContinueAfterExportBinderPickerAsync(StorageFolder toDir, string dbName, Briefcase bc)
		{
			bool isExported = false;
			try
			{
				if (bc != null && toDir != null)
				{
					_animationStarter.StartAnimation(AnimationStarter.Animations.Updating);

					if (string.IsNullOrWhiteSpace(dbName) /*|| _dbNames?.Contains(dbName) == false */|| toDir == null) return;

					var fromDirectory = await Briefcase.BindersDirectory
						.GetFolderAsync(dbName)
						.AsTask().ConfigureAwait(false);
					if (fromDirectory == null) return;
					// what if you copy a directory to an existing one? Shouldn't you delete the contents first? No! But then, shouldn't you issue a warning?
					var toDirectoryTest = await toDir.TryGetItemAsync(dbName).AsTask().ConfigureAwait(false);
					if (toDirectoryTest != null)
					{
						var confirmation =
							await UserConfirmationPopup.GetInstance().GetUserConfirmationBeforeExportingBinderAsync(CancToken).ConfigureAwait(false);
						if (CancToken.IsCancellationRequested) return;
						if (confirmation == null || confirmation.Item1 == false || confirmation.Item2 == false) return;
					}

					isExported = await bc.ExportBinderAsync(dbName, fromDirectory, toDir).ConfigureAwait(false);
				}
			}
			catch (Exception ex)
			{
				await Logger.AddAsync(ex.ToString(), Logger.FileErrorLogFilename, Logger.Severity.Info).ConfigureAwait(false);
			}
			finally
			{
				_animationStarter.EndAllAnimations();
				if (!CancToken.IsCancellationRequested)
					_animationStarter.StartAnimation(isExported
						? AnimationStarter.Animations.Success
						: AnimationStarter.Animations.Failure);

				IsExportingBinder = false;
			}
		}
コード例 #24
0
       private async void OpenComicCollection(StorageFolder chosenFolder, StorageFolder collections)
       {
           LoadingGridVisible(true);
           List<StorageFile> files = await RecursivelySearchForFiles(chosenFolder);
           StorageFolder collectionFolder = (StorageFolder)await collections.TryGetItemAsync(chosenFolder.Name);
           if (collectionFolder == null)
           {
               collectionFolder = await collections.CreateFolderAsync(chosenFolder.Name);
           }
           else
           {
               ShowWarning("Collection already exist!", "Adding new comics");
           }

           foreach (StorageFile sourceFile in files)
           {
               StorageFolder destFolder = (StorageFolder)await collectionFolder.TryGetItemAsync(sourceFile.Name);
               if (destFolder == null)
               {
                   destFolder = await collectionFolder.CreateFolderAsync(sourceFile.Name);
                   try
                   {
                       DefaultViewModel["LoadingFile"] = sourceFile.Name;
                       if (sourceFile.FileType.Equals("cbz") || sourceFile.FileType.Equals(".cbz"))
                           await FolderZip.UnZipFile(sourceFile, destFolder);
                       else if (sourceFile.FileType.Equals("cbr") || sourceFile.FileType.Equals(".cbr"))
                           await FolderZip.UnRarFile(sourceFile, destFolder);
                   }
                   catch (InvalidFormatException exception)
                   {
                       ShowWarning("Error opening file:" + sourceFile.Name, "Please try again");
                   }
               }
               LoadingBar.Value += (1.0 / files.Count()) * 100;
           }

           await CreateCollectionTiles();
           CollectionViews.Clear();
           foreach (CollectionTile tile in CollectionTiles)
           {
               CollectionViews.Add(new CollectionView(tile));
           }
           defaultViewModel["ComicTiles"] = ComicTiles;
           defaultViewModel["CollectionViews"] = CollectionViews;
           LoadingGridVisible(false);
       }
コード例 #25
0
ファイル: StorageHelper.cs プロジェクト: haroldma/Audiotica
 private static async Task<StorageFolder> _GetFolderAsync(string name, StorageFolder parent)
 {
     var item = await parent.TryGetItemAsync(name).AsTask().DontMarshall();
     return item as StorageFolder;
 }
コード例 #26
0
ファイル: DeviceManager.cs プロジェクト: jessupjn/CPRemote
        //Initialize "devices" list and Channel and volumeDevices
        public async Task initialize(StorageFolder devices_folder_)
        {
            is_initialized = true;
            // Device Manager Metadata Initialization 
            devices_folder = devices_folder_;
            devices_info_file = (StorageFile) await devices_folder.TryGetItemAsync("devices_info.txt");
            if(devices_info_file == null)
            {
                System.Diagnostics.Debug.WriteLine("No Devices info file!");
                return;
            }
            IList<string> input = await FileIO.ReadLinesAsync(devices_info_file);
            int num_channel_devices = Convert.ToInt32(input[0]);
            int cur_index = 1;
            String device_name;
            StorageFile cur_device_input_file;

            // Channel Device Initialization

            for(int i = 0; i < num_channel_devices; ++i)
            {
                device_name = input[cur_index++];
                try
                {
                    cur_device_input_file = (StorageFile)await get_input_file_from_name(device_name, 'c');
                    ChannelDevice c_device = new ChannelDevice(device_name, cur_device_input_file);
                    channel_devices.Add(c_device);
                }
                catch(Exception except)
                {
                    System.Diagnostics.Debug.WriteLine(except.Message);
                }
            }
            // Get Current Channel Device
            int chan_index = 0;
            bool found = false;
            string cur_chan_device_name = input[cur_index++];
            foreach(ChannelDevice cur in channel_devices)
            {
                if(cur.get_name().Equals(cur_chan_device_name))
                {
                    found = true;
                    break;
                }
                chan_index++;
            }
            if (!found)
            {
                // Throw Exception about channel device not found
            }
            else
            {
                channelController = channel_devices[chan_index];
                await channelController.initialize();
            }

            // Volume Device Initialization

            int num_vol_devices = Convert.ToInt32(input[cur_index++]);
            for(int i = 0; i < num_vol_devices; ++i)
            {
                device_name = input[cur_index++];
                cur_device_input_file = await get_input_file_from_name(device_name, 'v');
                VolumeDevice v_device = new VolumeDevice(device_name, cur_device_input_file);
                volume_devices.Add(v_device);
            }
            int vol_index = 0;
            string cur_vol_device_name = input[cur_index++];
            found = false;
            foreach(VolumeDevice cur_v in volume_devices)
            {
                if(cur_v.get_name().Equals(cur_vol_device_name))
                {
                    found = true;
                    break;
                }
                vol_index++;
            }
            if(!found)
            {
                // TODO: Throw Error
            }
            else
            {
                volumeController = volume_devices[vol_index];
                await volumeController.initialize();
            }
      
        }
コード例 #27
0
 /// <summary> 
 /// It checks if the specified folder exists. 
 /// </summary> 
 /// <param name="storageFolder">The container folder</param> 
 /// <param name="subFolderName">The sub folder name</param> 
 /// <returns></returns> 
 private static async Task<bool> IfFolderExistsAsync(StorageFolder storageFolder, string subFolderName)
 {
     var storageItem = await storageFolder.TryGetItemAsync(subFolderName);
     return storageItem != null && storageItem.IsOfType(StorageItemTypes.Folder);
 }