示例#1
0
        /// <summary>
        /// In-built function to download image.
        /// </summary>
        public async Task DownloadImage()
        {
            var savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            savePicker.SuggestedFileName      = GenerateImageName();

            savePicker.FileTypeChoices.Add("Image", new List <string>()
            {
                ".jpg", ".jpeg", ".png"
            });

            var file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);

                HttpClient client = new HttpClient();
                byte[]     buffer = await client.GetByteArrayAsync(new Uri(image_url));

                using (Stream stream = await file.OpenStreamForWriteAsync())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }

                await CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
示例#2
0
        /// <summary>
        /// Handle the returned file from file picker
        /// This method is triggered by ContinuationManager based on ActivationKind
        /// </summary>
        /// <param name="args">File save picker continuation activation argment. It cantains the file user selected with file save picker </param>
        public async void ContinueFileSavePicker(FileSavePickerContinuationEventArgs args)
        {
            StorageFile file = args.File;

            if (file != null)
            {
                // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);
                // write to file
                await FileIO.WriteTextAsync(file, file.Name);

                // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    OutputTextBlock.Text = "File " + file.Name + " was saved.";
                }
                else
                {
                    OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
                }
            }
            else
            {
                OutputTextBlock.Text = "Operation cancelled.";
            }
        }
示例#3
0
        public async Task <bool> getJPG(StorageFile sFile, UIElement Source)
        {
            try
            {
                CachedFileManager.DeferUpdates(sFile);
                //把控件变成图像
                RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
                //传入参数Image控件
                await renderTargetBitmap.RenderAsync(Source);

                var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                    encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Ignore,
                        (uint)renderTargetBitmap.PixelWidth,
                        (uint)renderTargetBitmap.PixelHeight,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                        pixelBuffer.ToArray());
                    //刷新图像
                    await encoder.FlushAsync();
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
    public async void Save(RichEditBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker();
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Rich Text", new List <string>()
            {
                ".rtf"
            });
            picker.DefaultFileExtension = ".rtf";
            picker.SuggestedFileName    = "Document";
            StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteTextAsync(file, get(ref display));

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
        catch
        {
        }
    }
示例#5
0
        private async void ExportCommandCommandHandler()
        {
            var downloadData = await _statisticsRepository.GetAllForDownload();

            var picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
            };

            picker.FileTypeChoices.Add("CSV", new List <string> {
                ".csv"
            });
            picker.SuggestedFileName = "DartsScoreMasterStats";

            var file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);

                await FileIO.WriteTextAsync(file, downloadData);

                var status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status != FileUpdateStatus.Complete)
                {
                    throw new Exception($"File could not be saved, status was {status}.");
                }
            }
        }
        private async void WriteFileButton_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(fileToken))
            {
                StorageFile file = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);

                // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);
                // write to file
                await FileIO.AppendTextAsync(file, String.Format(@"{0}Text Added @ {1}.", System.Environment.NewLine, DateTime.Now.ToString()));

                // Let Windows know that we're finished changing the file so the server app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                switch (status)
                {
                case FileUpdateStatus.Complete:
                    MainPage.Current.NotifyUser("File " + file.Name + " was saved.", NotifyType.StatusMessage);
                    OutputFileAsync(file);
                    break;

                case FileUpdateStatus.CompleteAndRenamed:
                    MainPage.Current.NotifyUser("File " + file.Name + " was renamed and saved.", NotifyType.StatusMessage);
                    Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace(fileToken, file);
                    OutputFileAsync(file);
                    break;

                default:
                    MainPage.Current.NotifyUser("File " + file.Name + " couldn't be saved.", NotifyType.StatusMessage);
                    break;
                }
            }
        }
