Exemplo n.º 1
1
        public static async Task<long> CopyStreamsAsyncParallel(Stream src, Stream dst)
        {
            long numCopied = 0;
            byte[][] buffer = new byte[2][];
            buffer[0] = new byte[0x1000];
            buffer[1] = new byte[0x1000];

            var index = 0;
            int numRead = await src.ReadAsync(buffer[index], 0, buffer[index].Length);

            while (numRead > 0)
            {
                var writeAsync = dst.WriteAsync(buffer[index], 0, numRead);
                index = index ^= 1;
                var readAsync = src.ReadAsync(buffer[index], 0, buffer[index].Length);

                Task.WaitAll(writeAsync, readAsync);
                numRead = readAsync.Result;

                numCopied += numRead;
            }
            await dst.FlushAsync();
            src.Dispose();
            dst.Dispose();

            return numCopied;

        }
 public async Task SaveFile(string name, Stream stream)
 {
     var fullPath = GetFullPath(name);
     using (var fs = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.Write))
     {
         await stream.CopyToAsync(fs).ConfigureAwait(false);
         await stream.FlushAsync().ConfigureAwait(false);
         await fs.FlushAsync().ConfigureAwait(false);
     }
 }
        public async Task WriteFrameAsync(PcapFrame frame, bool flush)
        {
            Tuple <uint, uint> secondsMicroseconds = this.GetSecondsMicrosecondsTuple(frame.Timestamp);

            await this.writeLock.WaitAsync();

            try {
                await outputStream.WriteAsync(ToByteArray(secondsMicroseconds.Item1), 0, 4);

                await outputStream.WriteAsync(ToByteArray(secondsMicroseconds.Item2), 0, 4);

                //number of octets of packet saved in file
                await outputStream.WriteAsync(ToByteArray((uint)frame.Data.Length), 0, 4);

                //actual length of packet
                await outputStream.WriteAsync(ToByteArray((uint)frame.Data.Length), 0, 4);

                //data
                await outputStream.WriteAsync(frame.Data, 0, frame.Data.Length);

                if (flush)
                {
                    await outputStream.FlushAsync();
                }
            }
            finally {
                this.writeLock.Release();
            }
            FramesWritten++;
        }
        public static async Task<long> CopyWithProgressAsync(this Stream source, Stream destination,
            ProgressReportDelegate progressReport = null, long sourceLength = 0, int bufferSize = 64 * 1024)
        {
            long bytesWritten = 0;
            long totalBytesToWrite = sourceLength;

            byte[] copy_buffer = new byte[bufferSize];
            int read;
            while ((read = await source.ReadAsync(copy_buffer, 0, copy_buffer.Length)) > 0)
            {
                await destination.WriteAsync(copy_buffer, 0, read);
                bytesWritten += read;

                System.Diagnostics.Debug.WriteLine("CopyWithProgress: {0} / {1}", bytesWritten, totalBytesToWrite);
                if (null != progressReport)
                {
                    int percentComplete = 0;
                    if (sourceLength > 0)
                        percentComplete = (int)((bytesWritten/(double)totalBytesToWrite) * 100);    
                    progressReport(percentComplete, bytesWritten, totalBytesToWrite);
                }
            }

            await destination.FlushAsync();

            return bytesWritten;
        }
Exemplo n.º 5
0
 public void SendOverStream(Stream stream, Notification value)
 {
     byte[] data = ServiceManager.Serializer.Serialize(value);
     byte[] dataLength = BitConverter.GetBytes(data.Length);
     stream.Write(dataLength, 0, dataLength.Length);
     stream.Write(data, 0, data.Length);
     stream.FlushAsync();
 }
 private static async Task WriteRequest(byte[] message, Stream tcpStream)
 {
     var lengthBigEndian = BitConverter.GetBytes(message.Length);
     Array.Reverse(lengthBigEndian);
     tcpStream.Write(lengthBigEndian, 0, lengthBigEndian.Length);
     tcpStream.Write(message, 0, message.Length);
     await tcpStream.FlushAsync();
 }
