public async Task Play(CoreDispatcher dispatcher)
        {
            LoggingMsg("Playing audio...");
            MediaElement        playback = new MediaElement();
            IRandomAccessStream audio    = buffer.CloneStream();

            if (audio == null)
            {
                throw new ArgumentNullException("buffer");
            }
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            if (!string.IsNullOrEmpty(filename))
            {
                StorageFile original = await storageFolder.GetFileAsync(filename);

                await original.DeleteAsync();
            }
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                recordingFile = await storageFolder.CreateFileAsync(RECORDING_FILE, CreationCollisionOption.ReplaceExisting);
                filename      = recordingFile.Name;
                using (IRandomAccessStream fileStream = await recordingFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                    await audio.FlushAsync();
                    audio.Dispose();
                }

                IRandomAccessStream stream = await recordingFile.OpenAsync(FileAccessMode.Read);
                playback.SetSource(stream, recordingFile.FileType);
                //Time.Text = playback.NaturalDuration.TimeSpan.TotalSeconds.ToString();
                playback.Play();
            });
        }
        private async void StoreImage(WriteableBitmap bmp, SpriteTextureType spriteTextureType)
        {
            if (!EnableImageStoring)
            {
                return;
            }
            var folderDesc = await FolderOfType(spriteTextureType);

            IRandomAccessStream stream = null;

            DeleteFilesUntilIndex(folderDesc.folder, folderDesc.lastIndex);
            try
            {
                folderDesc.lastIndex++;
                var file = await folderDesc.folder.CreateFileAsync(folderDesc.lastIndex.ToString());

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

                if (stream.CanWrite)
                {
                    await bmp.WriteBinAsync(stream);

                    await stream.FlushAsync();

                    stream.Dispose();
                    stream = null;
                    return;
                }
            }
            catch
            {
            }
        }
Esempio n. 3
0
        /// <inheritdoc/>
        public async Task <string> WriteFileAsync(Stream stream, string nameWithExt, string localDirName = null)
        {
            StorageFolder dir;

            if (string.IsNullOrWhiteSpace(localDirName))
            {
                dir = ApplicationData.Current.LocalFolder;
            }
            else
            {
                dir = await ApplicationData.Current.LocalFolder.CreateFolderAsync(
                    localDirName,
                    CreationCollisionOption.OpenIfExists);
            }

            StorageFile storageFile = await dir.CreateFileAsync(
                nameWithExt,
                CreationCollisionOption.ReplaceExisting);

            using IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

            await stream.CopyToAsync(fileStream.AsStreamForWrite());

            await fileStream.FlushAsync();

            return(storageFile.Path);
        }
Esempio n. 4
0
        public async Task SaveRecordedAudio(CoreDispatcher UiDispatcher)
        {
            IRandomAccessStream audio = buffer.CloneStream();

            if (audio == null)
            {
                throw new ArgumentNullException("buffer");
            }

            //StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            /*
             * StorageFolder storageFolder = await DownloadsFolder.;
             * if (!string.IsNullOrEmpty(filename))
             * {
             *  StorageFile original = await storageFolder.GetFileAsync(filename);
             *  await original.DeleteAsync();
             * }
             */
            await UiDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                //StorageFile storageFile = await storageFolder.CreateFileAsync(audioFile, CreationCollisionOption.GenerateUniqueName);
                StorageFile storageFile = await DownloadsFolder.CreateFileAsync(audioFile, CreationCollisionOption.GenerateUniqueName);
                filename = storageFile.Name;
                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                    await audio.FlushAsync();
                    audio.Dispose();
                }
                //IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);

                LogMessage($"File {storageFile.Name} saved to {storageFile.Path}");
            });
        }