示例#7
0
        private async void WriteToFileWithExplicitCFUButton_Click(Object sender, RoutedEventArgs e)
        {
            StorageFile file = m_afterWriteFile;

            CachedFileManager.DeferUpdates(file);
            await FileIO.WriteTextAsync(file, "The File Picker App just wrote to the file!");

            rootPage.NotifyUser("File write complete. Explicitly completing updates.", NotifyType.StatusMessage);
            FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

            switch (status)
            {
            case FileUpdateStatus.Complete:
                rootPage.NotifyUser($"File {file.Name} was saved.", NotifyType.StatusMessage);
                break;

            case FileUpdateStatus.CompleteAndRenamed:
                rootPage.NotifyUser($"File ${file.Name} was renamed and saved.", NotifyType.StatusMessage);
                break;

            default:
                rootPage.NotifyUser($"File ${file.Name} couldn't be saved.", NotifyType.ErrorMessage);
                break;
            }
        }
        private async Task <bool> UploadFile(IStorageFile localFile, string path)
        {
            var result = false;
            var cts    = new CancellationTokenSource();

            CachedFileManager.DeferUpdates(localFile);
            try
            {
                using (var stream = await localFile.OpenAsync(FileAccessMode.Read))
                {
                    var targetStream = stream.AsStreamForRead();

                    IProgress <WebDavProgress> progress = new Progress <WebDavProgress>(ProgressHandler);
                    result = await _client.Upload(path, targetStream, localFile.ContentType, progress, cts.Token);
                }
            }
            catch (ResponseError e2)
            {
                ResponseErrorHandlerService.HandleException(e2);
            }

            // Let Windows know that we're finished changing the file so
            // the other app can update the remote version of the file.
            // Completing updates may require Windows to ask for user input.
            await CachedFileManager.CompleteUpdatesAsync(localFile);

            return(result);
        }
示例#9
0
        private async Task Continue(FilePickTargets target,
                                    IStorageFile read, IStorageFile write = null)
        {
            switch (target)
            {
            case FilePickTargets.Databases:
                await _registration.RegisterAsync(read);

                break;

            case FilePickTargets.KeyFile:
                var view = _rootFrame.Content as FrameworkElement;
                if (view == null)
                {
                    break;
                }

                var viewModel = view.DataContext as PasswordViewModel;
                if (viewModel != null)
                {
                    await viewModel.AddKeyFile(read);
                }
                break;

            case FilePickTargets.Attachments:
                CachedFileManager.DeferUpdates(write);
                await read.CopyAndReplaceAsync(write);

                await CachedFileManager.CompleteUpdatesAsync(write);

                break;
            }
        }
示例#10
0
        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (imgs == null)
            {
                return;
            }
            if (imgs[index].ImageBytes == null)
            {
                return;
            }
            var bytes = imgs[index].ImageBytes;

            FileSavePicker save = new FileSavePicker();

            save.SuggestedStartLocation = PickerLocationId.PicturesLibrary;



            save.FileTypeChoices.Add("图片", new List <string>()
            {
                Path.GetExtension(imgs[index].ImageUrl)
            });
            save.SuggestedFileName = "bili_img_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            StorageFile file = await save.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteBytesAsync(file, bytes);

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                Utils.ShowMessageToast("保存成功");
            }
        }
示例#11
0
        private async Task MakeEmoji()
        {
            var local  = ApplicationData.Current.LocalFolder;
            var folder = await local.CreateFolderAsync("斗图", CreationCollisionOption.OpenIfExists);

            var sFile = await folder.CreateFileAsync("temp" + ".png", CreationCollisionOption.ReplaceExisting);

            CachedFileManager.DeferUpdates(sFile);
            //把控件变成图像
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            //传入参数Image控件
            await renderTargetBitmap.RenderAsync(pictureRoot);

            var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

            using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    (uint)renderTargetBitmap.PixelWidth,
                    (uint)renderTargetBitmap.PixelHeight,
                    DisplayInformation.GetForCurrentView().LogicalDpi,
                    DisplayInformation.GetForCurrentView().LogicalDpi,
                    pixelBuffer.ToArray());
                //刷新图像
                await encoder.FlushAsync();
            }
            CurrentFile = sFile;
        }
示例#12
0
        private async void ExportAllBtn_Click(object sender, RoutedEventArgs e)
        {
            var savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("json", new List <string>()
            {
                ".json"
            });
            savePicker.SuggestedFileName = "IoT_Devices";

            var file = await savePicker.PickSaveFileAsync();

            if (file is null)
            {
                return;
            }

            // Prevent updates to the remote version of the file until
            // we finish making changes and call CompleteUpdatesAsync.
            CachedFileManager.DeferUpdates(file);

            await FileIO.WriteTextAsync(file, JsonConvert.SerializeObject(Devices));

            await CachedFileManager.CompleteUpdatesAsync(file);

            _logger.LogInformation($"Successfully exported your devices to {file.Name}.");
        }
        public async Task <bool> SaveBitmap(byte[] bitmapData, string filename)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            savePicker.FileTypeChoices.Add("PNG", new List <string>()
            {
                ".png"
            });
            savePicker.FileTypeChoices.Add("JPEG", new List <string>()
            {
                ".jpeg"
            });
            savePicker.FileTypeChoices.Add("GIF", new List <string>()
            {
                ".gif"
            });
            savePicker.SuggestedFileName = filename;
            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.Read);

                await FileIO.WriteBytesAsync(file, bitmapData);

                Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                return(true);
            }
            return(false);
        }