Exemplo n.º 7
0
        /// <summary>
        /// Write and PNG file out to a file stream.  Currently compression is not supported.
        /// </summary>
        /// <param name="image">The WriteableBitmap to work on.</param>
        /// <param name="stream">The destination file stream.</param>
        /// <param name="compression">Level of compression to use (-1=auto, 0=none, 1-100 is percentage).</param>
        public async static Task WritePNG(WriteableBitmap image, System.IO.Stream stream, int compression)
        {
            // Set the global class variables for the image and stream.
            _image  = image;
            _stream = stream;

            // Write the png header.
            stream.Write(
                new byte[]
            {
                0x89, 0x50, 0x4E, 0x47,
                0x0D, 0x0A, 0x1A, 0x0A
            }, 0, 8);

            // Set the PNG header values for this image.
            var header = new PngHeader
            {
                Width             = image.PixelWidth,
                Height            = image.PixelHeight,
                ColorType         = 6,
                BitDepth          = 8,
                FilterMethod      = 0,
                CompressionMethod = 0,
                InterlaceMethod   = 0
            };

            // Write out the header.
            await WriteHeaderChunk(header);

            // Write out the rest of the mandatory fields to the PNG.
            await WritePhysicsChunk();
            await WriteGammaChunk();

            // Currently only uncompressed PNG's are supported, so this if statement really doesn't do anything ;).
            if (compression == -1)
            {
                // Autodetect compression setting
                await WriteDataChunksUncompressed();
            }
            else if (compression == 0)
            {
                // Write PNG without any compression
                await WriteDataChunksUncompressed();
            }
            else
            {
                // Write the PNG with a desired compression level
                await WriteDataChunks(compression);
            }

            // Write out the end of the PNG.
            await WriteEndChunk();

            // Flush the stream to make sure it's all written.
            await stream.FlushAsync();
        }
Exemplo n.º 8
0
 public static async Task CopyToAsync(this Stream source, Stream destination, IProgress<long> progress, CancellationToken cancellationToken) {
     byte[] buffer = new byte[81920];
     int bytesRead = 0;
     long bytesTotal = 0;
     while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) > 0) {
         await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken);
         bytesTotal += bytesRead;
         progress?.Report(bytesTotal);
     }
     await destination.FlushAsync(cancellationToken);
 }
Exemplo n.º 9
0
        private static async Task DelimWriteBufferedAsync(System.IO.Stream stream, byte[] message, CancellationToken cancellationToken)
        {
            using (var buffer = new MemoryStream())
            {
                await DelimWriteAsync(buffer, message, cancellationToken).ConfigureAwait(false);

                buffer.Seek(0, SeekOrigin.Begin);
                await buffer.CopyToAsync(stream, 4096, cancellationToken).ConfigureAwait(false);
            }
            await stream.FlushAsync(cancellationToken);
        }
Exemplo n.º 10
0
 public async Task ZipCatrobatPackage(Stream zipStream, string localStoragePath)
 {
     using (var storage = StorageSystem.GetStorage())
     {
         using(var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
         {
             await WriteFilesRecursiveToZip(archive, storage, localStoragePath, "");
             await zipStream.FlushAsync();
         }
     }
     //ZipFile.CreateFromDirectory(localStoragePath, zipPath, CompressionLevel.Fastest, true);
 }
        public async Task DownloadAsync(Uri uri, Stream destination, CancellationToken cancelToken)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            using (Stream stream = await m_client.GetStreamAsync(uri))
            {
                await stream.CopyToAsync(destination, 4096, cancelToken);
                await destination.FlushAsync();
            }
        }
Exemplo n.º 12
0
        public override void Flush()
        {
#if NETFX_CORE
            var task = stream.FlushAsync();
            task.Wait();
            if (task.IsFaulted)
            {
                throw task.Exception;
            }
#else
            stream.Flush();
#endif
        }
Exemplo n.º 13
0
 public async static Task ToStreamMaxJPEGAsync(this Image iImage,
     Stream iStream)
 {
     using (EncoderParameters pEPsParams = new EncoderParameters(1))
     {
         EncoderParameter pEPrParam = new EncoderParameter(Encoder.Quality, 100L);
         pEPsParams.Param[0] = pEPrParam;
         using (Bitmap pBmpCopy = new Bitmap(iImage))
         {
             pBmpCopy.Save(iStream, GetEncoder(ImageFormat.Jpeg), pEPsParams);
         }
         await iStream.FlushAsync();
     }
 }
