Ejemplo n.º 1
0
        public async Task StopRecording()
        {
            await datawriter.StoreAsync();

            await outputstream.FlushAsync();

            outputstream.Dispose();
            datawriter.Dispose();

            using (outputstream = stream.GetOutputStreamAt(4))
                using (datawriter = new DataWriter(outputstream)
                {
                    ByteOrder = ByteOrder.LittleEndian
                })
                {
                    datawriter.WriteUInt32((uint)size + 44);
                    await datawriter.StoreAsync();

                    await outputstream.FlushAsync();
                }

            using (outputstream = stream.GetOutputStreamAt(40))
                using (datawriter = new DataWriter(outputstream)
                {
                    ByteOrder = ByteOrder.LittleEndian
                })
                {
                    datawriter.WriteUInt32((uint)size);
                    await datawriter.StoreAsync();

                    await outputstream.FlushAsync();
                }
        }
Ejemplo n.º 2
0
        //
        //  we have to write the whole thing because we might have undo some records and so they
        //  need to be thrown away.
        public async Task WriteFullLogToDisk()
        {
            if (ActionStack.Count == 0)
            {
                return;
            }

            StringBuilder sb = new StringBuilder();

            foreach (var le in ActionStack)
            {
                sb.Append($"{le.Serialize()}\r\n");
            }


            _randomAccessStream.Size = 0;
            using (var outputStream = _randomAccessStream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new DataWriter(outputStream))
                {
                    dataWriter.WriteString(sb.ToString());
                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
        }
Ejemplo n.º 3
0
        public async Task SaveInkPageAsync(InkCanvas inkCanvas, InkPage inkPage, StorageFile file)
        {
            await FileIO.WriteBytesAsync(file, new byte[0]);

            CachedFileManager.DeferUpdates(file);

            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new DataWriter(outputStream))
                {
                    var json = JsonConvert.SerializeObject(inkPage, Formatting.Indented);
                    dataWriter.WriteString(json);
                    await dataWriter.StoreAsync();
                }
            }
            using (IOutputStream outputStream = stream.GetOutputStreamAt(100))
            {
                await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

                await outputStream.FlushAsync();
            }
            stream.Dispose();
        }
Ejemplo n.º 4
0
        public async Task <bool> SaveEpisodeList()
        {
            var filename = "Episodes.json";

            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                {
                    // Serialize the Session State.
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List <Episode>));

                    serializer.WriteObject(outStream.AsStreamForWrite(), EpisodesList);

                    await outStream.FlushAsync();

                    outStream.Dispose();
                    raStream.Dispose();

                    Debug.WriteLine("Episodelist saved");
                    return(true);
                }
            }
            catch (Exception) { Debug.WriteLine("episodelist failed to save"); return(false); }
        }
Ejemplo n.º 5
0
        public static async Task <bool> SaveAsync(string filename, IRandomAccessStream cacheStream)
        {
            StorageFolder saveFolder = Models.Setting.Current.SavePath;

            var storageFile = await saveFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream outputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                try
                {
                    using (IInputStream IS = cacheStream.GetInputStreamAt(0))
                    {
                        using (IOutputStream OS = outputStream.GetOutputStreamAt(0))
                        {
                            await RandomAccessStream.CopyAsync(IS, OS);
                        }
                    }
                    return(true);
                }
                catch
                {
                    try
                    {
                        await storageFile.DeleteAsync();
                    }
                    catch { }
                }
            }
            return(false);
        }
Ejemplo n.º 6
0
        private static async Task saveToJpegFile(WriteableBitmap writeableBitmap, StorageFile outputFile)
        {
            Guid   encoderId = BitmapEncoder.JpegEncoderId;
            Stream stream    = writeableBitmap.PixelBuffer.AsStream();

            byte[] pixels = new byte[(uint)stream.Length];
            await stream.ReadAsync(pixels, 0, pixels.Length);

            using (IRandomAccessStream writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Premultiplied,
                    (uint)writeableBitmap.PixelWidth,
                    (uint)writeableBitmap.PixelHeight,
                    96,
                    96,
                    pixels);
                await encoder.FlushAsync();

                using (IOutputStream outputStream = writeStream.GetOutputStreamAt(0))
                {
                    await outputStream.FlushAsync();
                }
            }
        }
