コード例 #1
0
ファイル: Logger.partial.cs プロジェクト: Valentine1/LG
        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();
                }
            }
        }
コード例 #2
0
        public async void Encode(IRandomAccessStream os)
        {
            await os.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(new byte[] { Convert.ToByte(initCodeSize) })); // write "initial code size" byte

            remaining = imgW * imgH;                                                                                   // reset navigation variables
            curPixel  = 0;

            Compress(initCodeSize + 1, os);                                                 // compress and write the pixel data

            await os.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(new byte[] { 0 })); // write block terminator
        }
コード例 #3
0
        async void Flush(IRandomAccessStream outs)
        {
            if (a_count > 0)
            {
                await outs.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(new byte[] { Convert.ToByte(a_count) }));

                await outs.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(accum, 0, a_count));

                a_count = 0;
            }
        }
コード例 #4
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();
        }
コード例 #5
0
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public async Task SaveImages(Windows.Storage.FileProperties.StorageItemThumbnail thumb, Mediafile file)
        {
            var albumartFolder = ApplicationData.Current.LocalFolder;
            var md5Path        = (file.Album + file.LeadArtist).ToLower().ToSha1();

            if (!File.Exists(albumartFolder.Path + @"\AlbumArts\" + md5Path + ".jpg"))
            {
                IBuffer buf;
                Windows.Storage.Streams.Buffer inputBuffer = new Windows.Storage.Streams.Buffer(1024);
                var albumart = await albumartFolder.CreateFileAsync(@"AlbumArts\" + md5Path + ".jpg", CreationCollisionOption.FailIfExists).AsTask().ConfigureAwait(false);

                using (IRandomAccessStream albumstream = await albumart.OpenAsync(FileAccessMode.ReadWrite).AsTask().ConfigureAwait(false))
                {
                    try
                    {
                        while ((buf = (await thumb.ReadAsync(inputBuffer, inputBuffer.Capacity, Windows.Storage.Streams.InputStreamOptions.None).AsTask().ConfigureAwait(false))).Length > 0)
                        {
                            await albumstream.WriteAsync(buf).AsTask().ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex) { NotificationManager.ShowAsync(ex.Message + "||" + file.Path); }
                }
                thumb.Dispose();
            }
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        public async Task DownloadFile(string path, StorageFile destFile)
        {
            Uri uri = GetUri($"/api/files/{Utils.EncodePath(path)}/download");

            if (uri == null)
            {
                return;
            }

            using (IRandomAccessStream fileStream = await destFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (HttpClient client = GetClient())
                {
                    using (IInputStream downloadStream = await client.GetInputStreamAsync(uri))
                    {
                        const uint capacity = 1_000_000;
                        Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
                        while (true)
                        {
                            await downloadStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                            if (buffer.Length == 0)
                            {
                                break;
                            }
                            await fileStream.WriteAsync(buffer);
                        }
                    }
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public async void SaveImages(Windows.Storage.FileProperties.StorageItemThumbnail thumb, Mediafile file)
        {
            var albumartFolder = ApplicationData.Current.LocalFolder;
            var md5Path        = (file.Album + file.LeadArtist).ToLower().ToSha1();

            if (!File.Exists(albumartFolder.Path + @"\AlbumArts\" + md5Path + ".jpg"))
            {
                IBuffer buf;
                Windows.Storage.Streams.Buffer inputBuffer = new Windows.Storage.Streams.Buffer(1024);
                var albumart = await albumartFolder.CreateFileAsync(@"AlbumArts\" + md5Path + ".jpg", CreationCollisionOption.FailIfExists);

                using (IRandomAccessStream albumstream = await albumart.OpenAsync(FileAccessMode.ReadWrite))
                {
                    while ((buf = (await thumb.ReadAsync(inputBuffer, inputBuffer.Capacity, Windows.Storage.Streams.InputStreamOptions.None))).Length > 0)
                    {
                        await albumstream.WriteAsync(buf);
                    }

                    //try
                    //{
                    //    var data = Data.AttachedPictureFrames["APIC"] as AttachedPictureFrame;
                    //    var stream = data.Data.AsRandomAccessStream();
                    //    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    //    var x = await decoder.GetSoftwareBitmapAsync();
                    //    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, albumstream);
                    //    encoder.SetSoftwareBitmap(x);
                    //    await encoder.FlushAsync();
                    //    stream.Dispose();
                    //}
                    //catch(Exception ex) { Debug.Write(ex.Message + "||" + file.Path); }
                }
                thumb.Dispose();
            }
        }
コード例 #9
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);
            }
        }
コード例 #10
0
        //gets the byte array from the BitmapDecoder
        //
        public async Task LoadFromDecoder(BitmapDecoder decoder)
        {
            this.decoder = decoder;

            //creates the byte array from the decoder
            var imagePixelData = await decoder.GetPixelDataAsync();

            bytes = imagePixelData.DetachPixelData();

            //creates the stream from the byte array
            stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(bytes.AsBuffer());

            stream.Seek(0);

            //creats the bitmapImage from the stream
            image = new BitmapImage();
            image.SetSource(stream);

            //decoder initializes SoftwareBitmap
            softMap = await decoder.GetSoftwareBitmapAsync();

            //gets the pixel width and height of the image
            width  = (int)decoder.PixelWidth;
            height = (int)decoder.PixelHeight;
        }
コード例 #11
0
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public static async Task <bool> SaveAlbumArtsAsync(StorageFile file, Mediafile mediafile)
        {
            var albumArt = AlbumArtFileExists(mediafile);

            if (!albumArt.NotExists)
            {
                return(false);
            }

            try
            {
                using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 512, ThumbnailOptions.ReturnOnlyIfCached))
                {
                    if (thumbnail == null && file.IsAvailable)
                    {
                        using (TagLib.File tagFile = TagLib.File.Create(new SimpleFileAbstraction(file), TagLib.ReadStyle.Average))
                        {
                            if (tagFile.Tag.Pictures.Length >= 1)
                            {
                                var image = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"AlbumArts\" + albumArt.FileName + ".jpg", CreationCollisionOption.FailIfExists);

                                using (FileStream stream = new FileStream(image.Path, FileMode.Open, FileAccess.Write, FileShare.None, 51200, FileOptions.WriteThrough))
                                {
                                    await stream.WriteAsync(tagFile.Tag.Pictures[0].Data.Data, 0, tagFile.Tag.Pictures[0].Data.Data.Length);
                                }
                                return(true);
                            }
                        }
                    }
                    else if (thumbnail != null)
                    {
                        var albumart = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"AlbumArts\" + albumArt.FileName + ".jpg", CreationCollisionOption.FailIfExists);

                        IBuffer buf;
                        Windows.Storage.Streams.Buffer inputBuffer = new Windows.Storage.Streams.Buffer((uint)thumbnail.Size / 2);
                        using (IRandomAccessStream albumstream = await albumart.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            while ((buf = await thumbnail.ReadAsync(inputBuffer, inputBuffer.Capacity, InputStreamOptions.ReadAhead)).Length > 0)
                            {
                                await albumstream.WriteAsync(buf);
                            }

                            return(true);
                        }
                    }
                }
            }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
            catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
            {
                //await SharedLogic.Instance.NotificationManager.ShowMessageAsync(ex.Message + "||" + file.Path);
            }

            return(false);
        }
コード例 #12
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);
        }
コード例 #13
0
        private async Task SaveItemToLocalStorage(MediaItem serverItem, byte[] transferredData)
        {
            StorageFolder folder  = ApplicationData.Current.TemporaryFolder;
            StorageFile   newFile = await folder.CreateFileAsync(serverItem.Name, CreationCollisionOption.FailIfExists);

            using (IRandomAccessStream stream = await newFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.AllowReadersAndWriters))
            {
                IBuffer buffer = transferredData.AsBuffer();
                await stream.WriteAsync(buffer);
            }
        }
コード例 #14
0
ファイル: Downloader.cs プロジェクト: yoavfr/podcatcher
        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);
        }
コード例 #15
0
        private async Task WriteLines()
        {
            while (Queue.Count != 0)
            {
                try
                {
                    _semaphore.WaitOne();
                    await CheckFileInitialization();

                    using (IRandomAccessStream stream = await _storageFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.AllowOnlyReaders))
                    {
                        stream.Seek(stream.Size);
                        for (int i = 0; i < 10 && Queue.Count != 0; i++)
                        {
                            if (!string.IsNullOrEmpty(Queue[0]))
                            {
                                await stream.WriteAsync(CryptographicBuffer.ConvertStringToBinary(Queue[0], BinaryStringEncoding.Utf8));

                                await stream.WriteAsync(LINE_END);

                                await stream.FlushAsync();
                            }
                            Queue.RemoveAt(0);
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("Error while writing", e);
                }
                finally
                {
                    Logger.Trace("Write end");
                    _semaphore.Release();
                }
            }

            _runningTask = null;
            QueueEmpty?.Invoke();
        }
コード例 #16
0
        private async Task ReadMediaFileAsync(DataReader reader)
        {
            //a media file will always start with an int32 containing the file length
            await reader.LoadAsync(sizeof(int));

            int messageLength = reader.ReadInt32();

            Debug.WriteLine("Message Length " + messageLength);

            _totalBytesRead = 0;
            uint    bytesRead  = 0;
            IBuffer readBuffer = new Windows.Storage.Streams.Buffer(MAX_PACKET_SIZE);

            // read as many blocks as are in the incoming stream - this prevents blocks getting dropped
            do
            {
                await reader.LoadAsync(sizeof(int));

                int partNumber = reader.ReadInt32();
                Debug.WriteLine("Part " + partNumber);

                readBuffer = await _socket.InputStream.ReadAsync(readBuffer, MAX_PACKET_SIZE,
                                                                 InputStreamOptions.Partial);

                bytesRead = readBuffer.Length;
                Debug.WriteLine("Bytes read " + bytesRead);

                if (bytesRead > 0)
                {
                    _incomingStream.WriteAsync(readBuffer).GetResults();
                    _totalBytesRead += bytesRead;
                }
                Debug.WriteLine("Total bytes read: " + _totalBytesRead);
            }while (_totalBytesRead < messageLength);

            Debug.WriteLine("Incoming stream length " + _incomingStream.Size);

            if (_totalBytesRead >= messageLength)
            {
                if (_writer == null)
                {
                    _writer = new DataWriter(_socket.OutputStream);
                }

                _writer.WriteUInt16((UInt16)MessageType.Ready);
                await _writer.StoreAsync();

                messageLength = 0;
            }
        }
コード例 #17
0
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public static async Task <bool> SaveAlbumArtsAsync(StorageFile file, Mediafile mediafile)
        {
            var albumArt = AlbumArtFileExists(mediafile);

            if (!albumArt.NotExists)
            {
                return(false);
            }

            try
            {
                using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 300, ThumbnailOptions.UseCurrentScale))
                {
                    if (thumbnail == null)
                    {
                        return(false);
                    }

                    switch (thumbnail.Type)
                    {
                    case ThumbnailType.Image:
                        var albumart = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"AlbumArts\" + albumArt.FileName + ".jpg", CreationCollisionOption.FailIfExists);

                        IBuffer buf;
                        Windows.Storage.Streams.Buffer inputBuffer = new Windows.Storage.Streams.Buffer(1024);
                        using (IRandomAccessStream albumstream = await albumart.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            while ((buf = await thumbnail.ReadAsync(inputBuffer, inputBuffer.Capacity, InputStreamOptions.None)).Length > 0)
                            {
                                await albumstream.WriteAsync(buf);
                            }

                            return(true);
                        }

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                await SharedLogic.NotificationManager.ShowMessageAsync(ex.Message + "||" + file.Path);
            }

            return(false);
        }
コード例 #18
0
        /// <summary>
        /// Saves the local image buffer to the the given file.
        /// </summary>
        /// <param name="file">The file where to save the image buffer.</param>
        /// <returns>True if successful, false otherwise.</returns>
        private async Task <bool> SaveImageFileAsync(StorageFile file)
        {
            bool success = false;

            try
            {
                using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    if (_imageBufferToSave != null)
                    {
                        await fileStream.WriteAsync(_imageBufferToSave);

                        await fileStream.FlushAsync();
                    }
                    else if (_writeableBitmapToSave != null)
                    {
                        Guid          bitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                        BitmapEncoder encoder           = await BitmapEncoder.CreateAsync(bitmapEncoderGuid, fileStream);

                        Stream pixelStream = _writeableBitmapToSave.PixelBuffer.AsStream();
                        byte[] pixelArray  = new byte[pixelStream.Length];
                        await pixelStream.ReadAsync(pixelArray, 0, pixelArray.Length);

                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                             (uint)_writeableBitmapToSave.PixelWidth,
                                             (uint)_writeableBitmapToSave.PixelHeight,
                                             96.0,
                                             96.0,
                                             pixelArray);
                        await encoder.FlushAsync();
                    }
                    else
                    {
                        throw new Exception("No data to save");
                    }
                }

                success = true;
            }
            catch (Exception)
            {
            }

            _writeableBitmapToSave = null;
            _imageBufferToSave     = null;
            return(success);
        }