Exemplo n.º 14
0
        public async Task ConnectAsync()
        {
            _tcpClient.NoDelay = true;
            await _tcpClient.ConnectAsync(_host, _port);

            _stream = _tcpClient.GetStream();
            await _stream.WriteAsync(TcpConstants.MagicCookie, 0, TcpConstants.MagicCookie.Length);
            await _stream.FlushAsync();

            ModData = await _stream.ReadObjectAsync<ModData>();

            _isConnected = true;
            var spawnedTask = Task.Run(() => RunChannel());
        }
        private async Task copyStreamAsync(System.IO.Stream input, System.IO.Stream output, int bufferSize)
        {
            byte[] buffer;
            int    len;

            buffer = new byte[bufferSize];

            while ((len = await input.ReadAsync(buffer, 0, bufferSize)) > 0)
            {
                await output.WriteAsync(buffer, 0, len);
            }

            await output.FlushAsync();
        }
Exemplo n.º 16
0
        private async Task SendHeaders(Uri url)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("GET / HTTP/1.1");
            sb.AppendLine("Connection: keep-alive");
            sb.AppendLine("Host: " + url.Host);
            sb.AppendLine("icy-metadata: 0");
            sb.AppendLine();

            outStream = underlayingSocket.OutputStream.AsStreamForWrite();

            var bytes = System.Text.UTF8Encoding.UTF8.GetBytes(sb.ToString());

            await outStream.WriteAsync(bytes, 0, bytes.Length);
            await outStream.FlushAsync();
        }
        private async Task OnCreate()
        {
            var result = await this.signatureService.Request();

            if (result.Cancelled)
            {
                await App.Current.MainPage.DisplayAlert(null, "Canceled Signature", "Close");
            }
            else
            {
                //Grab the configured image type
                var imageType = signatureService.GetConfiguration().ImageType;

                var  fileName = String.Format(FILE_FORMAT, DateTime.Now, imageType.ToString().ToLower());
                long fileSize;

                IFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (var image = result.GetStream())
                {
                    using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            image.CopyTo(ms);

                            byte[] buffer = ms.ToArray();
                            stream.Write(buffer, 0, buffer.Length);
                            fileSize = buffer.Length;
                            await stream.FlushAsync();
                        }
                    }
                }

                this.List.Add(new Signature
                {
                    FilePath = file.Path,
                    FileName = file.Name,
                    FileSize = fileSize
                });

                await App.Current.MainPage.DisplayAlert(null, String.Format("Draw Points: {0}", result.Points.Count()), "Close");

                this.NoData = !this.List.Any();
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Writes Packet to a stream Asynchronously
        /// </summary>
        /// <param name="stream">The stream to write to</param>
        /// <param name="flush">Flush the streams buffer</param>
        /// <param name="token">Cancellation token</param>
        /// <remarks>Known to freeze randomly so using the synchronously version is currently reccomended</remarks>
        public async Task WriteAsync(Stream stream, bool flush = true, CancellationToken token = default(CancellationToken))
        {
            if (!stream.CanWrite)
                throw new XpressNetProtocolViolationException("Unable to write to stream");

            var buffer = new List<byte>();

            buffer.Add(HeaderByte);

            buffer.AddRange(Payload);

            buffer.Add(GetXoredByte());

            await stream.WriteAsync(buffer.ToArray(), 0, buffer.Count, token);

            if (flush)
            {
                await stream.FlushAsync(token);
                LogPacketWrite();
            }
        }
Exemplo n.º 19
0
        public async Task WriteToStream(Stream stream)
        {
            var bodyArray = Encoding.UTF8.GetBytes(Content);
            var contentStream = new MemoryStream(bodyArray);

            var headerBuilder = new StringBuilder();
            headerBuilder.AppendLine($"HTTP/1.1 {(int)StatusCode} {StatusCode}");
            headerBuilder.AppendLine("Server: catnap-srv/1.0.0");

            foreach (var header in Headers)
            {
                headerBuilder.AppendLine($"{header.Key}: {header.Value}");
            }

            headerBuilder.AppendLine($"Content-Length: {contentStream.Length}");
            headerBuilder.AppendLine("Connection: close");
            headerBuilder.AppendLine();

            var headerArray = Encoding.UTF8.GetBytes(headerBuilder.ToString());
            await stream.WriteAsync(headerArray, 0, headerArray.Length);
            await contentStream.CopyToAsync(stream);
            await stream.FlushAsync();
        }
        internal async Task PlayTweetAsync(IAudioClient client, string text, string voiceName, string languageCode)
        {
            using Stream discord      = client.CreatePCMStream(AudioApplication.Mixed);
            using MemoryStream buffer = new MemoryStream();

            try
            {
                await GetTweetAudioAsync(text,
                                         voiceName,
                                         languageCode,
                                         buffer);

                buffer.Seek(0, SeekOrigin.Begin);
                await buffer.CopyToAsync(discord);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Exception when reading Tweet");
            }
            finally
            {
                await discord.FlushAsync();
            }
        }