Ejemplo n.º 7
0
        private async void OnSaveImage(object sender, RoutedEventArgs e)
        {
            IReadOnlyList <InkStroke> strokes = Canvas.InkPresenter.StrokeContainer.GetStrokes();

            if (strokes.Count > 0)
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation =
                    PickerLocationId.PicturesLibrary;
                savePicker.FileTypeChoices.Add(
                    "GIF",
                    new List <string> {
                    ".gif"
                });
                savePicker.DefaultFileExtension = ".gif";
                savePicker.SuggestedFileName    = "InkSample";

                // Show the file picker.
                StorageFile file = await savePicker.PickSaveFileAsync();

                if (file != null)
                {
                    IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                    // Write the ink strokes to the output stream.
                    using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
                    {
                        await Canvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

                        await outputStream.FlushAsync();
                    }
                    stream.Dispose();
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 序列化到文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task <bool> WriteAsync <T>(T data, string fileName)
        {
            bool result = false;

            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream rastream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    using (IOutputStream outStream = rastream.GetOutputStreamAt(0))
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                        serializer.WriteObject(outStream.AsStreamForWrite(), data);
                        await outStream.FlushAsync();

                        result = true;
                    }
                }
            }
            catch (Exception)
            {
                result = false;
            }
            return(result);
        }
Ejemplo n.º 9
0
        internal async void SaveProfile()
        {
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("profile", new List <string>()
            {
                ".prof"
            });
            savePicker.FileTypeChoices.Add("csv", new List <string>()
            {
                ".csv"
            });

            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "new profile";

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
                XmlSerializer serializer;
                serializer = new XmlSerializer(typeof(Profile));
                serializer.Serialize(sessionOutputStream.AsStreamForWrite(), CurrentProfile);

                sessionRandomAccess.Dispose();
                await sessionOutputStream.FlushAsync();

                sessionOutputStream.Dispose();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Processes and saves signatures.
        /// </summary>
        private async Task SaveSign(String ID, int index)
        {
            string fileName = ID + dateBox.Date.ToString("yyyy_MM_dd") + "_" + RealShiftBox.SelectedIndex + "_" + LineBox.SelectedIndex + "_" + ShiftBox.SelectedIndex + ".gif";

            StorageFile newFile = await saveHere.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            Windows.Storage.CachedFileManager.DeferUpdates(newFile);
            IRandomAccessStream stream =
                await newFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            // Write the ink strokes to the output stream.
            using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
            {
                await twoSigs[index].SaveAsync(outputStream);
                await outputStream.FlushAsync();
            }
            stream.Dispose();

            // Finalize write so other apps can update file.
            Windows.Storage.Provider.FileUpdateStatus status =
                await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(newFile);

            newCheck.sigPath[index] = fileName;
            //return newFile;
        }
Ejemplo n.º 11
0
        private async void SaveAsync(string filename, byte[] contents)
        {
            DateTime dtMetric = DateTime.UtcNow;

            filename = Path.IsPathRooted(filename) ? filename : Path.Combine(Device.ApplicationPath, filename);
            EnsureDirectoryExistsForFile(filename);
            var folder = await StorageFolder.GetFolderFromPathAsync(DirectoryName(filename));

            StorageFile file = await folder.CreateFileAsync(Path.GetFileName(filename), CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
                {
                    using (DataWriter dataWriter = new DataWriter(outputStream))
                    {
                        dataWriter.WriteBytes(contents);
                        await dataWriter.StoreAsync();

                        dataWriter.DetachStream();
                    }
                    await outputStream.FlushAsync();
                }
            }
            Device.Log.Metric(string.Format("BasicFile.SaveClear(stream): File: {0} Time: {1} milliseconds", filename, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds));
        }
Ejemplo n.º 12
0
        private async void Button_Savelocal_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker savePicker = new FileSavePicker();

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

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);

                var serializer = new XmlSerializer(typeof(TemplateCollection));
                serializer.Serialize(sessionOutputStream.AsStreamForWrite(), App.CodeSettingsContext.Templates);
                sessionRandomAccess.Dispose();
                await sessionOutputStream.FlushAsync();

                sessionOutputStream.Dispose();
            }
        }