コード例 #19
0
        /// <summary>
        /// Write the contents of stream to filename in the cache location. If a null stream is provided, the file is created with no contents.
        /// </summary>
        /// <param name="stream">Content to be written to file</param>
        /// <param name="filename">Name of the file to be written in cache location</param>
        private static async Task WriteFileAsync(Stream stream, string filename)
        {
            // Prepare output file stream
            StorageFolder parent = GetCacheFolder();
            StorageFile   file   = null;

            try
            {
                file = await parent.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            }
            catch (Exception)
            {
            }
            if (file != null && stream != null)
            {
                // Prepare input image stream
                IInputStream        inStream   = stream.AsInputStream();
                DataReader          reader     = new DataReader(inStream);
                IRandomAccessStream fileStream = null;
                try
                {
                    fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                    // Buffered write to file
                    await reader.LoadAsync(1024);

                    while (reader.UnconsumedBufferLength > 0)
                    {
                        await fileStream.WriteAsync(reader.ReadBuffer(reader.UnconsumedBufferLength));

                        await reader.LoadAsync(1024);
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (fileStream != null)
                    {
                        await fileStream.FlushAsync();
                    }
                }
                inStream.Dispose();
            }
        }
コード例 #20
0
ファイル: MapDLHelper.cs プロジェクト: pnp0a03/WinGo-Maps
        /// <summary>
        /// Fetch links and save them to file
        /// </summary>
        /// <param name="href">Tile link to download</param>
        /// <param name="filename">Filename to save on storage</param>
        /// <returns>acknowledge of downloading file</returns>
        private async Task <bool> Download(String href, String filename)
        {
            //mkdir if folder not existed
            StorageFile file = null;

            try
            {
                file = await MapFolder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists);
            }
            catch { /* Already Downloaded */ return(true); }

            IRandomAccessStream outp = null;

            try
            {
                var url = new Uri(href);
                outp = (await file.OpenAsync(FileAccessMode.ReadWrite));
                var http = new HttpClient();
                http.DefaultRequestHeaders.Accept.ParseAdd("text/html, application/xhtml+xml, image/jxr, */*");
                http.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.7,fa;q=0.3");
                http.DefaultRequestHeaders.Cookie.ParseAdd($"IP_JAR={DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}-21");
                http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AppCore.HttpUserAgent}");
                var res = await http.GetAsync(url);

                var buffer = await res.Content.ReadAsBufferAsync();

                if (buffer.Length == 0)
                {
                    throw new Exception();
                }
                await outp.WriteAsync(buffer);

                buffer.AsStream().Dispose();
                outp.Dispose();
                return(true);
            }
            catch
            {
                await file.DeleteAsync();

                FailedDownloads++;
                //ex.Message();
                return(false);
            }
        }