Esempio n. 5
0
        public async void SaveAudioToFile()
        {
            try
            {
                //await DeleteExistingFile();
                MediaPlayer mediaPlayer = new MediaPlayer();
                mediaPlayer.Source = MediaSource.CreateFromStream(_memoryBuffer, "MP3");
                mediaPlayer.Play();
                IRandomAccessStream audioStream   = _memoryBuffer.CloneStream();
                StorageFolder       storageFolder = Package.Current.InstalledLocation;

                StorageFile storageFile = await storageFolder.CreateFileAsync(DEFAULT_AUDIO_FILENAME, CreationCollisionOption.GenerateUniqueName);

                this._fileName = storageFile.Name;

                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                    await audioStream.FlushAsync();

                    audioStream.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 6
0
        private async void SaveAudioToFile(InMemoryRandomAccessStream buffer)
        {
            try
            {
                IRandomAccessStream audioStream   = buffer.CloneStream();
                StorageFolder       storageFolder = Package.Current.InstalledLocation;

                StorageFile storageFile = await storageFolder.CreateFileAsync(DEFAULT_AUDIO_FILENAME, CreationCollisionOption.GenerateUniqueName);

                this._fileName = storageFile.Name;

                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                    await audioStream.FlushAsync();

                    audioStream.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        private async void LoadPdfFileAsync(StorageFile bookUrl)
        {
            try
            {
                ObservableCollection <BookPdf> bookPages = new ObservableCollection <BookPdf>();
                PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(bookUrl);

                int count = 0;
                popUp.IsOpen           = true;
                progressLoader.Maximum = (int)pdfDocument.PageCount;
                pageCount.Text         = pdfDocument.PageCount.ToString() + " Pages";
                progressStatus.Text    = "Loading Pages...";
                for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++)
                {
                    var pdfPage = pdfDocument.GetPage((uint)pageIndex);
                    if (pdfPage != null)
                    {
                        StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
                        StorageFile   pngFile    = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                        if (pngFile != null && pdfPage != null)
                        {
                            IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite);

                            await pdfPage.RenderToStreamAsync(randomStream);

                            await randomStream.FlushAsync();

                            randomStream.Dispose();
                            pdfPage.Dispose();


                            count++;
                            progressLoader.Value = pageIndex;
                            int progress = (100 * pageIndex) / (int)pdfDocument.PageCount;

                            downloadSize.Text = String.Format("{0} of {1} pages loaded - {2} % complete.", pageIndex, pdfDocument.PageCount, progress);
                            bookPages.Add(new BookPdf {
                                Id = pageIndex.ToString(), PageNumber = pageIndex.ToString(), ImagePath = pngFile.Path
                            });
                        }
                    }
                }

                if (progressLoader.Value >= 99 || count >= (int)pdfDocument.PageCount - 1)
                {
                    progressStatus.Text = "Pages Loaded";
                    popUp.IsOpen        = false;
                }
                bookPagesView.ItemsSource = bookPages;
            }
            catch (Exception ex)
            {
                var popup = new Windows.UI.Popups.MessageDialog("Cant load the file. The program might have failed to open the file  or you are not connected");
                popup.Commands.Add(new Windows.UI.Popups.UICommand("Ok"));
                popup.DefaultCommandIndex = 0;
                popup.CancelCommandIndex  = 1;
                var results = await popup.ShowAsync();
            }
        }
        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);
        }
Esempio n. 9
0
        /// <summary>
        /// Saves the audio to a file in our local state folder
        /// </summary>
        /// <returns>the saved file's name</returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public async Task <string> SaveAudioToFile()
        {
            string        dateToday        = DateTime.Now.ToString("yyyy-MM-dd");
            string        ticks            = DateTime.Now.Ticks.ToString();
            string        mp3              = ".mp3";
            string        fileName         = String.Format("record_{0}_{1}{2}", dateToday, ticks, mp3);
            StorageFolder localStateFolder = ApplicationData.Current.LocalFolder;
            StorageFolder storageFolder;

            if (!Directory.Exists(Path.Combine(localStateFolder.Path, "VoiceNotes")))
            {
                storageFolder = await localStateFolder.CreateFolderAsync("VoiceNotes");
            }
            else
            {
                storageFolder = await localStateFolder.GetFolderAsync("VoiceNotes");
            }
            IRandomAccessStream audioStream = this.MemoryBuffer.CloneStream();
            StorageFile         storageFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

            this._fileName = storageFile.Name;
            using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                await audioStream.FlushAsync();

                audioStream.Dispose();
            }
            this.DisposeMemoryBuffer();

            return(this._fileName);
        }
        public async Task <IMediaModel> GenerateThumbImageFromVideo(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel)
        {
            StorageFolder currentFolder = await StorageFolder.GetFolderFromPathAsync(argCurrentDataFolder.FullName);

            StorageFile outfile = await currentFolder.CreateFileAsync(argNewMediaModel.OriginalFilePath, CreationCollisionOption.ReplaceExisting);

            //if (outfile.Name == "_e9e27fbe8ed34e9b554a0ba93aa~imagevideo.jpg")
            //{
            //}

            StorageFile videoFile = await currentFolder.GetFileAsync(argExistingMediaModel.OriginalFilePath);

            StorageItemThumbnail thumbnail = await videoFile.GetThumbnailAsync(ThumbnailMode.SingleItem);

            Windows.Storage.Streams.Buffer MyBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(thumbnail.Size));
            IBuffer iBuf = await thumbnail.ReadAsync(MyBuffer, MyBuffer.Capacity, InputStreamOptions.None);

            IRandomAccessStream strm = await outfile.OpenAsync(FileAccessMode.ReadWrite);

            await strm.WriteAsync(iBuf);

            await strm.FlushAsync();

            strm.Dispose();

            // check size
            BasicProperties outProperties = await outfile.GetBasicPropertiesAsync();

            if (outProperties.Size == 0)
            {
                return(new MediaModel());
            }

            return(argNewMediaModel);
        }