Ejemplo n.º 13
0
        private async Task SaveLog()
        {
            StorageFile storageFile = await storageFolder.CreateFileAsync(logFile, CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
            {
                using (DataWriter dataWriter = new DataWriter(outputStream))
                {
                    dataWriter.WriteInt32(log.Log.Count());

                    foreach (List <string> changeList in log.Log)
                    {
                        dataWriter.WriteInt32(changeList.Count());

                        foreach (String change in changeList)
                        {
                            dataWriter.WriteInt32(change.Length);
                            dataWriter.WriteString(change);
                        }
                    }

                    await dataWriter.StoreAsync();
                }
                //await outputStream.FlushAsync();
            }
            stream.Dispose();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 把实体类对象序列化成XML格式存储到文件里面
        /// </summary>
        /// <typeparam name="T">实体类类型</typeparam>
        /// <param name="data">实体类对象</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static async Task WriteAsync <T>(T data, string filename)
        {
            try
            {
                // 获取存储数据的文件夹
                IStorageFolder applicationFolder = await GetDataFolder();

                StorageFile file = await applicationFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

                // 获取文件的数据流来进行操作
                using (IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                    {
                        // 创建序列化对象写入数据
                        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                        serializer.WriteObject(outStream.AsStreamForWrite(), data);
                        await outStream.FlushAsync();
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("StorageFileHelper: " + e.Message);
            }
        }
Ejemplo n.º 15
0
        public async Task ExportCurrentPath()
        {
            // Code to call file picker
            FileSavePicker savePicker = new FileSavePicker();

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

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream        sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
                List <List <Point> > Allpaths            = CurrentPath.AllPoints;
                var serializer = new XmlSerializer(typeof(List <List <Point> >));
                serializer.Serialize(sessionOutputStream.AsStreamForWrite(), Allpaths);
                sessionRandomAccess.Dispose();
                await sessionOutputStream.FlushAsync();

                sessionOutputStream.Dispose();
            }
        }
    public async Task Thumb_save(int index)
    {
        StorageFolder storageFolder         = ApplicationData.Current.LocalFolder;
        var           filename_thumb        = "xx"; // I dont have filename thumb that you should replace it to your code.
        var           sampleFile_thumb_back = await storageFolder.CreateFileAsync(filename_thumb + index + ".jpg",
                                                                                  CreationCollisionOption.ReplaceExisting);

        // we suggeste that use camelCase. Try to replace sampleFileThumbBack to sampleFile_thumb_back
        StorageFile         file_thumb_back   = sampleFile_thumb_back;
        IRandomAccessStream stream_thumb_back =
            await file_thumb_back.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

        using (IOutputStream outputStream_thumb_back = stream_thumb_back.GetOutputStreamAt(0))
        {
            // for I dont have any ink that you should uncomment in your code
            //await ink1.InkPresenter.StrokeContainer.SaveAsync(outputStream_thumb_back);
            //await outputStream_thumb_back.FlushAsync();
        }
        stream_thumb_back.Dispose();
        var imgThumbnail_back =
            await file_thumb_back.GetThumbnailAsync(ThumbnailMode.PicturesView, 200,
                                                    ThumbnailOptions.ResizeThumbnail);

        BitmapImage bitmapImage = new BitmapImage();

        bitmapImage.SetSource(imgThumbnail_back);
        ImageThumbnailList.Add(new ImageThumbnail()
        {
            ImageSource = bitmapImage
        });
    }
Ejemplo n.º 17
0
        private async Task saveToFile()
        {
            var xml = new XElement("Reminders");

            foreach (var reminder in this.Reminders)
            {
                xml.Add(reminder.ToXml());
            }

            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile   file   = await folder.CreateFileAsync("reminders.xml", CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
                {
                    using (DataWriter dataWriter = new DataWriter(outputStream))
                    {
                        //TODO: Replace "Bytes" with the type you want to write.
                        dataWriter.WriteString(xml.ToString());
                        await dataWriter.StoreAsync();

                        dataWriter.DetachStream();
                    }

                    await outputStream.FlushAsync();
                }
            }
        }
        private async Task <StorageFile> DownloadDatasheet()
        {
            // Lien de la déclaration de confidentialité : "http://ma.ms.giz.fr/?name=Datasheet+Finder"
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");

            StorageFile datasheetFile = null;

            using (client)
                using (var response = await client.GetAsync(DatasheetURL))
                {
                    if (response.Content.Headers.ContentType.MediaType == "application/pdf")
                    {
                        // TODO : add temporary images and datasheets in specific folders
                        datasheetFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".pdf", CreationCollisionOption.ReplaceExisting);

                        using (IRandomAccessStream fs = await datasheetFile.OpenAsync(FileAccessMode.ReadWrite))
                            using (DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0)))
                            {
                                writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
                                await writer.StoreAsync();

                                await fs.FlushAsync();
                            }
                    }
                }

            return(datasheetFile);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Saves all data that this repository has
        /// </summary>
        /// <param name="rootFolder">Folder in which to save the data</param>
        public async Task Save(StorageFolder rootFolder)
        {
            StorageFolder modelFolder = await GetFolder(rootFolder);

            // If all data was deleted then delete all the files
            if (modelProperty().Count == 0)
            {
                // Create a new folder for this model, deleting the old one while it does
                modelFolder = await rootFolder.CreateFolderAsync(ModelName + "s", CreationCollisionOption.ReplaceExisting);
            }

            // Loop each instance in the list
            foreach (T model in modelProperty())
            {
                // Create an XmlSerializer for serializing the data
                XmlSerializer xmlSerializer = new XmlSerializer(model.GetType());
                // Create a file for the model
                // We replace existing files so that it overwrites old data
                StorageFile file = await modelFolder.CreateFileAsync(model.ID.ToString(), CreationCollisionOption.ReplaceExisting);

                // A random access stream is used to push data to the file
                IRandomAccessStream fileRandomAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                // Used to disposing and flushing data which helps for memory conservation
                IOutputStream fileOutputStream = fileRandomAccessStream.GetOutputStreamAt(0);
                // Serialize the data to the file
                xmlSerializer.Serialize(fileRandomAccessStream.AsStreamForWrite(), model);
                // Dispose of and flush the file streams (Do flush asynchronously so it doesn't jam the thread)
                fileRandomAccessStream.Dispose();
                await fileOutputStream.FlushAsync();

                fileOutputStream.Dispose();
            }
        }
Ejemplo n.º 20
0
        public static async Task <bool> writeObjektAsync <T>(string file, T objekt)
        {
            try
            {
                StorageFile userdetailsfile = await
                                              ApplicationData.Current.LocalFolder.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream rndStream = await
                                                userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);

                using (IOutputStream outStream = rndStream.GetOutputStreamAt(0))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(outStream.AsStreamForWrite(), objekt);
                    var xx = await outStream.FlushAsync();

                    rndStream.Dispose();
                    outStream.Dispose();
                }
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Saves the file with fullFilePath, uses FileMode.Create, so file create time will be rewrited if needed
        /// If exception has occurred while writing the file, it will delete it
        /// </summary>
        /// <param name="fullFilePath">example: "\\image_cache\\213898adj0jd0asd</param>
        /// <param name="cacheStream">stream to write to the file</param>
        /// <returns>true if file was successfully written, false otherwise</returns>
        protected async virtual Task <bool> InternalSaveAsync(string fullFilePath, IRandomAccessStream cacheStream)
        {
            var storageFile = await SF.CreateFileAsync(fullFilePath, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream outputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                try
                {
                    await RandomAccessStream.CopyAsync(
                        cacheStream.GetInputStreamAt(0L),
                        outputStream.GetOutputStreamAt(0L));

                    return(true);
                }
                catch
                {
                    try
                    {
                        // If file was not saved normally, we should delete it
                        await storageFile.DeleteAsync();
                    }
                    catch
                    {
                        ImageLog.Log("[error] can not delete unsaved file: " + fullFilePath);
                    }
                }
            }
            ImageLog.Log("[error] can not save cache to the: " + fullFilePath);
            return(false);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 保存远程url地址图片,到本地
        /// </summary>
        /// <param name="uri">远程地址</param>
        /// <param name="filename">保存的名称</param>
        /// <param name="folder">保存位置枚举</param>
        /// <returns></returns>
        internal async static Task SaveImageFromUrl(string uri, string filename, StorageFolder folder)
        {
            var rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri));
            IRandomAccessStream inputStream = await rass.OpenReadAsync();

            Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0));

            try
            {
                //获取图片扩展名的Guid
                StorageFile outputFile = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    Stream output = WindowsRuntimeStreamExtensions.AsStreamForWrite(outputStream.GetOutputStreamAt(0));
                    await input.CopyToAsync(output);

                    output.Dispose();
                    input.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 23
0
        async private Task Save(XDocument xdoc, string path)
        {
            StringWriter swriter = new StringWriter();

            xdoc.Save(swriter, SaveOptions.None);
            string  xmlString          = swriter.GetStringBuilder().ToString();
            IBuffer xmlEncryptedBuffer = EncryptionProvider.Encrypt(xmlString);

            StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\");

            var file = await sf.GetFileAsync(Path.GetFileName(path));

            using (IRandomAccessStream ras = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outs = ras.GetOutputStreamAt(0))
                {
                    await outs.WriteAsync(xmlEncryptedBuffer);

                    bool suc = await outs.FlushAsync();

                    outs.Dispose();
                }
                ras.Dispose();
            }
        }
        public virtual async Task <bool> WriteDataAsync(IList <T> data)
        {
            try
            {
                StorageFolder store = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataFilesFolder);

                StorageFile sessionFile = await store.CreateFileAsync(SourcePath, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0))
                    {
                        var sessionSerializer = new DataContractSerializer(typeof(T[]), new Type[] { typeof(T[]) });
                        sessionSerializer.WriteObject(sessionOutputStream.AsStreamForWrite(), data.ToArray());
                        await sessionOutputStream.FlushAsync();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 25
0
        public async Task StartRecording()
        {
            StorageFolder folder    = KnownFolders.MusicLibrary;
            string        timestamp = DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss");

            file = await folder.CreateFileAsync("soundhub-" + timestamp + ".wav",
                                                CreationCollisionOption.ReplaceExisting);

            stream = await file.OpenAsync(FileAccessMode.ReadWrite);

            outputstream = stream.GetOutputStreamAt(0);
            datawriter   = new DataWriter(outputstream)
            {
                ByteOrder = ByteOrder.LittleEndian
            };
            size = 0;

            byte[] header     = Encoding.UTF8.GetBytes("RIFF    WAVEfmt ");
            byte[] dataheader = Encoding.UTF8.GetBytes("data");

            datawriter.WriteBytes(header);
            datawriter.WriteUInt32(16);     // fmt chunk size = 16
            datawriter.WriteUInt16(3);      // Float audioformat = 3
            datawriter.WriteUInt16(1);      // No channels = 1
            datawriter.WriteUInt32(8000);   // Sample rate
            datawriter.WriteUInt32(32000);  // Byte rate
            datawriter.WriteUInt16(4);      // Block align
            datawriter.WriteUInt16(32);     // Bits per sample
            datawriter.WriteBytes(dataheader);
            datawriter.WriteUInt32(0);
            await datawriter.StoreAsync();

            await outputstream.FlushAsync();
        }
        private async void RenderInkImageAsync()
        {
            IReadOnlyList <InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();

            if (currentStrokes.Count > 0)
            {
                Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
                Windows.Storage.StorageFile   file          = await storageFolder.CreateFileAsync($"{Guid.NewGuid()}.png", Windows.Storage.CreationCollisionOption.ReplaceExisting);

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

                    IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                    using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
                    {
                        await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

                        await outputStream.FlushAsync();
                    }
                    stream.Dispose();
                }

                BitmapImage bm = new BitmapImage(new Uri($"ms-appdata:///temp/{file.Name}"));

                App.ViewModel.SelectedDocument.AnnotationImage = bm;
            }

            Frame.GoBack();
        }