コード例 #21
0
ファイル: Cache.cs プロジェクト: delavet/HelperUWP
        public static async Task saveBufferToFile(IBuffer buffer, String filename)
        {
            try
            {
                StorageFolder local    = Windows.Storage.ApplicationData.Current.LocalCacheFolder;
                StorageFile   new_file = await local.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream stream = await new_file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await stream.WriteAsync(buffer);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.StackTrace);
            }

            return;
        }
コード例 #22
0
        public async Task AddAsyc(ICanvasBitmapTile tile, IRandomAccessStream tileData)
        {
            StorageFolder folder = await OpenFolder(tile).ConfigureAwait(false);

            string      filename = string.Format(CultureInfo.InvariantCulture, "{0}.tile", tile.CacheKey);
            StorageFile file     = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false);

            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite).AsTask().ConfigureAwait(false))
            {
                Buffer buffer = new Buffer(1024 * 1024);
                bool   eof    = false;
                while (!eof)
                {
                    IBuffer readBuffer = await tileData.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial).AsTask().ConfigureAwait(false);

                    await fileStream.WriteAsync(readBuffer).AsTask().ConfigureAwait(false);

                    eof = readBuffer.Length < readBuffer.Capacity;
                }
                await fileStream.FlushAsync();
            }
        }
