System.IO.Stream.WriteAsync(byte[], int, int)

Here are the examples of the csharp api System.IO.Stream.WriteAsync(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

544 Examples 7

19 View Source File : FileStorage.cs
License : MIT License
Project Creator : bezzad

public async Task WriteAsync(byte[] data, int offset, int count)
        {
            try
            {
                await GetStreamSynchronizer().WaitAsync().ConfigureAwait(false);
                if (_stream?.CanWrite != true)
                {
                    _stream = new FileStream(FileName, FileMode.Append, FileAccess.Write,
                        FileShare.Delete | FileShare.ReadWrite);
                }
                await _stream.WriteAsync(data, offset, count).ConfigureAwait(false);
            }
            finally
            {
                GetStreamSynchronizer().Release();
            }
        }

19 View Source File : BCTest.cs
License : MIT License
Project Creator : BlazorExtensions

private async Task<byte[]> WritePacket(USBDevice device, byte[] data)
        {
            var toCRC = new MemoryStream();
            await toCRC.WriteAsync(data, 0, data.Length);
            toCRC.WriteByte(PinPadConstants.ETB);
            var crc = toCRC.ToArray().ComputeCRC16();

            // <SYN>[MESSAGE]<ETB>{CRC}
            var output = new MemoryStream();
            output.WriteByte(PinPadConstants.SYN); //<SYN>
            await output.WriteAsync(data, 0, data.Length); //[MESSAGE]
            output.WriteByte(PinPadConstants.ETB); //<ETB>
            await output.WriteAsync(crc, 0, crc.Length); //{CRC}

            var outputData = output.ToArray();
            this._logger.LogInformation($"{PinPadConstants.APP_TO_PINPAD} {PacketToString(outputData)}");

            var trxResult = await device.TransferOut(2, outputData);

            if (trxResult.Status != USBTransferStatus.OK)
            {
                this._logger.LogWarning("NOT OK!!!");
                this._logger.LogWarning(trxResult);
            }
            this._logger.LogInformation(trxResult);
            int sendFailures = 0;
            var readResult = await device.TransferIn(1, 64);
            this._logger.LogInformation(readResult);
            var read = readResult.Data[0];

            while (read == PinPadConstants.NAK && sendFailures < 3)
            {
                this._logger.LogInformation($"{PinPadConstants.PINPAD_TO_APP} {PinPadConstants.NAK_STR}");
                trxResult = await device.TransferOut(2, outputData);
                if (trxResult.Status != USBTransferStatus.OK)
                {
                    this._logger.LogWarning("WRITE NOT OK!!!");
                    this._logger.LogWarning(trxResult);
                }
                readResult = await device.TransferIn(1, 64);
                if (readResult.Status != USBTransferStatus.OK)
                {
                    this._logger.LogWarning("READ NOT OK!!!");
                    this._logger.LogWarning(readResult);
                }
                read = readResult.Data[0];
                sendFailures++;
                this._logger.LogInformation($"Failures: {sendFailures}");
            }

            if (read != PinPadConstants.ACK) throw new InvalidOperationException(PinPadConstants.NAK_STR);

            this._logger.LogInformation($"{PinPadConstants.PINPAD_TO_APP} {PinPadConstants.ACK_STR}");

            var response = new MemoryStream();

            if (readResult.Data.Length > 1 && readResult.Data.Length < 64)
            {
                await response.WriteAsync(readResult.Data, 0, readResult.Data.Length);
            }
            else
            {
                do
                {
                    this._logger.LogInformation($"Reading mode data...");
                    readResult = await device.TransferIn(1, 64);
                    await response.WriteAsync(readResult.Data, 0, readResult.Data.Length);
                } while (readResult.Data.Length == 64);
            }

            this._logger.LogInformation($"Data length: {response.Length}");

            return await ReadPacket(device, response.ToArray());
        }

19 View Source File : RealFileWriter.cs
License : GNU General Public License v3.0
Project Creator : asimmon

public async Task SaveScreenshot(string path, byte[] screenshotBytes)
        {
#if NETSTANDARD2_0
            using (var fileStream = File.Open(path, FileMode.Create))
            {
                await fileStream.WriteAsync(screenshotBytes, 0, screenshotBytes.Length).ConfigureAwait(false);
            }
#else
            await using (var fileStream = File.Open(path, FileMode.Create))
            {
                await fileStream.WriteAsync(screenshotBytes).ConfigureAwait(false);
            }
#endif
        }

19 View Source File : DLSSRecord.cs
License : GNU General Public License v3.0
Project Creator : beeradmoore

internal async Task<(bool Success, string Message, bool Cancelled)> DownloadAsync(Action<int> ProgressCallback = null)
        {

            var dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

            if (String.IsNullOrEmpty(DownloadUrl))
            {
                return (false, "Invalid download URL.", false);
            }

            _cancellationTokenSource?.Cancel();

            LocalRecord.IsDownloading = true;
            LocalRecord.DownloadProgress = 0;
            LocalRecord.HasDownloadError = false;
            LocalRecord.DownloadErrorMessage = String.Empty;
            NotifyPropertyChanged("LocalRecord");

            _cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = _cancellationTokenSource.Token;
            var response = await App.CurrentApp.HttpClient.GetAsync(DownloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    LocalRecord.HasDownloadError = true;
                    LocalRecord.DownloadErrorMessage = "Could not download DLSS.";
                    NotifyPropertyChanged("LocalRecord");
                });

                return (false, "Could not download DLSS.", false);
            }

            var totalDownloadSize = response.Content.Headers.ContentLength ?? 0L;
            var totalBytesRead = 0L;
            var buffer = new byte[1024 * 8];
            var isMoreToRead = true;



            var guid = Guid.NewGuid().ToString().ToUpper();

            var tempPath = Windows.Storage.ApplicationData.Current.TemporaryFolder.Path;
            var tempZipFile = Path.Combine(tempPath, $"{guid}.zip");
            var tempDllFile = Path.Combine(tempPath, $"{guid}.dll");
            try
            {
                using (var fileStream = new FileStream(tempZipFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None, buffer.Length, true))
                {
                    using (var contentStream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false))
                    {
                        var lastUpdated = DateTimeOffset.Now;
                        do
                        {
                            var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);

                            if (bytesRead == 0)
                            {
                                isMoreToRead = false;
                                continue;
                            }

                            await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);

                            totalBytesRead += bytesRead;


                            if ((DateTimeOffset.Now - lastUpdated).TotalMilliseconds > 100)
                            {
                                lastUpdated = DateTimeOffset.Now;
                                if (totalDownloadSize > 0)
                                {
                                    dispatcherQueue.TryEnqueue(() =>
                                    {
                                        var percent = (int)Math.Ceiling((totalBytesRead / (double)totalDownloadSize) * 100L);
                                        ProgressCallback?.Invoke(percent);
                                        LocalRecord.DownloadProgress = percent;
                                        NotifyPropertyChanged("LocalRecord");
                                    });
                                }
                            }
                        }
                        while (isMoreToRead);
                    }

                    if (ZipMD5Hash != fileStream.GetMD5Hash())
                    {
                        throw new Exception("Downloaded file was invalid.");
                    }
                }

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.DownloadProgress = 100;
                    NotifyPropertyChanged("LocalRecord");
                });


                var storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                var dllsFolder = await storageFolder.CreateFolderAsync("dlls", Windows.Storage.CreationCollisionOption.OpenIfExists);



                using (var archive = ZipFile.OpenRead(tempZipFile))
                {
                    var zippedDlls = archive.Entries.Where(x => x.Name.EndsWith(".dll")).ToArray();
                    if (zippedDlls.Length != 1)
                    {
                        throw new Exception("Downloaded file was invalid.");
                    }

                    zippedDlls[0].ExtractToFile(tempDllFile, true);
                }

                var versionInfo = FileVersionInfo.GetVersionInfo(tempDllFile);

                var dlssVersion = versionInfo.GetFormattedFileVersion();
                if (MD5Hash != versionInfo.GetMD5Hash())
                {
                    throw new Exception("Downloaded file was invalid.");
                }

                if (Settings.AllowUntrusted == false)
                {
                    var isTrusted = WinTrust.VerifyEmbeddedSignature(tempDllFile);
                    if (isTrusted == false)
                    {
                        throw new Exception("Downloaded file was not trusted by Windows.");
                    }
                }

                var dlssFolder = await dllsFolder.CreateFolderAsync($"{dlssVersion}_{MD5Hash}", Windows.Storage.CreationCollisionOption.OpenIfExists);
                var dlssFile = Path.Combine(dlssFolder.Path, "nvngx_dlss.dll");
                File.Move(tempDllFile, dlssFile, true);

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloaded = true;
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    NotifyPropertyChanged("LocalRecord");
                });

                return (true, String.Empty, false);
            }
            catch (TaskCanceledException)
            {
                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    LocalRecord.IsDownloaded = false;
                    NotifyPropertyChanged("LocalRecord");
                });


                return (false, String.Empty, true);
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine($"ERROR: {err.Message}");

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    LocalRecord.IsDownloaded = false;
                    LocalRecord.HasDownloadError = true;
                    LocalRecord.DownloadErrorMessage = "Could not download DLSS.";
                    NotifyPropertyChanged("LocalRecord");
                });

                return (false, err.Message, false);
            }
            finally
            {
                // Remove temp file.
                try
                {
                    File.Delete(tempZipFile);
                }
                catch (Exception)
                {
                    // NOOP
                }

                try
                {
                    File.Delete(tempDllFile);
                }
                catch (Exception)
                {
                    // NOOP
                }

            }
        }