Ejemplo n.º 27
0
        public async Task <bool> OpenFile(string fileName, bool forWriting)
        {
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            IStorageItem  f      = await folder.TryGetItemAsync(fileName);

            if (f == null)
            {
                f = await folder.CreateFileAsync(fileName);
            }
            StorageFile file = (StorageFile)f;

            if (forWriting)
            {
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                outputStream = stream.GetOutputStreamAt(0);
                dataWriter   = new DataWriter(outputStream);
                dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8;
                dataWriter.ByteOrder       = ByteOrder.LittleEndian;
            }
            else
            {
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

                ulong len = stream.Size;
                inputStream = stream.GetInputStreamAt(0);
                dataReader  = new DataReader(inputStream);
                await dataReader.LoadAsync((uint)len);

                dataReader.UnicodeEncoding    = UnicodeEncoding.Utf8;
                dataReader.ByteOrder          = ByteOrder.LittleEndian;
                dataReader.InputStreamOptions = InputStreamOptions.ReadAhead;
            }
            return(true);
        }
Ejemplo n.º 28
0
        public static async Task <StorageFile> AsUIScreenShotFileAsync(this UIElement elememtName, string ReplaceLocalFileNameWithExtension)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(ReplaceLocalFileNameWithExtension, CreationCollisionOption.ReplaceExisting);

            try
            {
                RenderTargetBitmap         renderTargetBitmap = new RenderTargetBitmap();
                InMemoryRandomAccessStream stream             = new InMemoryRandomAccessStream();
                // Render to an image at the current system scale and retrieve pixel contents
                await renderTargetBitmap.RenderAsync(elememtName);

                var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

                // Encode image to an in-memory stream
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight,
                                     DisplayInformation.GetForCurrentView().LogicalDpi,
                                     DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray());
                await encoder.FlushAsync();

                //CreatingFolder
                // var folder = Windows.Storage.ApplicationData.Current.LocalFolder;

                RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromStream(stream);
                var streamWithContent            = await rasr.OpenReadAsync();

                byte[] buffer = new byte[streamWithContent.Size];
                await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);


                using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))

                {
                    using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))

                    {
                        using (DataWriter dataWriter = new DataWriter(outputStream))

                        {
                            dataWriter.WriteBytes(buffer);

                            await dataWriter.StoreAsync(); //

                            dataWriter.DetachStream();
                        }
                        // write data on the empty file:
                        await outputStream.FlushAsync();
                    }
                    await fileStream.FlushAsync();
                }
                // await file.CopyAsync(folder, "tempFile.jpg", NameCollisionOption.ReplaceExisting);
            }
            catch (Exception ex)
            {
                Reporting.DisplayMessageDebugExemption(ex);
            }
            return(file);
        }