示例#14
0
    public async void Save(ListBox display)
    {
        try
        {
            XElement items = new XElement("tasklist");
            foreach (CheckBox item in display.Items)
            {
                items.Add(new XElement("task", item.Content, new XAttribute("value",
                                                                            ((bool)item.IsChecked ? "checked" : "unchecked"))));
            }
            string         value  = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), items).ToString();
            FileSavePicker picker = new FileSavePicker();
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Task List", new List <string>()
            {
                ".tsk"
            });
            picker.DefaultFileExtension = ".tsk";
            picker.SuggestedFileName    = "Document";
            StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteTextAsync(file, value);

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
        catch
        {
        }
    }
示例#15
0
        private async void saveFileAsync(object sender, RoutedEventArgs e)
        {
            FileSavePicker picker = new FileSavePicker();

            picker.FileTypeChoices.Add("Plain Text", new List <string>()
            {
                ".txt"
            });
            picker.SuggestedFileName      = "Nowy Dokument";
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

            StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteTextAsync(file, string.Join(Environment.NewLine, matrixToCalc.getAsText()));

                await FileIO.AppendTextAsync(file, Environment.NewLine + capacityTextBox.Text);
            }
            else
            {
                ContentDialog dialog = new ContentDialog {
                    Title = "Information", Content = "Nie wybrano pliku", CloseButtonText = "ok"
                };
                ContentDialogResult result = await dialog.ShowAsync();
            }
        }
示例#16
0
        private async void btn_SaveImage_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker save = new FileSavePicker();

            save.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            save.FileTypeChoices.Add("图片", new List <string>()
            {
                ".jpg"
            });
            save.SuggestedFileName = "bili_img_" + _aid;
            StorageFile file = await save.PickSaveFileAsync();

            if (file != null)
            {
                //img_Image
                IBuffer bu = await WebClientClass.GetBuffer(new Uri((this.DataContext as VideoInfoModels).pic));

                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteBufferAsync(file, bu);

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                Utils.ShowMessageToast("保存成功", 3000);
            }
        }
示例#17
0
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            var mru = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;

            if (mruToken != null || mruToken != "")
            {
                StorageFile file = await mru.GetFileAsync(mruToken);

                if (file != null)
                {
                    using (Stream fs = await file.OpenStreamForWriteAsync())
                    {
                        fs.SetLength(0);
                        CachedFileManager.DeferUpdates(file);
                        Serializer.Serialize(fs, contacts);
                    }
                }
                else
                {
                    SaveAsButton_Click(sender, e);
                }
            }
            else
            {
                SaveAsButton_Click(sender, e);
            }
        }
        private async Task SaveNewFileAsync()
        {
            var savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("Adaptive Card JSON", new List <string>()
            {
                ".json"
            });
            savePicker.SuggestedFileName = "NewAdaptiveCard.json";

            File = await savePicker.PickSaveFileAsync();

            if (File != null)
            {
                CachedFileManager.DeferUpdates(File);
                await FileIO.WriteTextAsync(File, File.Name);

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(File);

                if (status == FileUpdateStatus.Complete)
                {
                    this.Name = File.Name;
                }
                else
                {
                    CreateMessageDialog("File " + File.Name + " couldn't be saved");
                }
            }
        }
示例#19
0
        /// <summary>
        /// Serialize devices list to file
        /// </summary>
        /// <param name="file">StorageFile item where JSON will write</param>
        /// <returns>True if export was ok, false otherwise</returns>
        private async Task <bool> SaveFileConfiguration(StorageFile file)
        {
            var dbContent = JsonConvert.SerializeObject(this.Devices);

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteTextAsync(file, dbContent);

                Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status != Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    var dialog = new MessageDialog(string.Format(this.Loader.GetString("ErrorCannotSaveFile"), file.Name), this.Loader.GetString("Error"));
                    dialog.Commands.Add(new UICommand("Ok")
                    {
                        Id = 0
                    });
                    dialog.DefaultCommandIndex = 0;
                    var result = await dialog.ShowAsync();

                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }
示例#20
0
        private async Task DownloadDataAndDisplayAsync(Uri dataUri)
        {
            try
            {
                HttpClient client   = new HttpClient();
                var        response = await client.GetAsync(dataUri);

                var zipStream = await response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync();

                var file = await SaveFileAsync(zipStream.AsRandomAccessStream());

                CachedFileManager.DeferUpdates(file);

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await zipStream.CopyToAsync(stream.AsStreamForWrite());
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
        }
示例#21
0
        /// <summary>
        /// Saves to CSV.
        /// </summary>
        /// <param name="weatherDataCollection">The weather data collection.</param>
        public static async void SaveToCsv(WeatherDataCollection weatherDataCollection)
        {
            var fileSaver = new FileSavePicker {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            fileSaver.FileTypeChoices.Add("CSV", new List <string> {
                ".csv"
            });

            var saveFile = await fileSaver.PickSaveFileAsync();

            if (saveFile != null)
            {
                CachedFileManager.DeferUpdates(saveFile);

                var dataForFile = new StringBuilder();
                foreach (var day in weatherDataCollection)
                {
                    dataForFile.Append($"{day.Date.ToShortDateString()},{day.High},{day.Low}{Environment.NewLine}");
                }

                await FileIO.WriteTextAsync(saveFile, dataForFile.ToString());
            }
        }
示例#22
0
        private async void savePacketButton_Click(object sender, RoutedEventArgs e)
        {
            var savePicker = new FileSavePicker();
            var packets    = receivedPacketsView.SelectedItems;

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Binary file", new List <string>()
            {
                ".bin"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "Packet" + receivedPacketsView.SelectedIndex;

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);
                var stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                // write to file
                using (var outputStream = stream.GetOutputStreamAt(0)) {
                    using (var dataWriter = new DataWriter(outputStream)) {
                        foreach (Packet packet in packets)
                        {
                            int    padding     = Constants.PAYLOADLEN - packet.payload.Length;
                            byte[] nullPadding = new byte[padding];
                            dataWriter.WriteBytes(packet.payload);
                            //dataWriter.WriteBytes(nullPadding);
                        }
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
                // Let Windows know that we're finished changing the file so
                // the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                Windows.Storage.Provider.FileUpdateStatus res =
                    await CachedFileManager.CompleteUpdatesAsync(file);

                if (res == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    status.Text = "File " + file.Name + " was saved.";
                }
                else
                {
                    status.Text = "File " + file.Name + " couldn't be saved.";
                }
            }
            else
            {
                status.Text = "Operation cancelled.";
            }
        }
示例#23
0
        private async void ExportButton_Click(object sender, RoutedEventArgs e)
        {
            mainPage.SetProgressRing(true);

            if (fromDatePicker.Date == null || toDatePicker.Date == null)
            {
                await Utility.ShowDialog("Date Not Selected", "You must enter a date into both From and To!");
            }
            else
            {
                from = fromDatePicker.Date.Value.Date;
                to   = toDatePicker.Date.Value.Date;

                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                // Dropdown of file types the user can save the file as
                savePicker.FileTypeChoices.Add("Comma Seperated Value", new List <string>()
                {
                    ".csv"
                });
                // Default file name if the user does not type one in or select a file to replace
                savePicker.SuggestedFileName = "New Document";

                file = await savePicker.PickSaveFileAsync();

                if (file != null)
                {
                    // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                    CachedFileManager.DeferUpdates(file);

                    //// write to file
                    //await FileIO.WriteTextAsync(file, file.Name);
                    //// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
                    //// Completing updates may require Windows to ask for user input.
                    //FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
                    //if (status == FileUpdateStatus.Complete)
                    //{
                    //    //File Update Complete
                    //}

                    switch (filterBox.SelectedIndex)
                    {
                    case 0:
                        ExportShifts();
                        break;

                    case 1:
                        ExportUsersHours();
                        break;

                    default:
                        Debug.WriteLine("Value not defined!");
                        break;
                    }
                }

                mainPage.SetProgressRing(false);
            }
        }
示例#24
0
        private async void ButtonSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (!this.TextBoxName.Text.Equals(string.Empty) && !this.TextBoxIp.Text.Equals(string.Empty) && !this.TextBoxPort.Equals(string.Empty))
            {
                // To catch Edit Mode
                if (this.ExistingDevice != null)
                {
                    Device deviceToDelete = this.Devices.Where(x => x.Name.Equals(this.ExistingDevice.Name) && x.IpAddress.Equals(this.ExistingDevice.IpAddress)).FirstOrDefault();
                    this.Devices.Remove(deviceToDelete);
                }

                Device newDevice = new Device();
                newDevice.Name      = this.TextBoxName.Text;
                newDevice.Location  = this.TextBoxLocation.Text;
                newDevice.IpAddress = this.TextBoxIp.Text;
                newDevice.Port      = this.TextBoxPort.Text;
                this.Devices.Add(newDevice);

                var dbContent = JsonConvert.SerializeObject(this.Devices);

                StorageFile file = await StorageFile.GetFileFromPathAsync(this.PathDbFile);

                if (file != null)
                {
                    CachedFileManager.DeferUpdates(file);
                    await FileIO.WriteTextAsync(file, dbContent);

                    Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    var dialog = new MessageDialog(this.ExistingDevice != null ? this.Loader.GetString("ConfirmationEditDevice") : this.Loader.GetString("ConfirmationAddDevice"));
                    if (status != Windows.Storage.Provider.FileUpdateStatus.Complete)
                    {
                        dialog.Content = this.Loader.GetString("ErrorCannotSave");
                        dialog.Title   = this.Loader.GetString("Error");
                    }
                    dialog.Commands.Add(new UICommand("Ok")
                    {
                        Id = 0
                    });
                    dialog.DefaultCommandIndex = 0;
                    var result = await dialog.ShowAsync();

                    this.Frame.Navigate(typeof(MainPage), null);
                }
            }
            else
            {
                var dialogError = new MessageDialog(this.Loader.GetString("RequiredFileds"));
                dialogError.Commands.Add(new UICommand("Ok")
                {
                    Id = 0
                });
                dialogError.DefaultCommandIndex = 0;
                await dialogError.ShowAsync();

                this.TextBoxName.Focus(FocusState.Programmatic);
                this.TextBoxName.SelectAll();
            }
        }
示例#25
0
        public async Task SaveJsonWithFilePicker(string RepeatTimes)
        {
            if (Controller.framesList.Count <= 0)
            {
                return;
            }

            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            savePicker.FileTypeChoices.Add("JSON File", new List <string>()
            {
                ".json"
            });
            savePicker.SuggestedFileName = "Frames";
            var file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                /*SERIALIZACAO MANUAL EM JSON*/
                try
                {
                    CachedFileManager.DeferUpdates(file); //Evita outros programas editarem o arquivo enquanto ele está sendo gravado
                    string repeatTimes = string.Format("{0:D5}", RepeatTimes);
                    await FileIO.WriteTextAsync(file, "{\"repeatTimes\":" + repeatTimes + ",\"moves\":[");

                    for (int i = 0; i < Controller.framesList.Count; i++) //salva os frames linha por linha
                    {
                        string garra = string.Format("{0:D3}", Controller.framesList[i][0]);
                        string axis4 = string.Format("{0:D3}", Controller.framesList[i][1]);
                        string axis3 = string.Format("{0:D3}", Controller.framesList[i][2]);
                        string axis2 = string.Format("{0:D3}", Controller.framesList[i][3]);
                        string axis1 = string.Format("{0:D3}", Controller.framesList[i][4]);
                        string speed = string.Format("{0:D3}", Controller.framesList[i][5]);
                        string delay = string.Format("{0:D6}", Controller.framesList[i][6]);

                        await FileIO.AppendTextAsync(file, "{\"garra\":\"" + garra + "\",\"axis4\":\"" + axis4 + "\",\"axis3\":\"" + axis3 + "\",\"axis2\":\"" + axis2 + "\",\"axis1\":\"" + axis1 + "\",\"speed\":\"" + speed + "\",\"delay\":\"" + delay + "\"}");

                        if (i != Controller.framesList.Count - 1)
                        {
                            await FileIO.AppendTextAsync(file, ",");
                        }
                    }

                    await FileIO.AppendTextAsync(file, "]}");

                    var status = await CachedFileManager.CompleteUpdatesAsync(file);

                    /*FIM DA SERIALIZACAO MANUAL*/
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("SaveJsonWithFilePicker() Exception: " + ex.Message);
                    throw;
                }
            }
        }
示例#26
0
        private async ValueTask SaveFileAsync()
        {
            CachedFileManager.DeferUpdates(_editedFile);

            await FileIO.WriteTextAsync(_editedFile, ViewModel.InputData);

            var status = await CachedFileManager.CompleteUpdatesAsync(_editedFile);
        }
示例#27
0
        private async Task <bool> LaunchFilePickerAndExportAsync()
        {
            bool processIsSuccessful = false;

            FileSavePicker savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.Downloads,
                SuggestedFileName      = "PhiliaContacts"
            };

            savePicker.FileTypeChoices.Add("Virtual Contact File", new List <string>()
            {
                ".vcf"
            });

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                try
                {
                    IsBusy = true;

                    CachedFileManager.DeferUpdates(file);

                    await FileIO.WriteTextAsync(file, Writer.Write(Manager));

                    Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    processIsSuccessful = status == Windows.Storage.Provider.FileUpdateStatus.Complete;

                    if (processIsSuccessful)
                    {
                        if (WorkflowSuccessAction != null)
                        {
                            WorkflowSuccessAction.Invoke();
                        }
                    }
                    else
                    {
                        if (WorkflowFailureAction != null)
                        {
                            WorkflowFailureAction.Invoke();
                        }
                    }
                }
                finally
                {
                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        IsBusy = false;
                        ExportCommand.RaiseCanExecuteChanged();
                    });
                }
            }

            return(processIsSuccessful);
        }