Esempio n. 11
0
    public async Task PlayVoice(CoreDispatcher dispatcher) //Plays the voice recording back
    {
        MediaElement        playVoice = new MediaElement();
        IRandomAccessStream voice     = buffer.CloneStream();

        if (voice == null)
        {
            throw new ArgumentNullException("BUFFER");
        }
        StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

        if (!string.IsNullOrEmpty(appFile))
        {
            StorageFile sf = await appFolder.GetFileAsync(appFile);

            await sf.DeleteAsync();
        }
        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
        {
            StorageFile file = await appFolder.CreateFileAsync(voiceFile, CreationCollisionOption.GenerateUniqueName);
            appFile          = file.Name;
            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(voice.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                await voice.FlushAsync();
                voice.Dispose();
            }
            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
            playVoice.SetSource(stream, file.FileType);
            playVoice.Play();
        });
    }
        private async Task SaveImageToStream(IRandomAccessStream stream)
        {
            // render bitmap
            var desiredWidth  = (uint)Window.Current.Bounds.Right;
            var desiredHeight = (uint)Window.Current.Bounds.Bottom;

            TileCanvas.Width  = desiredWidth;
            TileCanvas.Height = desiredHeight;

            var bitmap = new RenderTargetBitmap();
            await bitmap.RenderAsync(TileCanvas);

            IBuffer pixels = await bitmap.GetPixelsAsync();

            byte[] bytes = pixels.ToArray();

            // encode bitmap
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            encoder.BitmapTransform.Bounds = new BitmapBounds
            {
                Width  = desiredWidth,
                Height = desiredHeight
            };
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96, bytes);
            await encoder.FlushAsync();

            await stream.FlushAsync();
        }
Esempio n. 13
0
        protected async Task <string> SaveBitmapFile(WriteableBitmap wb)
        {
            EventSource.Log.Debug("SaveBitmapFile()");

            // Copy our current color image
            DateTime now      = DateTime.Now;
            string   fileName = "KinectPhotobooth" + "-" + now.ToString("s").Replace(":", "-") + "-" + now.Millisecond.ToString() + ".png";

            StorageFile file = await this.targetFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

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

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            Stream pixelStream = wb.PixelBuffer.AsStream();

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

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)wb.PixelWidth, (uint)wb.PixelHeight, 96.0, 96.0, pixels);

            // clean up
            pixelStream.Dispose();
            await encoder.FlushAsync();

            await stream.FlushAsync();

            stream.Dispose();

            return(fileName);
        }
Esempio n. 14
0
        /// <summary>
        /// The download.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/> to run asynchronously.
        /// </returns>
        private async Task Download()
        {
            var page       = DataManager.CurrentPage;
            var url        = page.Url.ToString();
            var nameOnDisk =
                url.Substring(url.LastIndexOf("//", StringComparison.CurrentCultureIgnoreCase) + 2)
                .Replace(".", "_")
                .Replace("/", "-");

            if (nameOnDisk.EndsWith("-"))
            {
                nameOnDisk = nameOnDisk.Substring(0, nameOnDisk.Length - 1);
            }

            var filename = string.Format("{0}.txt", nameOnDisk);
            var download = await DownloadsFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

            // await FileIO.WriteTextAsync(download, page.Text, Windows.Storage.Streams.UnicodeEncoding.Utf8);
            using (IRandomAccessStream stream = await download.OpenAsync(FileAccessMode.ReadWrite))
            {
                await stream.WriteAsync(Encoding.UTF8.GetBytes(page.Text).AsBuffer());

                await stream.FlushAsync();
            }

            var dialog = new MessageDialog(
                "Successfully downloaded the page as text to your Downloads folder.",
                download.Name);
            await dialog.ShowAsync();
        }