19 View Source File : FileBlogService.cs
License : Apache License 2.0
Project Creator : aws

[SuppressMessage(
            "Usage",
            "SecurityIntelliSenseCS:MS Security rules violation",
            Justification = "Caller must review file name.")]
        public async Task<string> SaveFile(byte[] bytes, string fileName, string? suffix = null)
        {
            if (bytes is null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }

            suffix = CleanFromInvalidChars(suffix ?? DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture));

            var ext = Path.GetExtension(fileName);
            var name = CleanFromInvalidChars(Path.GetFileNameWithoutExtension(fileName));

            var fileNameWithSuffix = $"{name}_{suffix}{ext}";

            var absolute = Path.Combine(this.folder, FILES, fileNameWithSuffix);
            var dir = Path.GetDirectoryName(absolute);

            Directory.CreateDirectory(dir);
            using (var writer = new FileStream(absolute, FileMode.CreateNew))
            {
                await writer.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
            }

            return $"/{POSTS}/{FILES}/{fileNameWithSuffix}";
        }

19 View Source File : GitignoreFileWriter.cs
License : Apache License 2.0
Project Creator : Arasz

public async Task WriteToFileAsync(string destination, string content)
        {
            if (string.IsNullOrEmpty(destination))
            {
                destination = Directory.GetCurrentDirectory();
            }

            var path = Path.Combine(destination, GitignoreFileName);
            using (var fileStream = File.Create(path))
            {
                var convertedContent = Encoding.UTF8.GetBytes(content);
                await fileStream.WriteAsync(convertedContent);
            }
        }

19 View Source File : StreamExtensions.cs
License : GNU General Public License v3.0
Project Creator : Bililive

internal static async Task<bool> CopyBytesAsync(this Stream from, Stream to, long length)
        {
            if (null == from) { throw new ArgumentNullException(nameof(from)); }
            if (null == to) { throw new ArgumentNullException(nameof(to)); }
            if (length < 0) { throw new ArgumentOutOfRangeException("length must be non-negative"); }
            if (length == 0) { return true; }
            if (!from.CanRead) { throw new ArgumentException("cannot read stream", nameof(from)); }
            if (!to.CanWrite) { throw new ArgumentException("cannot write stream", nameof(to)); }

            var buffer = t_buffer.Value!;

            while (length > BUFFER_SIZE)
            {
                if (BUFFER_SIZE != await from.ReadAsync(buffer, 0, BUFFER_SIZE))
                {
                    return false;
                }
                await to.WriteAsync(buffer, 0, BUFFER_SIZE);
                length -= BUFFER_SIZE;
            }

            if (length != await from.ReadAsync(buffer, 0, (int)length))
            {
                return false;
            }

            await to.WriteAsync(buffer, 0, (int)length);

            return true;
        }

19 View Source File : NativeMessagingHost.cs
License : MIT License
Project Creator : alexwiese

public async Task Write(object value)
        {
            var jsonString = JsonConvert.SerializeObject(value, _jsonSerializerSettings);

            // Use the encoding to get the length of the 
            // buffer, it may not be the number of chars
            var byteBuffer = _encoding.GetBytes(jsonString);
            var byteBufferLength = byteBuffer.Length;

            _sendLengthBuffer[0] = (byte)byteBufferLength;
            _sendLengthBuffer[1] = (byte)(byteBufferLength >> 8);
            _sendLengthBuffer[2] = (byte)(byteBufferLength >> 16);
            _sendLengthBuffer[3] = (byte)(byteBufferLength >> 24);

            // Send the buffer length (Int32) then the JSON
            await _outStream.WriteAsync(_sendLengthBuffer, 0, sizeof(int));
            await _outStream.WriteAsync(byteBuffer, 0, byteBufferLength);
        }

19 View Source File : RtspTcpTransportClient.cs
License : MIT License
Project Creator : BogdanovKirill

protected override Task WriteAsync(byte[] buffer, int offset, int count)
        {
            Debug.replacedert(_networkStream != null, "_networkStream != null");
            return _networkStream.WriteAsync(buffer, offset, count);
        }

19 View Source File : WebClient.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil

internal async Task<WebResponse> SendAsync(HttpMethod methodType, string url, CancellationToken token, IProgress<double> progress = null)
        {
            Plugin.Log($"{methodType.ToString()}: {url}");

            // create new request messsage
            var req = new HttpRequestMessage(methodType, url);

            // send request
            var resp = await _client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);

            //if ((int)resp.StatusCode == 429)
            //{
            //    // rate limiting handling
            //}

            if (token.IsCancellationRequested) throw new TaskCanceledException();

            using (var memoryStream = new MemoryStream())
            using (var stream = await resp.Content.ReadreplacedtreamAsync())
            {
                var buffer = new byte[8192];
                var bytesRead = 0; ;

                long? contentLength = resp.Content.Headers.ContentLength;
                var totalRead = 0;

                // send report
                progress?.Report(0);

                while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    if (token.IsCancellationRequested) throw new TaskCanceledException();

                    if (contentLength != null)
                    {
                        progress?.Report((double)totalRead / (double)contentLength);
                    }

                    await memoryStream.WriteAsync(buffer, 0, bytesRead);
                    totalRead += bytesRead;
                }

                progress?.Report(1);
                byte[] bytes = memoryStream.ToArray();

                return new WebResponse(resp, bytes);
            }
        }