Exemplo n.º 21
0
        public async Task SaveBinary(string fName, Stream stream)
        {
            try
            {
                IFolder rootFolder = FileSystem.Current.LocalStorage;//;
                IFolder folder = await rootFolder.CreateFolderAsync("Settings", CreationCollisionOption.OpenIfExists, CancellationToken.None);
                IFile file = await folder.CreateFileAsync(fName, CreationCollisionOption.ReplaceExisting, CancellationToken.None);
                var t = file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite, CancellationToken.None);
                using (Stream s = await t)
                {
                    await stream.CopyToAsync(s);
                    await stream.FlushAsync();
                    s.Dispose();
                    stream.Dispose();
                }

                //stream.Dispose ();
                //s.Dispose ();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="type"></param>
 /// <param name="value"></param>
 /// <param name="writeStream"></param>
 /// <param name="content"></param>
 /// <param name="transportContext"></param>
 /// <returns></returns>
 public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
 {
     Serializer.Serialize(value, writeStream);
     return writeStream.FlushAsync();
 }
Exemplo n.º 23
0
    private static async Task FlushAsyncInternal(CancellationToken cancellationToken,
                                                 BufferedStream _this, Stream stream, Int32 writePos, Int32 readPos, Int32 readLen) {
        
        // We bring instance fields down as local parameters to this async method becasue BufferedStream is derived from MarshalByRefObject.
        // Field access would be from the async state machine i.e., not via the this pointer and would require runtime checking to see
        // if we are talking to a remote object, which is currently very slow 

        Contract.Assert(stream != null);        
        
        SemaphoreSlim sem = _this.EnsureAsyncActiveSemaphoreInitialized();
        await sem.WaitAsync().ConfigureAwait(false);
        try {

            if (writePos > 0) {

                await _this.FlushWriteAsync(cancellationToken).ConfigureAwait(false);
                Contract.Assert(_this._writePos == 0 && _this._readPos == 0 && _this._readLen == 0);
                return;
            }        

            if (readPos < readLen) {

                // If the underlying stream is not seekable AND we have something in the read buffer, then FlushRead would throw.
                // We can either throw away the buffer resulting in date loss (!) or ignore the Flush. (We cannot throw becasue it
                // would be a breaking change.) We opt into ignoring the Flush in that situation.
                if (!stream.CanSeek)
                    return;                                   

                _this.FlushRead();  // not async; it uses Seek, but there's no SeekAsync

                // User streams may have opted to throw from Flush if CanWrite is false (although the abstract Stream does not do so).
                // However, if we do not forward the Flush to the underlying stream, we may have problems when chaining several streams.
                // Let us make a best effort attempt:
                if (stream.CanRead || stream is BufferedStream)
                    await stream.FlushAsync(cancellationToken).ConfigureAwait(false);

                Contract.Assert(_this._writePos == 0 && _this._readPos == 0 && _this._readLen == 0);
                return;
            }            

            // We had no data in the buffer, but we still need to tell the underlying stream to flush.
            if (stream.CanWrite || stream is BufferedStream)
                await stream.FlushAsync(cancellationToken).ConfigureAwait(false);

            // There was nothing in the buffer:
            Contract.Assert(_this._writePos == 0 && _this._readPos == _this._readLen);

        } finally {
            sem.Release();
        }
    }
Exemplo n.º 24
0
 public static IAsyncOperation <bool> FlushAsyncOperation(this Stream stream)
 => AsyncOperation.FromTask(async ct =>
 {
     await stream.FlushAsync(ct);
     return(true);
 });
Exemplo n.º 25
0
            public async Task<bool> WriteAsync(Stream stream, byte[] buffer, TimeSpan initialDelay, int chunkSize, TimeSpan writeDelay, int[] writePermutation = null, bool flush = true)
            {
                Console.WriteLine($"{nameof(WriteAsync)} Start");

                if (writePermutation == null)
                    writePermutation = Enumerable.Range(0, buffer.Length / chunkSize).ToArray();

                await Task.Delay(initialDelay);

                var volume = 0;
                for (int i = 0; volume < buffer.Length; ++i) {
                    stream.Position = writePermutation[i] * chunkSize;
                    await stream.WriteAsync(buffer, writePermutation[i] * chunkSize, chunkSize);
                    volume += chunkSize;
                    Console.WriteLine($"{nameof(WriteAsync)}[{writePermutation[i] * chunkSize}] -> {chunkSize}");
                    await Task.Delay(writeDelay);
                }

                if (flush) {
                    Console.WriteLine($"{nameof(WriteAsync)} Flush");
                    await stream.FlushAsync();
                }

                Console.WriteLine($"{nameof(WriteAsync)} End");

                return true;
            }
Exemplo n.º 26
0
 private async Task FlushRegularly(Stream stream, int intervalMs, Task interrupt)
 {
     try
     {
         Task awoken;
         do
         {
             awoken = await Task.WhenAny(Task.Delay(intervalMs), interrupt);
             await stream.FlushAsync();
         } while (awoken != interrupt);
     }
     catch (Exception e)
     {
         logger.Log("Flusher caught exception " + e.ToString());
     }
 }
Exemplo n.º 27
0
 public override Task FlushAsync(CancellationToken cancellationToken) => _stream.FlushAsync(cancellationToken);
Exemplo n.º 28
0
 /// <summary>
 /// Sends a string message over stream.
 /// </summary>
 /// <param name="stream">Stream to send message to.</param>
 /// <param name="buffer">A byte array to streamline bit shuffling.</param>
 /// <param name="message">Text to transmit.</param>
 public async static Task SendStreamStringAsync(Stream stream, byte[] buffer, string message)
 {
     Buffer.BlockCopy(Encoding.UTF8.GetBytes(message), 0, buffer, 0, message.Length);
     await stream.WriteAsync(buffer, 0, message.Length);
     await stream.FlushAsync();
 }
Exemplo n.º 29
0
        }  // WriteAsync_AbstractStream

        #endregion WriteAsync implementations


        #region FlushAsync implementations

        internal static IAsyncOperation<Boolean> FlushAsync_AbstractStream(Stream stream)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream.CanWrite);
            Contract.EndContractBlock();

            Func<CancellationToken, Task<Boolean>> flushOperation = async (cancelToken) =>
            {
                if (cancelToken.IsCancellationRequested)  // CancellationToken is non-nullable
                    return false;

                await stream.FlushAsync(cancelToken).ConfigureAwait(continueOnCapturedContext: false);
                return true;
            };

            // Construct and run the async operation:
            return AsyncInfo.Run<Boolean>(flushOperation);
        }