Esempio n. 15
0
        async public static void Log(string s)
        {
            using (var releaser = await myLock.LockAsync())
            {
                StorageFile sfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("errorlog.txt", CreationCollisionOption.OpenIfExists);

                using (IRandomAccessStream rasw = await sfile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    IBuffer ibuf = null;
                    using (IInputStream inputStream = rasw.GetInputStreamAt(0))
                    {
                        ulong      size       = rasw.Size;
                        DataReader dataReader = new DataReader(inputStream);
                        await dataReader.LoadAsync((uint)size);

                        ibuf = dataReader.ReadBuffer((uint)size);
                        inputStream.Dispose();
                    }

                    if (ibuf.Length < 64000)
                    {
                        await rasw.WriteAsync(ibuf);
                    }

                    await rasw.WriteAsync(CryptographicBuffer.ConvertStringToBinary("\r\n" + DateTime.Now.ToUniversalTime().ToString() + " : " + s, BinaryStringEncoding.Utf8));

                    rasw.Seek(0);
                    await rasw.FlushAsync();

                    rasw.Dispose();
                }
            }
        }
Esempio n. 16
0
    public async Task Play(CoreDispatcher dispatcher, MediaElement playback)
    {
        IRandomAccessStream video = buffer.CloneStream();

        if (video == null)
        {
            throw new ArgumentNullException("buffer");
        }
        StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

        if (!string.IsNullOrEmpty(filename))
        {
            StorageFile original = await storageFolder.GetFileAsync(filename);

            await original.DeleteAsync();
        }
        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
        {
            StorageFile storageFile = await storageFolder.CreateFileAsync(videoFilename, CreationCollisionOption.GenerateUniqueName);
            filename = storageFile.Name;
            using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(video.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                await video.FlushAsync();
                video.Dispose();
            }
            IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
            playback.SetSource(stream, storageFile.FileType);
            playback.Play();
        });
    }
Esempio n. 17
0
        /// <summary>
        /// Clicking on the save button saves the photo in MainPage.ImageStream
        /// to media library camera roll. Once image has been saved, the
        /// application will navigate back to the main page.
        /// </summary>
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedIndex = FilterPreviewListView.SelectedIndex;

            DataContext dataContext = FilterEffects.DataContext.Instance;

            // Create the File Picker control
            var picker = new FileSavePicker();

            picker.FileTypeChoices.Add("JPG File", new List <string> {
                ".jpg"
            });
            StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                // If the file path and name is entered properly, and user has not tapped 'cancel'..

                AbstractFilter filter = _filters[selectedIndex];
                IBuffer        buffer = await filter.RenderJpegAsync(
                    dataContext.FullResolutionStream.GetWindowsRuntimeBuffer());

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await stream.WriteAsync(buffer);

                    await stream.FlushAsync();
                }

                ShowToast(Strings.ImageSavedAs + file.Name);
            }
        }
Esempio n. 18
0
        public async Task Play(CoreDispatcher dispatcher)
        {
            MediaElement        playback = new MediaElement();
            IRandomAccessStream audio    = buffer.CloneStream();

            if (audio == null)
            {
                throw new ArgumentNullException("buffer");
            }
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            if (!string.IsNullOrEmpty(filename))
            {
                StorageFile original = await storageFolder.GetFileAsync(filename);

                await original.DeleteAsync();
            }
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                StorageFile storageFile = await storageFolder.CreateFileAsync(audioFilename, CreationCollisionOption.ReplaceExisting);
                filename = storageFile.Name;
                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                    await audio.FlushAsync();
                    audio.Dispose();
                }
                IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
                playback.SetSource(stream, "");
                playback.Play();
            });
        }
Esempio n. 19
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);
        }
Esempio n. 20
0
 public override void Flush()
 {
     if (_disposed)
     {
         throw new ObjectDisposedException("_stream");
     }
     Task.Run(async() => await _stream.FlushAsync()).Wait();
 }