19 View Source File : Plugin.cs
License : MIT License
Project Creator : b-editor

private static async ValueTask SaveAsync(IProgressDialog progress, HttpResponseMessage response, FileStream fs, int ticks)
        {
            using var stream = await response.Content.ReadreplacedtreamAsync();
            while (true)
            {
                var buffer = new byte[ticks];
                var t = await stream.ReadAsync(buffer.AsMemory(0, ticks));
                // 0バイト読みこんだら終わり
                if (t == 0) break;

                progress.Value += t;

                await fs.WriteAsync(buffer.AsMemory(0, t));
            }
        }

19 View Source File : SchematizedMediaTypeFormatter.cs
License : MIT License
Project Creator : AzureAD

public override Task WriteToStreamAsync(
            Type type,
            object value,
            Stream writeStream,
            HttpContent content,
            TransportContext transportContext)
        {
            if (null == type)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (null == writeStream)
            {
                throw new ArgumentNullException(nameof(writeStream));
            }

            Func<byte[], Task> writeFunction =
                new Func<byte[], Task>(
                    async (byte[] buffer) =>
                        await writeStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false));
            Task result = this.WriteToStream(type, value, writeStream, writeFunction);
            return result;
        }

19 View Source File : SaveUserSettings.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(_appSettings.UserSettingsFilePath);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(_context.UserSettings, Formatting.Indented);

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(_appSettings.UserSettingsFilePath, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : UploadFile.cs
License : MIT License
Project Creator : beryldev

[Fact]
        public async Task DoWithRefitUsingFileInfo()
        {
            using (var fileStream = new FileStream("filename.txt", FileMode.Create))
            {
                await fileStream.WriteAsync(Encoding.UTF8.GetBytes(FileContent));
            }
 
            var api = RestService.For<IUploadFile>("http://localhost:5000");
            
            var fileInfo = new FileInfo("filename.txt");
            HttpResponseMessage response = await api.Upload(fileInfo);

            string responseContent = await response.Content.ReadreplacedtringAsync();
            replacedert.Equal($"filename.txt:{FileContent}", responseContent);
        }

19 View Source File : Win10ToastNotificationsProvider.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private async Task<string> DownloadImageToDiskCached(string image, bool isAvatar = false, bool isRounded = false)
        {
            // Toasts can live for up to 3 days, so we cache images for up to 3 days.
            // Note that this is a very simple cache that doesn't account for space usage, so
            // this could easily consume a lot of space within the span of 3 days.
            if (image == null)
            {
                image = string.Empty;
            }

            try
            {
                var directory = Directory.CreateDirectory(this.ToastImagePath);

                if (!this.HasPerformedCleanup)
                {
                    // First time we run, we'll perform cleanup of old images
                    this.HasPerformedCleanup = true;

                    foreach (var d in directory.EnumerateDirectories())
                    {
                        if (d.LastAccessTime.Date < DateTime.UtcNow.Date.AddDays(-3))
                        {
                            d.Delete(true);
                        }
                    }
                }

                string hashName = this.Hash(image) + ".png";
                string imagePath = Path.Combine(directory.FullName, hashName);

                if (File.Exists(imagePath))
                {
                    return imagePath;
                }

                byte[] imageData;

                if (isAvatar)
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadAvatarImageAsync(image, !isRounded);
                }
                else
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadPostImageAsync(image);
                }

                using (var fileStream = File.OpenWrite(imagePath))
                {
                    await fileStream.WriteAsync(imageData, 0, imageData.Length);
                }

                return imagePath;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

19 View Source File : MemoryStorage.cs
License : MIT License
Project Creator : bezzad

public async Task WriteAsync(byte[] data, int offset, int count)
        {
            count = Math.Min(count, data.Length);
            InitialStorage();
            await _dataStream.WriteAsync(data, offset, count).ConfigureAwait(false);
        }

19 View Source File : StreamExtensions.cs
License : GNU General Public License v3.0
Project Creator : Artentus

public static async Task WriteAsync(this Stream stream, Packet packet)
        {
            await stream.WriteInt32LEAsync(packet.GetSize());
            await stream.WriteInt32LEAsync(packet.Id);
            await stream.WriteInt32LEAsync((int)packet.Type);

            byte[] body = Encoding.ASCII.GetBytes(packet.Body);
            await stream.WriteAsync(body, 0, body.Length);

            await stream.WriteAsync(Padding, 0, Padding.Length);
        }

19 View Source File : DragonUtil.cs
License : MIT License
Project Creator : BlackDragonBE

public static async Task DownloadFile(string url, string fileSavePath, string userAgent = null, int fileSizeInKilobytes = 0, IProgress<SimpleTaskProgress> taskProgress = null)
        {
            using (var client = new HttpClient())
            {
                if (userAgent != null)
                {
                    client.DefaultRequestHeaders.Add("User-Agent", userAgent);
                }

                using (HttpResponseMessage response = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result)
                {
                    response.EnsureSuccessStatusCode();

                    using (Stream contentStream = await response.Content.ReadreplacedtreamAsync(), fileStream = new FileStream(fileSavePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                    {
                        var totalRead = 0L;
                        var totalReads = 0L;
                        var buffer = new byte[8192];
                        var isMoreToRead = true;

                        do
                        {
                            var read = await contentStream.ReadAsync(buffer, 0, buffer.Length);
                            if (read == 0)
                            {
                                isMoreToRead = false;
                            }
                            else
                            {
                                await fileStream.WriteAsync(buffer, 0, read);

                                totalRead += read;
                                totalReads += 1;

                                if (totalReads % 256 != 0) continue;

                                taskProgress?.Report(new SimpleTaskProgress { CurrentProgress = (int)(totalRead / 1024), TotalProgress = fileSizeInKilobytes });

                                if (fileSizeInKilobytes > 0)
                                {
                                    long progress = totalRead / fileSizeInKilobytes * 100;

                                    Console.WriteLine(String.Format("Download progress: {2:n0} %  {0:n0}/{1:n0}", totalRead / 1024,
                                        fileSizeInKilobytes, progress));
                                }
                                else
                                {
                                    Console.WriteLine(String.Format("Total kiloBytes downloaded so far: {0:n0}", totalRead / 1024));
                                }
                            }
                        }
                        while (isMoreToRead);

                        taskProgress?.Report(new SimpleTaskProgress { CurrentProgress = (int)(totalRead / 1024), TotalProgress = fileSizeInKilobytes });
                    }
                }

            }
        }

19 View Source File : FileUtil.cs
License : MIT License
Project Creator : adospace

public static async Task SaveAllFileAsync(string filename, byte[] data)
        {
            using (var file = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Write, 4096, true))
            {
                await file.WriteAsync(data, 0, data.Length);
            }
        }

19 View Source File : ThrottledStream.cs
License : GNU Affero General Public License v3.0
Project Creator : blockbasenetwork

public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            await _sendBandwithController.WaitToTransmit(count);
            await _stream.WriteAsync(buffer, offset, count);
        }

19 View Source File : CanonicalRequestPatterns.cs
License : Apache License 2.0
Project Creator : aspnet

[CanonicalRequest(Path = "/large-awaitingwork-asyncwrite", Description = "Return 1mb ascii byte[] in 2kb await WriteAsync with 20ms awaits every 8 writes")]
        public async Task LargeAwaitingWorkAsyncWrite(IDictionary<string, object> env)
        {
            Util.ResponseHeaders(env)["Content-Type"] = new[] { "text/plain" };
            Stream responseBody = Util.ResponseBody(env);
            for (int loop = 0; loop != (1 << 20) / (2 << 10); ++loop)
            {
                await responseBody.WriteAsync(_2KAlphabet, 0, 2048);
                if ((loop % 8) == 0)
                {
                    await Task.Delay(20);
                }
            }
        }

19 View Source File : FileCache.cs
License : MIT License
Project Creator : automuteus

public static async Task<MemoryStream> HitAsync(string url)
        {
            if (!Directory.Exists(AppCacheDirectory))
            {
                Directory.CreateDirectory(AppCacheDirectory);
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
            {
                return null;
            }

            var fileNameBuilder = new StringBuilder();
            using (var sha1 = new SHA1Managed())
            {
                var canonicalUrl = uri.ToString();
                var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(canonicalUrl));
                fileNameBuilder.Append(BitConverter.ToString(hash).Replace("-", "").ToLower());

                if (Path.HasExtension(canonicalUrl))
                {
                    fileNameBuilder.Append(Path.GetExtension(canonicalUrl.Split('?')[0]));
                }
            }

            var fileName = fileNameBuilder.ToString();
            var localFile = Path.Combine(AppCacheDirectory, fileName);
            var memoryStream = new MemoryStream();

            FileStream fileStream = null;
            if (!_isWritingFile.ContainsKey(fileName) && File.Exists(localFile))
            {
                await using (fileStream = new FileStream(localFile, FileMode.Open, FileAccess.Read))
                {
                    await fileStream.CopyToAsync(memoryStream);
                }
                memoryStream.Seek(0, SeekOrigin.Begin);
                return memoryStream;
            }

            try
            {
                var responseStream = await _httpClient.GetStreamAsync(uri);

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

                if (!_isWritingFile.ContainsKey(fileName))
                {
                    _isWritingFile[fileName] = true;
                    fileStream = new FileStream(localFile, FileMode.Create, FileAccess.Write);
                }

                await using (responseStream)
                {
                    var bytebuffer = new byte[1024];
                    int bytesRead;
                    do
                    {
                        bytesRead = await responseStream.ReadAsync(bytebuffer, 0, 1024);
                        if (fileStream != null)
                        {
                            await fileStream.WriteAsync(bytebuffer, 0, bytesRead);
                        }

                        await memoryStream.WriteAsync(bytebuffer, 0, bytesRead);
                    } while (bytesRead > 0);
                    if (fileStream != null)
                    {
                        await fileStream.FlushAsync();
                        fileStream.Dispose();
                        _isWritingFile.Remove(fileName);
                    }
                }
                memoryStream.Seek(0, SeekOrigin.Begin);
                return memoryStream;
            }
            catch (HttpRequestException)
            {
                return null;
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, bool debugging = true)
        {
            
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
               
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                Console.WriteLine($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                Console.WriteLine([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : IdleManager.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

private void WriteProgress()
        {
            if (_output != null)
            {
                try
                {
                    // To output progress, we need to use git's progress sideband. Needs to look like:
                    //      0006[0x2].
                    // Where [0x2] is just an ASCII 2 char, and is the marker for the progress sideband
                    // 0006 is the line length.
                    _output.WriteAsync(progressLine, 0, progressLine.Length).Wait();

                    _output.Flush();
                }
                catch (Exception e)
                {
                    // To be defensive, if anything goes wrong during progress writing, so trying
                    _output = null;

                    _tracer.Trace("Failed to write progress in IdleManager. {0}", e.Message);
                }
            }
        }

19 View Source File : PayServices.cs
License : Apache License 2.0
Project Creator : anjoy8

public async Task<MessageModel<PayRefundReturnResultModel>> PayRefund(PayRefundNeedModel payModel)
        {
            _logger.LogInformation("退款开始");
            MessageModel<PayRefundReturnResultModel> messageModel = new MessageModel<PayRefundReturnResultModel>();
            messageModel.response = new PayRefundReturnResultModel();
            try
            {
                _logger.LogInformation($"原始GET参数->{_httpContextAccessor.HttpContext.Request.QueryString}");

                string REQUEST_SN = StringHelper.GetGuidToLongID().ToString().Substring(0, 16);//请求序列码
                string CUST_ID = StaticPayInfo.MERCHANTID;//商户号
                string USER_ID = StaticPayInfo.USER_ID;//操作员号
                string PreplacedWORD = StaticPayInfo.PreplacedWORD;//密码
                string TX_CODE = "5W1004";//交易码
                string LANGUAGE = "CN";//语言
                                       //string SIGN_INFO = "";//签名信息
                                       //string SIGNCERT = "";//签名CA信息
                                       //外联平台客户端服务部署的地址+设置的监听端口
                string sUrl = StaticPayInfo.OutAddress;

                //XML请求报文
                //string sRequestMsg = $" requestXml=<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>{REQUEST_SN}</REQUEST_SN><CUST_ID>{CUST_ID}</CUST_ID><USER_ID>{USER_ID}</USER_ID><PreplacedWORD>{PreplacedWORD}</PreplacedWORD><TX_CODE>{TX_CODE}</TX_CODE><LANGUAGE>{LANGUAGE}</LANGUAGE><TX_INFO><MONEY>{payModel.MONEY}</MONEY><ORDER>{payModel.ORDER}</ORDER><REFUND_CODE>{payModel.REFUND_CODE}</REFUND_CODE></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX> ";
                string sRequestMsg = $"<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>{REQUEST_SN}</REQUEST_SN><CUST_ID>{CUST_ID}</CUST_ID><USER_ID>{USER_ID}</USER_ID><PreplacedWORD>{PreplacedWORD}</PreplacedWORD><TX_CODE>{TX_CODE}</TX_CODE><LANGUAGE>{LANGUAGE}</LANGUAGE><TX_INFO><MONEY>{payModel.MONEY}</MONEY><ORDER>{payModel.ORDER}</ORDER><REFUND_CODE>{payModel.REFUND_CODE}</REFUND_CODE></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX> ";

                //string sRequestMsg = readRequestFile("E:/02-外联平台/06-测试/测试报文/商户网银/客户端连接-5W1001-W06.txt");


                //注意:请求报文必须放在requestXml参数送
                sRequestMsg = "requestXml=" + sRequestMsg;

                _logger.LogInformation("请求地址:" + sUrl);
                _logger.LogInformation("请求报文:" + sRequestMsg);
                HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(sUrl);
                request.Method = "POST";

                request.ContentType = "application/x-www-form-urlencoded";
                request.KeepAlive = false;
                request.Connection = "";

                //外联平台使用GB18030编码,这里进行转码处理 
                byte[] byteRquest = Encoding.GetEncoding("GB18030").GetBytes(sRequestMsg);
                request.ContentLength = byteRquest.Length;

                //发送请求
                Stream writerStream = request.GetRequestStream();
                await writerStream.WriteAsync(byteRquest, 0, byteRquest.Length);
                writerStream.Flush();
                writerStream.Close();

                //接收请求
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream result = response.GetResponseStream();
                StreamReader readerResult = new StreamReader(result, System.Text.Encoding.GetEncoding("GB18030"));
                string sResult = await readerResult.ReadToEndAsync();
                _logger.LogInformation("响应报文:" + sResult);
                var Xmlresult = XmlHelper.ParseFormByXml<PayRefundReturnModel>(sResult, "TX");
                if (Xmlresult.RETURN_CODE.Equals("000000"))
                {
                    messageModel.success = true;
                    messageModel.msg = "退款成功";
                }
                else
                {
                    messageModel.success = false;
                    messageModel.msg = "退款失败";
                }
                messageModel.response.RETURN_MSG = Xmlresult.RETURN_MSG;
                messageModel.response.TX_CODE = Xmlresult.TX_CODE;
                messageModel.response.REQUEST_SN = Xmlresult.REQUEST_SN;
                messageModel.response.RETURN_CODE = Xmlresult.RETURN_CODE;
                messageModel.response.CUST_ID = Xmlresult.CUST_ID;
                messageModel.response.LANGUAGE = Xmlresult.LANGUAGE;

                messageModel.response.AMOUNT = Xmlresult.TX_INFO?.AMOUNT;
                messageModel.response.PAY_AMOUNT = Xmlresult.TX_INFO?.PAY_AMOUNT;
                messageModel.response.ORDER_NUM = Xmlresult.TX_INFO?.ORDER_NUM;
            }
            catch (Exception ex)
            {
                messageModel.success = false;
                messageModel.msg = "服务错误";
                messageModel.response.RETURN_MSG = ex.Message;
                _logger.LogInformation($"异常信息:{ex.Message}");
                _logger.LogInformation($"异常堆栈:{ex.StackTrace}");
            }
            finally
            {
                _logger.LogInformation($"返回数据->{JsonHelper.GetJSON<MessageModel<PayRefundReturnResultModel>>(messageModel)}");
                _logger.LogInformation("退款结束");
            }
            return messageModel;

        }

19 View Source File : ModifyPageViewModel.cs
License : MIT License
Project Creator : b-editor

private async ValueTask SaveAsync(HttpResponseMessage response, FileStream fs, int ticks)
        {
            using var stream = await response.Content.ReadreplacedtreamAsync();
            while (true)
            {
                var buffer = new byte[ticks];
                var t = await stream.ReadAsync(buffer.AsMemory(0, ticks));
                // 0バイト読みこんだら終わり
                if (t == 0) break;

                Progress.Value += t;

                await fs.WriteAsync(buffer.AsMemory(0, t));
            }
        }

19 View Source File : X11Client.cs
License : MIT License
Project Creator : azyobuzin

protected internal async Task SendRequestAsync(int requestSize, Action<byte[]> createRequest)
        {
            var tcs = new TaskCompletionSource<Unit>();
            ushort sequenceNumber = 0;

            Task mainReplyAction(byte[] replyHeader, byte[] replyContent, Exception exception)
            {
                tcs.SetException(exception ?? new InvalidOperationException("Received an unexpected reply."));
                return Task.CompletedTask;
            }

            Task syncReplyAction(byte[] replyHeader, byte[] replyContent, Exception exception)
            {
                Debug.replacedert(sequenceNumber > 0);
                this._replyActions.TryRemove(sequenceNumber, out var _);

                if (exception == null)
                {
                    tcs.TrySetResult(Unit.Default);
                }
                else
                {
                    tcs.TrySetException(exception);
                }

                return Task.CompletedTask;
            }

            void createSyncRequest(byte[] buf)
            {
                ref var req = ref Unsafe.As<byte, EmptyRequestHeader>(ref buf[0]);
                req = default;
                req.Opcode = 43;
                req.RequestLength = 1;
            }

            await this._requestSemapreplaced.WaitAsync().ConfigureAwait(false);
            try
            {
                // 1. リクエストを送信
                sequenceNumber = this._sequenceNumber;
                if (!this._replyActions.TryAdd(sequenceNumber, mainReplyAction))
                    throw new InvalidOperationException("Duplicated sequence number");

                EnsureBufferSize(ref this._requestBuffer, requestSize);
                createRequest(this._requestBuffer);
                await this.Stream.WriteAsync(this._requestBuffer, 0, requestSize).ConfigureAwait(false);

                this._sequenceNumber++;

                // 2. 次のリクエストのリプライが返ってくる前に 1 へのエラーが返ってくるんじゃねえかなぁ
                if (!this._replyActions.TryAdd((ushort)(sequenceNumber + 1), syncReplyAction))
                    throw new InvalidOperationException("Duplicated sequence number");

                // _requestBuffer は最低 8192 あるから EnsureBufferSize は要らない
                createSyncRequest(this._requestBuffer);
                await this.Stream.WriteAsync(this._requestBuffer, 0, EmptyRequestHeaderSize).ConfigureAwait(false);

                this._sequenceNumber++;
            }
            catch
            {
                if (sequenceNumber > 0)
                {
                    this._replyActions.TryRemove(sequenceNumber, out var _);
                    this._replyActions.TryRemove((ushort)(sequenceNumber + 1), out var _);
                }
            }
            finally
            {
                this._requestSemapreplaced.Release();
            }
        }

19 View Source File : SaveSession.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(_appSettings.SessionFilePath);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(_context.Session, Formatting.Indented);

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(_appSettings.SessionFilePath, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : ScrapeTask.cs
License : MIT License
Project Creator : BaristaLabs

public override async Task PerformTask(ISkraprWorker worker)
        {
            if (Gather == null)
                throw new InvalidOperationException("Gather must be specified on a Scrape task.");

            var result = await GetDataObject(worker);

            //worker.Session.run
            //TODO: Change this to use a repository.
            var id = result["_id"].ToString();
            if (!String.IsNullOrWhiteSpace(id))
            {
                Directory.CreateDirectory($"./data/{id}");
                File.WriteAllText($"./data/{id}/default.json", result.ToString());

                foreach (var key in worker.DevTools.Responses.Keys)
                {
                    if (Regex.IsMatch(key, @"\.jpg$", RegexOptions.IgnoreCase))
                    {
                        var responseBody = await worker.Session.Network.GetResponseBody(new Network.GetResponseBodyCommand
                        {
                            RequestId = worker.DevTools.Responses[key].RequestId
                        });

                        var fileName = Path.GetFileName(key);
                        if (responseBody.Base64Encoded)
                        {
                            var imageBytes = Convert.FromBase64String(responseBody.Body);
                            using (var fileStream = File.Open($"./data/{id}/{fileName}", FileMode.Create))
                            {
                                fileStream.Seek(0, SeekOrigin.End);
                                await fileStream.WriteAsync(imageBytes, 0, imageBytes.Length);
                            }
                        }
                    }
                }
            }
        }

19 View Source File : Win10ToastNotificationsProvider.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private async Task<string> DownloadImageToDiskCached(string image, bool isAvatar = false, bool isRounded = false)
        {
            // Toasts can live for up to 3 days, so we cache images for up to 3 days.
            // Note that this is a very simple cache that doesn't account for space usage, so
            // this could easily consume a lot of space within the span of 3 days.
            if (image == null)
            {
                image = string.Empty;
            }

            try
            {
                var directory = Directory.CreateDirectory(this.ToastImagePath);

                if (!this.HasPerformedCleanup)
                {
                    // First time we run, we'll perform cleanup of old images
                    this.HasPerformedCleanup = true;

                    foreach (var d in directory.EnumerateDirectories())
                    {
                        if (d.LastAccessTime.Date < DateTime.UtcNow.Date.AddDays(-3))
                        {
                            d.Delete(true);
                        }
                    }
                }

                string hashName = HashUtils.SHA1Hash(image) + ".png";
                string imagePath = Path.Combine(directory.FullName, hashName);

                if (File.Exists(imagePath))
                {
                    return imagePath;
                }

                byte[] imageData;

                if (isAvatar)
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadAvatarImageAsync(image, !isRounded);
                }
                else
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadPostImageAsync(image);
                }

                using (var fileStream = File.OpenWrite(imagePath))
                {
                    await fileStream.WriteAsync(imageData, 0, imageData.Length);
                }

                return imagePath;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

19 View Source File : FileOperations.cs
License : GNU General Public License v3.0
Project Creator : belowaverage-org

public static void CopyFile(string Source, string Destination)
        {
            FileInfo file = new FileInfo(Source);
            FileInfo destination = new FileInfo(Destination);
            const int bufferSize = 1024 * 1024;
            byte[] buffer = new byte[bufferSize], buffer2 = new byte[bufferSize];
            bool swap = false;
            int reportedProgress = 0;
            long len = file.Length;
            float flen = len;
            Task writer = null;
            using (var source = file.OpenRead())
            using (var dest = destination.OpenWrite())
            {
                dest.SetLength(source.Length);
                int read;
                for (long size = 0; size < len; size += read)
                {
                    int progress;
                    if ((progress = ((int)((size / flen) * 100))) != reportedProgress)
                    {
                        Logger.UpdateProgress(reportedProgress = progress);
                    }
                    read = source.Read(swap ? buffer : buffer2, 0, bufferSize);
                    writer?.Wait();
                    writer = dest.WriteAsync(swap ? buffer : buffer2, 0, read);
                    swap = !swap;
                }
                writer?.Wait();
            }
        }

19 View Source File : SaveWidget.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(request.FileName);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(request.Widget, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All,
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                });

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(request.FileName, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : UploadFile.cs
License : MIT License
Project Creator : beryldev

[Fact]
        public async Task DoWithRefitUsingFileInfoPart()
        {
            using (var fileStream = new FileStream("filename2.txt", FileMode.Create))
            {
                await fileStream.WriteAsync(Encoding.UTF8.GetBytes(FileContent));
            }
            
            var api = RestService.For<IUploadFile>("http://localhost:5000");
            
            var fileInfo = new FileInfoPart(new FileInfo("filename2.txt"), "filename.txt");
            HttpResponseMessage response = await api.Upload(fileInfo);

            string responseContent = await response.Content.ReadreplacedtringAsync();
            replacedert.Equal($"filename.txt:{FileContent}", responseContent);
        }

19 View Source File : ReloadCommand.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, IVsOutputWindowPane outputPane, bool debugging)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
                
                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                outputPane.OutputStringThreadSafe($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                outputPane.OutputStringThreadSafe([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : ThrottledStreamTest.cs
License : MIT License
Project Creator : bezzad

[TestMethod]
        public void TestStreamWriteAsyncSpeed()
        {
            TestStreamWriteSpeed((stream, buffer, offset, count) => {
                stream.WriteAsync(buffer, offset, count).Wait();
            });
        }

19 View Source File : StreamExtensions.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private static Task WriteInt32LEAsync(this Stream stream, int value)
        {
            var bytes = GetInt32BytesLE(value);
            return stream.WriteAsync(bytes, 0, bytes.Length);
        }

19 View Source File : RawDataRecordTask.cs
License : GNU General Public License v3.0
Project Creator : Bililive

private async Task WriteStreamToFileAsync(Stream stream, FileStream file)
        {
            try
            {
                var buffer = new byte[1024 * 8];
                this.timer.Start();

                while (!this.ct.IsCancellationRequested)
                {
                    var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, this.ct).ConfigureAwait(false);
                    if (bytesRead == 0)
                        break;

                    Interlocked.Add(ref this.fillerDownloadedBytes, bytesRead);

                    await file.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException ex)
            {
                this.logger.Debug(ex, "录制被取消");
            }
            catch (IOException ex)
            {
                this.logger.Warning(ex, "录制时发生IO错误");
            }
            catch (Exception ex)
            {
                this.logger.Warning(ex, "录制时发生了错误");
            }
            finally
            {
                this.timer.Stop();
                this.RequestStop();

                try
                {
                    var openingEventArgs = this.fileOpeningEventArgs;
                    if (openingEventArgs is not null)
                        this.OnRecordFileClosed(new RecordFileClosedEventArgs(this.room)
                        {
                            SessionId = this.SessionId,
                            FullPath = openingEventArgs.FullPath,
                            RelativePath = openingEventArgs.RelativePath,
                            FileOpenTime = openingEventArgs.FileOpenTime,
                            FileCloseTime = DateTimeOffset.Now,
                            Duration = 0,
                            FileSize = file.Length,
                        });
                }
                catch (Exception ex)
                {
                    this.logger.Warning(ex, "Error calling OnRecordFileClosed");
                }

                try
                { file.Dispose(); }
                catch (Exception ex)
                { this.logger.Warning(ex, "关闭文件时发生错误"); }

                try
                { stream.Dispose(); }
                catch (Exception) { }

                this.OnRecordSessionEnded(EventArgs.Empty);

                this.logger.Information("录制结束");
            }
        }

19 View Source File : DnsServer.cs
License : Apache License 2.0
Project Creator : alexreinert

private async void HandleTcpListenerAsync()
		{
			TcpClient client = null;

			try
			{
				try
				{
					client = await _tcpListener.AcceptTcpClientAsync();

					ClientConnectedEventArgs clientConnectedEventArgs = new ClientConnectedEventArgs(ProtocolType.Tcp, (IPEndPoint) client.Client.RemoteEndPoint);
					await ClientConnected.RaiseAsync(this, clientConnectedEventArgs);

					if (clientConnectedEventArgs.RefuseConnect)
						return;
				}
				finally
				{
					lock (_listenerLock)
					{
						_hasActiveTcpListener = false;
					}
				}

				StartTcpListenerTask();

				using (NetworkStream stream = client.GetStream())
				{
					while (true)
					{
						byte[] buffer = await ReadIntoBufferAsync(client, stream, 2);
						if (buffer == null) // client disconneted while reading or timeout
							break;

						int offset = 0;
						int length = DnsMessageBase.ParseUShort(buffer, ref offset);

						buffer = await ReadIntoBufferAsync(client, stream, length);
						if (buffer == null) // client disconneted while reading or timeout
						{
							throw new Exception("Client disconnted or timed out while sending data");
						}

						DnsMessageBase query;
						byte[] tsigMac;
						try
						{
							query = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
							tsigMac = query.TSigOptions?.Mac;
						}
						catch (Exception e)
						{
							throw new Exception("Error parsing dns query", e);
						}

						DnsMessageBase response;
						try
						{
							response = await ProcessMessageAsync(query, ProtocolType.Tcp, (IPEndPoint) client.Client.RemoteEndPoint);
						}
						catch (Exception ex)
						{
							OnExceptionThrownAsync(ex);

							response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
							response.IsQuery = false;
							response.AdditionalRecords.Clear();
							response.AuthorityRecords.Clear();
							response.ReturnCode = ReturnCode.ServerFailure;
						}

						byte[] newTsigMac;

						length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac);

						if (length <= 65535)
						{
							await stream.WriteAsync(buffer, 0, length);
						}
						else
						{
							if ((response.Questions.Count == 0) || (response.Questions[0].RecordType != RecordType.Axfr))
							{
								OnExceptionThrownAsync(new ArgumentException("The length of the serialized response is greater than 65,535 bytes"));

								response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
								response.IsQuery = false;
								response.AdditionalRecords.Clear();
								response.AuthorityRecords.Clear();
								response.ReturnCode = ReturnCode.ServerFailure;

								length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac);
								await stream.WriteAsync(buffer, 0, length);
							}
							else
							{
								bool isSubSequentResponse = false;

								while (true)
								{
									List<DnsRecordBase> nextPacketRecords = new List<DnsRecordBase>();

									while (length > 65535)
									{
										int lastIndex = Math.Min(500, response.AnswerRecords.Count / 2);
										int removeCount = response.AnswerRecords.Count - lastIndex;

										nextPacketRecords.InsertRange(0, response.AnswerRecords.GetRange(lastIndex, removeCount));
										response.AnswerRecords.RemoveRange(lastIndex, removeCount);

										length = response.Encode(true, tsigMac, isSubSequentResponse, out buffer, out newTsigMac);
									}

									await stream.WriteAsync(buffer, 0, length);

									if (nextPacketRecords.Count == 0)
										break;

									isSubSequentResponse = true;
									tsigMac = newTsigMac;
									response.AnswerRecords = nextPacketRecords;
									length = response.Encode(true, tsigMac, true, out buffer, out newTsigMac);
								}
							}
						}

						// Since support for multiple tsig signed messages is not finished, just close connection after response to first signed query
						if (newTsigMac != null)
							break;
					}
				}
			}
			catch (Exception ex)
			{
				OnExceptionThrownAsync(ex);
			}
			finally
			{
				try
				{
					// ReSharper disable once ConstantConditionalAccessQualifier
					client?.Close();
				}
				catch
				{
					// ignored
				}

				lock (_listenerLock)
				{
					_availableTcpListener++;
				}
				StartTcpListenerTask();
			}
		}

19 View Source File : DanmakuClient.cs
License : GNU General Public License v3.0
Project Creator : Bililive

private static async Task SendMessageAsync(Stream stream, int action, string body = "")
        {
            if (stream is null)
                throw new ArgumentNullException(nameof(stream));

            var playload = Encoding.UTF8.GetBytes(body);
            var size = playload.Length + 16;
            var buffer = ArrayPool<byte>.Shared.Rent(16);
            try
            {
                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 0, 4), (uint)size);
                BinaryPrimitives.WriteUInt16BigEndian(new Span<byte>(buffer, 4, 2), 16);
                BinaryPrimitives.WriteUInt16BigEndian(new Span<byte>(buffer, 6, 2), 1);
                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 8, 4), (uint)action);
                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 12, 4), 1);

                await stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
                if (playload.Length > 0)
                    await stream.WriteAsync(playload, 0, playload.Length).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
            }
        }

19 View Source File : FileUploadController.cs
License : MIT License
Project Creator : ASF-Framework

private async Task UploadPartialFile(string fileName, HttpRequest request, List<ViewDataUploadFilesResult> statuses)
        {
            if (request.Form.Files.Count != 1)
                throw new ValidationException("Attempt to upload chunked file containing more than one fragment per request");
            var file = request.Form.Files[0];
            var inputStream = file.OpenReadStream();
            var fullPath = Path.Combine(StorageRoot, Path.GetFileName(fileName));

            using (var fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write))
            {
                var buffer = new byte[1024];

                var l = inputStream.Read(buffer, 0, 1024);
                while (l > 0)
                {
                    await fs.WriteAsync(buffer, 0, l);
                    l = inputStream.Read(buffer, 0, 1024);
                }
                fs.Flush();
                fs.Close();
            }
            statuses.Add(new ViewDataUploadFilesResult(fileName, fullPath, file));
        }