Exemplo n.º 30
0
 public async Task DownloadToStream(Stream stream, string hash)
 {
     var blobRef = Container.GetBlockBlobReference(hash);
     await blobRef.DownloadToStreamAsync(stream);
     await stream.FlushAsync();
 }
Exemplo n.º 31
0
 public async Task UploadResizedBlob(Stream stream, string hash)
 {
     var blobRef = Container.GetBlockBlobReference(hash);
     blobRef.Properties.ContentType = "image/jpeg";
     await blobRef.UploadFromStreamAsync(stream);
     await stream.FlushAsync();
 }
Exemplo n.º 32
0
 private static async Task AddToFile(YoutubeEntry entry, Uri uri, Stream destinationStream, long? start, long? stop, MSYoutubeLoading onYoutubeLoading)
 {
     if (entry.ExecutionStatus != ExecutionStatus.Normal) return;
     var response = await DownloadToStreamAsync(uri, start, stop);
     if (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable) return;
     var range = GetRange(response);
     var total =  range.Length; // (response.Headers.ContentRange.Length ?? 0);
     var to = range.To; // (response.Headers.ContentRange.To ?? 0);
     using (var stream = response.GetResponseStream()) {
         if (stream == null) return;
         await stream.CopyToAsync(destinationStream);
         await destinationStream.FlushAsync();
         if (onYoutubeLoading != null && entry.ExecutionStatus == ExecutionStatus.Normal) onYoutubeLoading(to, total);
         if (total > to + 1)
             await AddToFile(entry, uri, destinationStream, to + 1, to + BlockSize, onYoutubeLoading);
     }
 }
        public async Task <bool> WaitLogin()
        {
            if (!listener.Prefixes.Any())
            {
                listener.Prefixes.Add("http://localhost:58263/");
            }

            if (listener.IsListening)
            {
                listener.Stop();
            }
            listener.Start();
            var random     = new Random();
            var randombyte = new byte[32];

            random.NextBytes(randombyte);
            var code_veri = Utils.Base64UrlEncode(randombyte);
            var code_cha  = Utils.Base64UrlEncode(SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(code_veri))).Replace("=", "");
            var loginargs = new Dictionary <string, string>();

            loginargs["response_type"] = "code";
            loginargs["redirect_uri"]  = BLiveSpotify_Plugin.CALLBACK;
            loginargs["client_id"]     = BLiveSpotify_Plugin.APPID;
            var scope = new[] { "user-read-playback-state", "user-modify-playback-state", "user-read-private" };

            loginargs["scope"]                 = string.Join(" ", scope);
            loginargs["code_challenge"]        = code_cha;
            loginargs["code_challenge_method"] = "S256";
            var queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);

            foreach (var loginarg in loginargs)
            {
                queryString[loginarg.Key] = loginarg.Value;
            }
            System.Diagnostics.Process.Start("https://accounts.spotify.com/authorize?" + queryString);;
            HttpListenerResponse response = null;

            try
            {
                var context = await listener.GetContextAsync();

                response = context.Response;

                var ret = HttpUtility.ParseQueryString(context.Request.Url.Query);
                if (!string.IsNullOrEmpty(ret["code"]))
                {
                    var code = ret["code"];
                    var nv   = HttpUtility.ParseQueryString(string.Empty);
                    nv["grant_type"]    = "authorization_code";
                    nv["code"]          = code;
                    nv["redirect_uri"]  = BLiveSpotify_Plugin.CALLBACK;
                    nv["client_id"]     = BLiveSpotify_Plugin.APPID;
                    nv["code_verifier"] = code_veri;
                    var result = await client.PostAsync("https://accounts.spotify.com/api/token",
                                                        new StringContent(nv.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"));

                    if (result.IsSuccessStatusCode)
                    {
                        var res = await result.Content.ReadAsStringAsync();

                        var jobj = JObject.Parse(res);
                        this.refresh_token = jobj["refresh_token"] + "";
                        this.access_token  = jobj["access_token"] + "";
                        this.expriedate    = DateTime.Now.AddSeconds(jobj.Value <int>("expires_in"));
                        this.SaveConfig();
                        string responseString = "<HTML><META charset=\"UTF-8\"><BODY>授權成功, 請關閉本頁面</BODY></HTML>";
                        byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                        response.ContentLength64 = buffer.Length;
                        response.ContentType     = "text/html";
                        System.IO.Stream output = response.OutputStream;
                        await output.WriteAsync(buffer, 0, buffer.Length);

                        await output.FlushAsync();

                        output.Close();
                        return(true);
                    }
                    else
                    {
                        string responseString = "<HTML><META charset=\"UTF-8\"><BODY>授權失敗, 請關閉本頁面</BODY></HTML>";
                        byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                        response.ContentLength64 = buffer.Length;
                        response.ContentType     = "text/html";
                        System.IO.Stream output = response.OutputStream;
                        await output.WriteAsync(buffer, 0, buffer.Length);

                        await output.FlushAsync();

                        output.Close();
                        return(false);
                    }
                }

                {
                    string responseString = "<HTML><META charset=\"UTF-8\"><BODY>授權失敗, 請關閉本頁面</BODY></HTML>";
                    byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    response.ContentType     = "text/html;charset=utf-8";
                    System.IO.Stream output = response.OutputStream;
                    await output.WriteAsync(buffer, 0, buffer.Length);

                    await output.FlushAsync();

                    output.Close();
                }
                return(false);
            }
            catch (Exception e)
            {
                if (response != null)
                {
                    string responseString = "<HTML><META charset=\"UTF-8\"><BODY>授權失敗, 請關閉本頁面</BODY></HTML>";
                    byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    response.ContentType     = "text/html;charset=utf-8";
                    System.IO.Stream output = response.OutputStream;
                    await output.WriteAsync(buffer, 0, buffer.Length);

                    await output.FlushAsync();

                    output.Close();
                }

                return(false);
            }
            finally
            {
                listener.Stop();
            }
        }
Exemplo n.º 34
0
 /// <inheritdoc />
 public override Task FlushAsync(CancellationToken cancellationToken)
 {
     return(_stream.FlushAsync(cancellationToken));
 }
        private static async Task WriteAsync(AdminProject project, Stream stream, CancellationToken cancellationToken)
        {
            var stringWriter = new StringWriter();
            await stringWriter.WriteLineAsync(string.Format("{0},{1},{2},{3},{4},{5},{6}",
                project.Id.ToCsvValue(),
                project.Name.ToCsvValue(),
                project.Created.ToCsvValue(),
                project.UserId.ToCsvValue(),
                project.UserName.ToCsvValue(),
                project.ProductType.ToCsvValue(),
                project.Product.ToCsvValue()));

            byte[] bytes = Encoding.UTF8.GetBytes(stringWriter.ToString());

            await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
            await stream.FlushAsync(cancellationToken);
        }
Exemplo n.º 36
0
 protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
 {
     var array = new byte[100000];
     for (int i = 0; i < 10; i++)
     {
         await stream.WriteAsync(array, 0, array.Length);
         await stream.FlushAsync();
     }
 }
Exemplo n.º 37
0
        // We pass in private instance fields of this MarshalByRefObject-derived type as local params
        // to ensure performant access inside the state machine that corresponds this async method.
        private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
                                                     char[] charBuffer, int charPos, bool haveWrittenPreamble,
                                                     Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
        {
            if (!haveWrittenPreamble)
            {
                _this.HaveWrittenPreamble_Prop = true;
                byte[] preamble = encoding.GetPreamble();
                if (preamble.Length > 0)
                {
                    await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
                }
            }

            int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
            if (count > 0)
            {
                await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
            }

            // By definition, calling Flush should flush the stream, but this is
            // only necessary if we passed in true for flushStream.  The Web
            // Services guys have some perf tests where flushing needlessly hurts.
            if (flushStream)
            {
                await stream.FlushAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 38
0
        public bool Start()
        {
            try
            {
                StreamSocketListener listener = new StreamSocketListener();
                listener.BindServiceNameAsync("80").AsTask();
                listener.ConnectionReceived += async(sender, args) =>
                {
                    StringBuilder request = new StringBuilder();
                    using (Windows.Storage.Streams.IInputStream input = args.Socket.InputStream)
                    {
                        byte[] data = new byte[BufferSize];
                        Windows.Storage.Streams.IBuffer buffer = data.AsBuffer();
                        uint dataRead = BufferSize;
                        while (dataRead == BufferSize)
                        {
                            await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);

                            request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                            dataRead = buffer.Length;
                        }
                        //In the future, maybe we parse the HTTP request and serve different HTML pages for now we just always push index.html
                    }
                    using (IOutputStream output = args.Socket.OutputStream)
                    {
                        using (System.IO.Stream response = output.AsStreamForWrite())
                        {
                            string page   = "";
                            var    folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
                            // acquire file
                            var file = await folder.GetFileAsync("index.html");

                            var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);

                            foreach (var line in readFile)
                            {
                                page += line;
                            }
                            byte[] bodyArray  = Encoding.UTF8.GetBytes(page);
                            var    bodyStream = new MemoryStream(bodyArray);
                            //iCount++;

                            var header = "HTTP/1.1 200 OK\r\n" +
                                         $"Content-Length: {bodyStream.Length}\r\n" +
                                         "Connection: close\r\n\r\n";
                            byte[] headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray, 0, headerArray.Length);

                            await bodyStream.CopyToAsync(response);

                            await response.FlushAsync();
                        }
                    }
                };
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Exemplo n.º 39
0
        private async void StartStreamingLog(TranscodingJob transcodingJob, StreamState state, Stream source, Stream target)
        {
            try
            {
                using (var reader = new StreamReader(source))
                {
                    while (!reader.EndOfStream)
                    {
                        var line = await reader.ReadLineAsync().ConfigureAwait(false);

                        ParseLogLine(line, transcodingJob, state);

                        var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);

                        await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
                        await target.FlushAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error reading ffmpeg log", ex);
            }
        }
        private static async Task WriteAsync(AdminClient client, Stream stream, CancellationToken cancellationToken)
        {
            var stringWriter = new StringWriter();
            await stringWriter.WriteLineAsync(string.Format("{0},{1},{2},{3},{4},{5}",
                client.Id.ToCsvValue(),
                client.Email.ToCsvValue(),
                client.Name.ToCsvValue(),
                client.Created.ToCsvValue(),
                (client.Balance/100).ToCsvValue(),
                client.State.ToCsvValue()));

            byte[] bytes = Encoding.UTF8.GetBytes(stringWriter.ToString());

            await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
            await stream.FlushAsync(cancellationToken);
        }
        /// <summary>
        /// Writes the http response asynchronously to the specified stream.
        /// </summary>
        /// <param name="stream">The stream to write the response to.</param>
        /// <param name="close">Indicates whether the stream shall be closed after writing.</param>
        /// <returns>The task representing the asynchronous operation.</returns>
        public async override Task SendAsync(Stream stream, bool close)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));

            using (StreamWriter writer = new StreamWriter(stream, Encoding.ASCII, 2048, true) { NewLine = "\r\n" }) // TODO: UTF-8
            {
                // Write header line
                switch (HttpVersion)
                {
                    case Http10:
                        await writer.WriteAsync("HTTP/1.0");
                        break;

                    case Http11:
                        await writer.WriteAsync("HTTP/1.1");
                        break;
                }

                await writer.WriteAsync(" ");

                await writer.WriteAsync(State.ToString());

                await writer.WriteLineAsync();

                // Write header fields

                foreach (var kvp in _headerFields)
                {
                    await writer.WriteAsync(kvp.Key);

                    await writer.WriteAsync(": ");

                    await writer.WriteAsync(kvp.Value);

                    await writer.WriteLineAsync();
                }

                if (ContentAvailable)
                {
                    await writer.WriteAsync("Content-Length");

                    await writer.WriteAsync(": ");

                    await writer.WriteAsync(Content.Length.ToString());

                    await writer.WriteLineAsync();

                    if (ContentType != null)
                    {
                        await writer.WriteAsync("Content-Type");

                        await writer.WriteAsync(": ");

                        await writer.WriteAsync(ContentType.ToString());

                        await writer.WriteLineAsync();
                    }
                }

                await writer.WriteLineAsync();
            }

            // Write content
            if (ContentAvailable)
            {
                long position = Content.Position;

                Content.Position = 0;

                await Content.CopyToAsync(stream);

                Content.Position = position;
            }

            if (close)
                stream.Close();
            else
                await stream.FlushAsync();
        }