Esempio n. 21
0
        public static async Task <StorageFile> CropImage(IRandomAccessStream fs, int newWidth, int newHeight)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fs);

            StorageFile file = await FileHelper.CreateLocalFile("cropped.jpg", "Cache", true);

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

            BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(stream, decoder);

            enc.BitmapTransform.ScaledWidth  = (uint)newWidth;
            enc.BitmapTransform.ScaledHeight = (uint)newHeight;
            var MaxImageWidth  = 100;
            var MaxImageHeight = 100;

            if (newWidth > MaxImageWidth || newHeight > MaxImageHeight)
            {
                BitmapBounds bounds = new BitmapBounds();
                if (newWidth > MaxImageWidth)
                {
                    bounds.Width = (uint)MaxImageWidth;
                    bounds.X     = (uint)(newWidth - MaxImageWidth) / 2;
                }
                else
                {
                    bounds.Width = (uint)newWidth;
                }
                if (newHeight > MaxImageHeight)
                {
                    bounds.Height = (uint)MaxImageHeight;
                    bounds.Y      = (uint)(newHeight - MaxImageHeight) / 2;
                }
                else
                {
                    bounds.Height = (uint)newHeight;
                }
                enc.BitmapTransform.Bounds = bounds;
            }

            try
            {
                await enc.FlushAsync();
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
            }

            await stream.FlushAsync();

            stream.Dispose();

            fs.Dispose();

            return(file);
        }
        private async void loadWebViewToStream(WebView webview, IRandomAccessStream stream)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(10));

            await webview.CapturePreviewToStreamAsync(stream);

            await stream.FlushAsync();

            stream.Seek(0);
        }
Esempio n. 23
0
    private async void StropButton_Click(object sender, RoutedEventArgs e)
    {
        await mediaCapture.StopRecordAsync();

        await randomAccessStream.FlushAsync();

        randomAccessStream.Seek(0);
        // want to convert this randomAccessStream into byte[]
        mediaElement.SetSource(randomAccessStream, "video/x-ms-wmv");
    }
Esempio n. 24
0
        async Task <byte[]> ToBytesArray(IRandomAccessStream s, int size)
        {
            var dr    = new DataReader(s.GetInputStreamAt(0));
            var bytes = new byte[size];
            await dr.LoadAsync((uint)size);

            dr.ReadBytes(bytes);
            await s.FlushAsync();

            return(bytes);
        }
Esempio n. 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task <bool> SaveImageFileAsync(StorageFile file)
        {
            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await stream.WriteAsync(_imageBuffer);

                await stream.FlushAsync();
            }

            return(true);
        }
Esempio n. 26
0
        public async Task <StorageFile> Download()
        {
            if (m_SourceUri == null || m_SourceUri.IsFile)
            {
                return(null);
            }
            StorageFile tempFile = await m_DestinationStorageFolder.CreateFileAsync(m_DestinationFileName + ".tmp", CreationCollisionOption.GenerateUniqueName);

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
                HttpResponseMessage response = await httpClient.GetAsync(m_SourceUri, HttpCompletionOption.ResponseHeadersRead);

                if (response.StatusCode != HttpStatusCode.Ok /*||
                                                              * Path.GetFileName(response.RequestMessage.RequestUri.AbsoluteUri) != Path.GetFileName(m_SourceUri.ToString())*/)
                {
                    string result = await response.Content.ReadAsStringAsync();

                    throw new Exception(result);
                }

                if (response.Content.Headers.ContentLength != null)
                {
                    m_TotalBytes = response.Content.Headers.ContentLength.Value;
                }
                IBuffer buffer = new Windows.Storage.Streams.Buffer(m_bufferSize);
                using (IRandomAccessStream fileStream = await tempFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IInputStream httpStream = await response.Content.ReadAsInputStreamAsync())
                    {
                        do
                        {
                            await httpStream.ReadAsync(buffer, m_bufferSize, InputStreamOptions.ReadAhead);

                            if (buffer.Length > 0)
                            {
                                await fileStream.WriteAsync(buffer);

                                if (m_Progress != null)
                                {
                                    m_DownloadedBytes += buffer.Length;
                                    ((IProgress <Downloader>)m_Progress).Report(this);
                                }
                            }
                        }while (buffer.Length > 0);
                    }
                    await fileStream.FlushAsync();
                }
            }

            await tempFile.RenameAsync(Path.GetFileName(m_DestinationFileName), NameCollisionOption.ReplaceExisting);

            return(tempFile);
        }