19 View Source File : WebSocketConnection.cs
License : GNU Lesser General Public License v2.1
Project Creator : Blancworks

public async Task<byte[]> GetNextMessage()
        {
            Logger.LogMessage("Getting Message.");

            byte[] buffer = new byte[1024];

            try
            {
                var msg = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); //Keep connection open for 15 seconds

                using (MemoryStream ms = new MemoryStream())
                {

                    //While not end of message and while close status is empty (not closed)
                    while (msg.CloseStatus == null)
                    {
                        await ms.WriteAsync(buffer, 0, msg.Count);

                        //Stop getting if this is the end of the message.
                        if (msg.EndOfMessage)
                        {
                            break;
                        }

                        msg = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), GetTimeoutCancelToken(1000));

                        //If size of message is too large
                        if (ms.Length >= 1024 * 110)
                        {
                            Logger.LogMessage("Message is too large.");

                            int tries = 0;
                            //Read rest of message, do nothing with the data tho
                            while (tries < 1000 && msg.EndOfMessage == false && msg.CloseStatus == null)
                            {
                                msg = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), GetTimeoutCancelToken(1000));

                                tries++;
                            }

                            return new byte[0];
                        }
                    }

                    //If connection closed, return 0-length byte array.
                    if (msg.CloseStatus != null)
                    {
                        Logger.LogMessage("Connection was closed from client");
                        return new byte[0];
                    }

                    Logger.LogMessage("End Of Message. Length:" + ms.Length);

                    //Check byte rate limit.
                    if (byteRateLimiter.TryTakePoints(ms.Length))
                    {
                        return ms.ToArray();
                    } 
                    else
                    {
                        Logger.LogMessage("Byte Ratelimit hit.");
                        SendMessage(new ErrorMessageSender(ErrorMessageSender.BYTE_RATE_LIMIT));
                        return new byte[0];
                    }
                }
            }
            catch (Exception e)
            {
                Logger.LogMessage(e);
            }

            return new byte[0];
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