Exemplo n.º 42
0
        public static async Task Compress(Stream inputStream, Stream outputStream)
        {
            var buffer = new BufferBlock<CompressionDetails>(new DataflowBlockOptions { BoundedCapacity = BoundedCapacity });
            var compressorOptions = new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = MaxDegreeOfParallelism,
                BoundedCapacity = BoundedCapacity
            };

            var writerOptions = new ExecutionDataflowBlockOptions
            {
                BoundedCapacity = BoundedCapacity,
                SingleProducerConstrained = true
            };

            var compressor = new TransformBlock<CompressionDetails, CompressionDetails>(compressionDetails => Compress(compressionDetails), compressorOptions);
            var writer = new ActionBlock<CompressionDetails>(compressionDetailsWithSize => Multiplex(outputStream, compressionDetailsWithSize), writerOptions);

            buffer.LinkTo(compressor);
            compressor.LinkTo(writer);
            
            buffer.Completion.ContinueWith(task => compressor.Complete()); 
            compressor.Completion.ContinueWith(task => writer.Complete());

            long sourceLength = inputStream.Length;
            // Write total size to destination
            byte[] size = BitConverter.GetBytes(sourceLength);
            await outputStream.WriteAsync(size, 0, size.Length);

            long chunkSize = 1048576; // 1 MB
            int index = 0;
            while (sourceLength > 0)
            {
                byte[] data = new byte[chunkSize];
                int readCount = await inputStream.ReadAsync(data, 0, data.Length);

                byte[] bytes = new byte[readCount];
                Buffer.BlockCopy(data, 0, bytes, 0, readCount);

                CompressionDetails compressionDetails = new CompressionDetails
                {
                    Bytes = bytes,
                    ChunkSize = BitConverter.GetBytes(chunkSize),
                    Sequence = ++index
                };

                while (await buffer.SendAsync(compressionDetails) != true) { }

                sourceLength -= chunkSize;
                if (sourceLength < chunkSize)
                    chunkSize = sourceLength;

                if (sourceLength == 0)
                    buffer.Complete();
            }
            writer.Completion.Wait();

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