示例#28
0
        private async void btn_Pin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //SettingHelper.PinTile(_aid, _aid, txt_title.Text, (this.DataContext as VideoInfoModels).pic);
                string        appbarTileId = _aid;
                var           str          = (this.DataContext as VideoInfoModels).pic;
                StorageFolder localFolder  = Windows.Storage.ApplicationData.Current.LocalFolder;

                StorageFile file = await localFolder.CreateFileAsync(_aid + ".jpg", CreationCollisionOption.OpenIfExists);

                if (file != null)
                {
                    //img_Image
                    IBuffer bu = await WebClientClass.GetBuffer(new Uri((str)));

                    CachedFileManager.DeferUpdates(file);
                    await FileIO.WriteBufferAsync(file, bu);

                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if (status == FileUpdateStatus.Complete)
                    {
                        Uri    logo = new Uri("ms-appdata:///local/" + _aid + ".jpg");
                        string tileActivationArguments = _aid;
                        string displayName             = (this.DataContext as VideoInfoModels).title;

                        TileSize newTileDesiredSize = TileSize.Wide310x150;

                        SecondaryTile secondaryTile = new SecondaryTile(appbarTileId,
                                                                        displayName,
                                                                        tileActivationArguments,
                                                                        logo,
                                                                        newTileDesiredSize);


                        secondaryTile.VisualElements.Square44x44Logo             = logo;
                        secondaryTile.VisualElements.Wide310x150Logo             = logo;
                        secondaryTile.VisualElements.ShowNameOnSquare150x150Logo = true;
                        secondaryTile.VisualElements.ShowNameOnWide310x150Logo   = true;


                        await secondaryTile.RequestCreateAsync();

                        btn_Pin.Visibility   = Visibility.Collapsed;
                        btn_unPin.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        Utils.ShowMessageToast("创建失败", 3000);
                    }
                }
            }
            catch (Exception)
            {
                Utils.ShowMessageToast("创建失败", 3000);
            }
        }