Ejemplo n.º 29
0
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                IReadOnlyList <InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
                if (currentStrokes.Count > 0)
                {
                    FileSavePicker savePicker = new FileSavePicker();
                    savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                    savePicker.FileTypeChoices.Add(
                        "GIF with embedded ISF",
                        new List <string>()
                    {
                        ".gif"
                    });
                    savePicker.DefaultFileExtension = ".gif";
                    savePicker.SuggestedFileName    = "InkSample";

                    StorageFile file = await savePicker.PickSaveFileAsync();

                    if (file != null)
                    {
                        Windows.Storage.CachedFileManager.DeferUpdates(file);
                        IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                        using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
                        {
                            await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

                            await outputStream.FlushAsync();
                        }
                        stream.Dispose();

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

                        if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                        {
                            var messageDialog = new MessageDialog("Save Success!");
                            await messageDialog.ShowAsync();
                        }
                        else
                        {
                            var messageDialog = new MessageDialog("Save Failed");
                            await messageDialog.ShowAsync();
                        }
                    }
                    else
                    {
                        var messageDialog = new MessageDialog("No strokes to save.");
                        await messageDialog.ShowAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                var messageDialog = new MessageDialog(ex.Message);
                await messageDialog.ShowAsync();
            }
        }
Ejemplo n.º 30
0
        public static async Task SaveCheatCodes(ROMDBEntry re, List <CheatData> cheatCodes)
        {
            try
            {
                String romFileName = re.FileName;
                int    index       = romFileName.LastIndexOf('.');
                int    diff        = romFileName.Length - index;

                string cheatFileName = romFileName.Substring(0, romFileName.Length - diff);
                cheatFileName += ".cht";

                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                StorageFolder romFolder   = await localFolder.GetFolderAsync(ROM_DIRECTORY);

                StorageFolder saveFolder = await romFolder.GetFolderAsync(SAVE_DIRECTORY);


                StorageFile file = await saveFolder.CreateFileAsync("cheattmp.cht", CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IOutputStream outStream = stream.GetOutputStreamAt(0L))
                    {
                        using (DataWriter writer = new DataWriter(outStream))
                        {
                            writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                            writer.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                            for (int i = 0; i < cheatCodes.Count; i++)
                            {
                                if (i > 0)
                                {
                                    writer.WriteString("\n");
                                }
                                writer.WriteString(cheatCodes[i].Description);
                                writer.WriteString("\n");
                                writer.WriteString(cheatCodes[i].CheatCode);
                                writer.WriteString("\n");
                                writer.WriteString(cheatCodes[i].Enabled ? "1" : "0");
                            }
                            await writer.StoreAsync();

                            await writer.FlushAsync();

                            writer.DetachStream();
                        }
                    }
                }

                //rename the temp file to the offical file
                await file.RenameAsync(cheatFileName, NameCollisionOption.ReplaceExisting);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Save cheat code error: " + ex.Message);
            }
        }