Esempio n. 27
0
        private async void LoadTrang()
        {
            Debug.WriteLine(FileName);
            DateTime startTime = DateTime.Now;

            if (PdfImages == null)
            {
                PdfImages = new ObservableCollection <string>();
            }
            PdfImages.Clear();

            Uri fileTarget = new Uri(@"ms-appx:///KhoChuaDe/" + FileName + ".pdf");
            var file       = await Package.Current.InstalledLocation.GetFileAsync(@"KhoChuaDe\" + FileName + ".pdf");

            var pdfFile = await PdfDocument.LoadFromFileAsync(file);

            if (pdfFile == null)
            {
                return;
            }
            tongsotrang.Text = pdfFile.PageCount.ToString();
            pagecount        = pdfFile.PageCount;
            for (uint i = 0; i < pdfFile.PageCount; i++)
            {
                StorageFolder tempFolder = ApplicationData.Current.LocalFolder;
                StorageFile   jpgFile    = await tempFolder.CreateFileAsync(
                    pdfFile + "-Page-" + i.ToString() + ".png",
                    CreationCollisionOption.ReplaceExisting
                    );

                var pdfPage = pdfFile.GetPage(i);

                if (jpgFile != null && pdfPage != null)
                {
                    IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite);

                    await pdfPage.RenderToStreamAsync(randomStream);

                    await randomStream.FlushAsync();

                    randomStream.Dispose();
                    pdfPage.Dispose();
                }

                PdfImages.Add(jpgFile.Path);
            }

            this.pdfViewer.ItemsSource = PdfImages;

            TimeSpan processTime = DateTime.Now - startTime;

            Debug.WriteLine(processTime.TotalMilliseconds + " ms to process PDF");
        }
Esempio n. 28
0
 public void Flush()
 {
     if (acts.Count > 0)
     {
         acts.Add(rs.FlushAsync().AsTask().Wait);
         foreach (var w in acts)
         {
             w();
         }
     }
     acts.Clear();
 }
Esempio n. 29
0
        private async void LoadPdfFileAsync(StorageFile selectedFile)
        {
            try
            {
                StorageFile pdfFile = selectedFile;
                //Load Pdf File

                PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile);;
                ObservableCollection <SampleDataItem> items = new ObservableCollection <SampleDataItem>();
                this.DefaultViewModel["Items"] = items;

                if (pdfDocument != null && pdfDocument.PageCount > 0)
                {
                    //Get Pdf page
                    for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++)
                    {
                        var pdfPage = pdfDocument.GetPage((uint)pageIndex);
                        if (pdfPage != null && navigate == false)
                        {
                            // next, generate a bitmap of the page
                            StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
                            StorageFile   pngFile    = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                            if (pngFile != null)
                            {
                                IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite);

                                PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions();
                                pdfPageRenderOptions.DestinationWidth = (uint)(this.ActualWidth - 130);
                                await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions);

                                await randomStream.FlushAsync();

                                if (navigate == false)
                                {
                                    randomStream.Dispose();
                                    pdfPage.Dispose();
                                    items.Add(new SampleDataItem(
                                                  pageIndex.ToString(),
                                                  pageIndex.ToString(),
                                                  pngFile.Path));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
            }
        }
Esempio n. 30
0
        private async void SaveLocalData_Unloaded(object sender, RoutedEventArgs e)
        {
            // Export XML to app local folder
            var folder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var file   = await folder.CreateFileAsync(Strings.ExportFileName, Windows.Storage.CreationCollisionOption.OpenIfExists);

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

            await sched1.DataStorage.ExportAsync(stream.AsStreamForWrite(), C1.C1Schedule.FileFormatEnum.XML);

            await stream.FlushAsync();

            stream.Dispose();
        }
        private async Task Play(IRandomAccessStream buffer)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");

            var storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            if (!string.IsNullOrEmpty(_fileName))
            {
                var oldFile = await storageFolder.GetFileAsync(_fileName);
                await oldFile.DeleteAsync();
            }

            await Dispatcher.RunAsync(
                CoreDispatcherPriority.Normal,
                async () =>
                {
                    var storageFile = await storageFolder.CreateFileAsync(AudioFileName, CreationCollisionOption.GenerateUniqueName);

                    _fileName = storageFile.Name;

                    using (var fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await RandomAccessStream.CopyAndCloseAsync(
                            buffer.GetInputStreamAt(0),
                            fileStream.GetOutputStreamAt(0));

                        await buffer.FlushAsync();
                        buffer.Dispose();
                    }

                    var stream = await storageFile.OpenAsync(FileAccessMode.Read);
                    playBack.SetSource(stream, storageFile.FileType);

                    playBack.Play();
                });
        }
 private async void loadWebViewToStream(WebView webview, IRandomAccessStream stream)
 {
     await Task.Delay(TimeSpan.FromMilliseconds(10));
     await webview.CapturePreviewToStreamAsync(stream);
     await stream.FlushAsync();
     stream.Seek(0);
 }