示例#29
0
        private async void SaveTXT(StorageFile file)
        {
            CachedFileManager.DeferUpdates(file);
            Windows.Storage.Streams.IRandomAccessStream randAccStream = await file.OpenAsync(FileAccessMode.ReadWrite);

            Text.Document.SaveToStream(TextGetOptions.None, randAccStream);

            await CachedFileManager.CompleteUpdatesAsync(file);
        }
示例#30
0
        // Save As
        public static async Task <StorageFile> SaveAs(TextDataModel data)
        {
            FileSavePicker picker = new FileSavePicker();

            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Text Documents", new List <string>()
            {
                ".txt"
            });
            picker.FileTypeChoices.Add("All files", new List <string>()
            {
                "."
            });
            picker.DefaultFileExtension = ".txt";
            if (data.DocumentTitle != "")
            {
                picker.SuggestedFileName = data.DocumentTitle;
                // TODO: Get original file here as well
            }
            else
            {
                picker.SuggestedFileName = "Untitled";
            }


            StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                // Prevent remote access to file until saving is done
                CachedFileManager.DeferUpdates(file);

                // Write the stuff to the file
                await FileIO.WriteTextAsync(file, data.Text);

                // Get Fast Access token
                string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
                // #TODO: Check if the limit of 1000 has been reached and if yes, remove the 100 oldest entries
                // #TODO: Store this token somewhere

                // Let Windows know stuff is done
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                // DEBUG: Let programmer know what has happened
                if (status == FileUpdateStatus.Complete)
                {
                    Debug.WriteLine("File " + file.Name + " has been saved");
                }
                else
                {
                    Debug.WriteLine("File " + file.Name + " has NOT been saved");
                }
            }


            return(file);
        }