コード例 #23
0
ファイル: FTPClient.cs プロジェクト: zyangpointer/SDK
        /// <summary>
        /// Download a single file from FTP server using WebRequest.
        /// </summary>
        public static async Task <DownloadCompletedEventArgs> DownloadFTPFileAsync(FTPFileSystem item,
                                                                                   StorageFile targetFile, ICredentials credential)
        {
            var result = new DownloadCompletedEventArgs
            {
                RequestFile = item.Url,
                LocalFile   = targetFile,
                Error       = null
            };

            // This request is FtpWebRequest in fact.
            WebRequest request = WebRequest.Create(item.Url);

            if (credential != null)
            {
                request.Credentials = credential;
            }

            request.Proxy = WebRequest.DefaultWebProxy;

            // Set the method to Download File
            request.Method = "RETR";
            try
            {
                // Open the file for write.
                using (IRandomAccessStream fileStream =
                           await targetFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // Get response.
                    using (WebResponse response = await request.GetResponseAsync())
                    {
                        // Get response stream.
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            byte[] downloadBuffer = new byte[2048];
                            int    bytesSize      = 0;

                            // Download the file until the download is completed.
                            while (true)
                            {
                                // Read a buffer of data from the stream.
                                bytesSize = responseStream.Read(downloadBuffer, 0,
                                                                downloadBuffer.Length);
                                if (bytesSize == 0)
                                {
                                    break;
                                }

                                // Write buffer to the file.
                                await fileStream.WriteAsync(downloadBuffer.AsBuffer());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Error = ex;
            }

            return(result);
        }
コード例 #24
0
ファイル: HTTPHelper.cs プロジェクト: suwakowww/CodeHub
        public static async Task <IBuffer> GetBufferFromUrlAsync([NotNull] String url, CancellationToken token)
        {
            // URL check
            if (String.IsNullOrEmpty(url))
            {
                return(null);
            }

            // Loop to make sure to retry once if the existing cached file is invalid
            while (true)
            {
                // Input check
                if (token.IsCancellationRequested)
                {
                    return(null);
                }

                // Get the filename for the cache storage
                byte[]      bytes = Encoding.Unicode.GetBytes(url);
                IBuffer     hash = HashProvider.HashData(bytes.AsBuffer());
                String      hex = CryptographicBuffer.EncodeToHexString(hash), cacheFilename = $"{hex}{CacheExtension}";
                StorageFile file = await ApplicationData.Current.LocalCacheFolder.TryGetItemAsync(cacheFilename) as StorageFile;

                // Check the cache result
                if (file == null)
                {
                    // Try to get the remote buffer
                    IBuffer buffer = await DownloadDataAsync(url, token);

                    if (buffer == null)
                    {
                        return(null);
                    }

                    // Save the buffer if possible
                    StorageFile cacheFile = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(cacheFilename, CreationCollisionOption.OpenIfExists);

                    using (IRandomAccessStream outputStream = await cacheFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await outputStream.WriteAsync(buffer);

                        return(buffer);
                    }
                }

                // Load the buffer from the cached file
                if (token.IsCancellationRequested)
                {
                    return(null);
                }
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    try
                    {
                        byte[] data = new byte[stream.Size];
                        return(await stream.ReadAsync(data.AsBuffer(), (uint)data.Length, InputStreamOptions.None));
                    }
                    catch
                    {
                        // Invalid file
                    }
                }

                // Delete the cached file
                try
                {
                    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                }
                catch
                {
                    return(null);
                }
            }
        }
コード例 #25
0
ファイル: Print3D.cs プロジェクト: ice0/test
 public IAsyncOperationWithProgress <UInt32, UInt32> WriteAsync(IBuffer buffer)
 {
     return(_stream.WriteAsync(buffer));
 }
コード例 #26
0
 public IAsyncOperationWithProgress <uint, uint> WriteAsync(IBuffer buffer)
 {
     return(_randomAccessStream.WriteAsync(buffer));
 }
コード例 #27
0
ファイル: WebSocket.cs プロジェクト: mixedworld/WebSocket.UWP
        private async Task ProcessIncomingFrame(FrameParser.Frame frame)
        {
            switch (frame.opCode)
            {
            case FrameParser.OP_CONTINUATION:
                await _stream.WriteAsync(frame.payload?.ToBuffer());

                if (frame.isFinal)
                {
                    var    buffer  = _stream.ToBuffer();
                    byte[] message = buffer.ToByteArray();
                    if (this.OnMessage != null)
                    {
                        this.OnMessage(this, new WebSocketMessageEventArgs(this.Control.MessageType, message));
                    }
                    this.ResetStream();
                }
                break;

            case FrameParser.OP_TEXT:
                if (frame.isFinal)
                {
                    if (this.OnMessage != null)
                    {
                        this.OnMessage(this, new WebSocketMessageEventArgs(this.Control.MessageType, frame.payload));
                    }
                }
                else
                {
                    if (_stream.Size != 0)
                    {
                        throw new IOException("no FIN frame");
                    }
                    this.Control.MessageType = WebSocketMessageType.Text;
                    await _stream.WriteAsync(frame.payload.ToBuffer());
                }
                break;

            case FrameParser.OP_BINARY:
                if (frame.isFinal)
                {
                    if (this.OnMessage != null)
                    {
                        this.OnMessage(this, new WebSocketMessageEventArgs(this.Control.MessageType, frame.payload));
                    }
                }
                else
                {
                    if (_stream.Size != 0)
                    {
                        throw new IOException("no FIN frame");
                    }
                    this.Control.MessageType = WebSocketMessageType.Binary;
                    await _stream.WriteAsync(frame.payload.ToBuffer());
                }
                break;

            case FrameParser.OP_CLOSE:
                int code = 0;
                if (frame.payload.Length >= 2)
                {
                    code = ((frame.payload[0] << 8) | (frame.payload[1] & 0xFF)) & 0xFFFF;
                }
                string reason = null;
                if (frame.payload.Length > 2)
                {
                    var temp = frame.payload.CopyOfRange(2, frame.payload.Length);
                    reason = Encoding.UTF8.GetString(temp, 0, temp.Length);
                }
                if (this.Closed != null)
                {
                    this.Closed(this, new WebSocketClosedEventArgs(code, reason));
                }
                this.Disconnect();
                break;

            case FrameParser.OP_PING:
                if (frame.payload.Length > 125)
                {
                    throw new IOException("Ping payload too large");
                }
                byte[] data = FrameParser.BuildFrame(frame.payload, FrameParser.OP_PONG, -1, IS_CLIENT, true);
                await SendFrame(data);

                break;

            case FrameParser.OP_PONG:
                if (this.OnPong != null)
                {
                    this.OnPong(this, frame.payload);
                }
                break;
            }
        }
コード例 #28
0
 private async Task SendDataToProxy(string data)
 {
     byte[]  buffer  = Encoding.ASCII.GetBytes(data);
     IBuffer ibuffer = buffer.AsBuffer();
     await standardInput.WriteAsync(ibuffer);
 }
コード例 #29
0
 public IAsyncOperationWithProgress <uint, uint> WriteAsync(IBuffer buffer)
 => _stream.WriteAsync(buffer);