protected override async void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (!_disposed)
            {
                _disposed = true;
                if (_recordFileData != null)
                {
                    try
                    {
                        var filePath = _recordFileData.Name;
                        using (var recordFile = new FileStream(filePath.Substring(0, filePath.Length - 5) + ".flv", FileMode.OpenOrCreate))
                        {
                            recordFile.SetLength(0);
                            recordFile.Seek(0, SeekOrigin.Begin);
                            await recordFile.WriteAsync(FlvMuxer.MultiplexFlvHeader(true, true));
                            var metaData = _metaData.Data[1] as Dictionary<string, object>;
                            metaData["duration"] = ((double)_currentTimestamp) / 1000;
                            metaData["keyframes"] = _keyframes;
                            _metaData.MessageHeader.MessageLength = 0;
                            var dataTagLen = FlvMuxer.MultiplexFlv(_metaData).Length;

                            var offset = recordFile.Position + dataTagLen;
                            for (int i = 0; i < _keyframeFilePositions.Count; i++)
                            {
                                _keyframeFilePositions[i] = (double)_keyframeFilePositions[i] + offset;
                            }

                            await recordFile.WriteAsync(FlvMuxer.MultiplexFlv(_metaData));
                            _recordFileData.Seek(0, SeekOrigin.Begin);
                            await _recordFileData.CopyToAsync(recordFile);
                            _recordFileData.Dispose();
                            File.Delete(filePath);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
                _recordFile?.Dispose();
            }
        }

19 View Source File : BCTest.cs
License : MIT License
Project Creator : BlazorExtensions

private async Task<byte[]> WritePacket(USBDevice device, byte[] data)
        {
            var toCRC = new MemoryStream();
            await toCRC.WriteAsync(data, 0, data.Length);
            toCRC.WriteByte(PinPadConstants.ETB);
            var crc = toCRC.ToArray().ComputeCRC16();

            // <SYN>[MESSAGE]<ETB>{CRC}
            var output = new MemoryStream();
            output.WriteByte(PinPadConstants.SYN); //<SYN>
            await output.WriteAsync(data, 0, data.Length); //[MESSAGE]
            output.WriteByte(PinPadConstants.ETB); //<ETB>
            await output.WriteAsync(crc, 0, crc.Length); //{CRC}

            var outputData = output.ToArray();
            this._logger.LogInformation($"{PinPadConstants.APP_TO_PINPAD} {PacketToString(outputData)}");

            var trxResult = await device.TransferOut(2, outputData);

            if (trxResult.Status != USBTransferStatus.OK)
            {
                this._logger.LogWarning("NOT OK!!!");
                this._logger.LogWarning(trxResult);
            }
            this._logger.LogInformation(trxResult);
            int sendFailures = 0;
            var readResult = await device.TransferIn(1, 64);
            this._logger.LogInformation(readResult);
            var read = readResult.Data[0];

            while (read == PinPadConstants.NAK && sendFailures < 3)
            {
                this._logger.LogInformation($"{PinPadConstants.PINPAD_TO_APP} {PinPadConstants.NAK_STR}");
                trxResult = await device.TransferOut(2, outputData);
                if (trxResult.Status != USBTransferStatus.OK)
                {
                    this._logger.LogWarning("WRITE NOT OK!!!");
                    this._logger.LogWarning(trxResult);
                }
                readResult = await device.TransferIn(1, 64);
                if (readResult.Status != USBTransferStatus.OK)
                {
                    this._logger.LogWarning("READ NOT OK!!!");
                    this._logger.LogWarning(readResult);
                }
                read = readResult.Data[0];
                sendFailures++;
                this._logger.LogInformation($"Failures: {sendFailures}");
            }

            if (read != PinPadConstants.ACK) throw new InvalidOperationException(PinPadConstants.NAK_STR);

            this._logger.LogInformation($"{PinPadConstants.PINPAD_TO_APP} {PinPadConstants.ACK_STR}");

            var response = new MemoryStream();

            if (readResult.Data.Length > 1 && readResult.Data.Length < 64)
            {
                await response.WriteAsync(readResult.Data, 0, readResult.Data.Length);
            }
            else
            {
                do
                {
                    this._logger.LogInformation($"Reading mode data...");
                    readResult = await device.TransferIn(1, 64);
                    await response.WriteAsync(readResult.Data, 0, readResult.Data.Length);
                } while (readResult.Data.Length == 64);
            }

            this._logger.LogInformation($"Data length: {response.Length}");

            return await ReadPacket(device, response.ToArray());
        }

19 View Source File : CanonicalRequestPatterns.cs
License : Apache License 2.0
Project Creator : aspnet

[CanonicalRequest(Path = "/large-immediate-asyncwrite", Description = "Return 1mb ascii byte[] in 2kb await WriteAsync")]
        public async Task LargeImmediateAsyncWrite(IDictionary<string, object> env)
        {
            Util.ResponseHeaders(env)["Content-Type"] = new[] { "text/plain" };
            Stream responseBody = Util.ResponseBody(env);
            for (int loop = 0; loop != (1 << 20) / (2 << 10); ++loop)
            {
                await responseBody.WriteAsync(_2KAlphabet, 0, 2048);
            }
        }

19 View Source File : FilesSelfTest.cs
License : Apache License 2.0
Project Creator : aloneguid

[Test]
      public async Task OpenWrite_WriteAsync_DisposeSync_ReadsSameText()
      {
         string text = "write me here on " + DateTime.UtcNow;

         using(Stream s = await _storage.OpenWrite("writeme.txt", WriteMode.Create))
         {
            byte[] data = Encoding.UTF8.GetBytes(text);
            await s.WriteAsync(data, 0, data.Length);
         }

         string actual = await _storage.ReadText("writeme.txt");
         if(actual != text)
            replacedertFail(text, actual);
      }

19 View Source File : BufferSpan.cs
License : MIT License
Project Creator : 1996v

internal Task WriteToAsync(Stream stream, int count)
        {
            return stream.WriteAsync(Buffer, Start, count);
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

private async Task SaveMessage(Message message)
        {
            await _recordFileData.WriteAsync(FlvMuxer.MultiplexFlv(message));
        }

19 View Source File : HotReloadCommand.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(ProgressMonitor progressMonitor, string replacedemblyPath, bool debugging)
        {
            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                await progressMonitor.Log.WriteLineAsync($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator");
            }
            catch (Exception ex)
            {
                await progressMonitor.ErrorLog.WriteLineAsync([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}");

                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : SaveEndpoints.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus

public async Task<bool> Handle(Request request, CancellationToken cancellationToken)
            {
                var directory = Path.GetDirectoryName(_appSettings.EndpointsFilePath);

                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var json = JsonConvert.SerializeObject(_context.Endpoints, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All,
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                });

                var bytes = new UTF8Encoding().GetBytes(json);

                using (var stream = File.Open(_appSettings.EndpointsFilePath, FileMode.Create))
                {
                    stream.Seek(0, SeekOrigin.End);

                    await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
                }

                return true;
            }

19 View Source File : X11Client.cs
License : MIT License
Project Creator : azyobuzin

protected internal async Task<T> SendRequestAsync<T>(int requestSize, Action<byte[]> createRequest, Func<byte[], byte[], ValueTask<T>> readReply)
        {
            var tcs = new TaskCompletionSource<T>();

            async Task action(byte[] replyHeader, byte[] replyContent, Exception excpetion)
            {
                if (excpetion != null)
                {
                    tcs.TrySetException(excpetion);
                    return;
                }

                try
                {
                    tcs.TrySetResult(await readReply(replyHeader, replyContent).ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            }

            ushort sequenceNumber = 0;

            await this._requestSemapreplaced.WaitAsync().ConfigureAwait(false);
            try
            {
                sequenceNumber = this._sequenceNumber;

                if (!this._replyActions.TryAdd(sequenceNumber, action))
                    throw new InvalidOperationException("Duplicated sequence number");

                EnsureBufferSize(ref this._requestBuffer, requestSize);
                createRequest(this._requestBuffer);
                await this.Stream.WriteAsync(this._requestBuffer, 0, requestSize).ConfigureAwait(false);

                this._sequenceNumber++;
            }
            catch
            {
                this._replyActions.TryRemove(sequenceNumber, out var _);
                throw;
            }
            finally
            {
                this._requestSemapreplaced.Release();
            }

            return await tcs.Task.ConfigureAwait(false);
        }

See More Examples