public override int FinalizeHashAndReset(Span <byte> destination)
        {
            GetCurrentHash(destination);
            buffer = null;

            return(hashSizeInBytes);
        }
        public async Task <MemoryStream?> Get(string key, MemoryStream? @default = null)
        {
            var(bucketName, filePath) = SplitKey(key);

            using var client = GetClient;

            var bucketExists = await client.DoesS3BucketExistAsync(bucketName);

            if (!bucketExists)
            {
                return(@default);
            }

            using var obj = await client.GetObjectAsync(new GetObjectRequest
            {
                BucketName = bucketName,
                Key        = filePath,
            });

            if (obj == null || obj.ResponseStream == null || obj.ResponseStream.Length <= 0)
            {
                return(@default);
            }

            using var data = obj.ResponseStream;
            var memoryStream = new MemoryStream();

            data.CopyTo(memoryStream);
            data.Seek(0, SeekOrigin.Begin);

            return(memoryStream);
        }
        public async Task <MemoryStream?> Get(string key, MemoryStream? @default = null)
        {
            var(containerName, filePath) = SplitKey(key);

            var container = new BlobContainerClient(_connectionString, containerName);

            var containerExists = await container.ExistsAsync();

            if (!containerExists.Value)
            {
                return(@default);
            }

            var blob = container.GetBlobClient(filePath);

            var blobExists = await blob.ExistsAsync();

            if (!blobExists.Value)
            {
                return(@default);
            }

            var stream = new MemoryStream();

            await blob.DownloadToAsync(stream);

            return(stream);
        }
        protected override void HandleExtendedHandshakeMessage(PeerId id, ExtendedHandshakeMessage message)
        {
            base.HandleExtendedHandshakeMessage(id, message);

            if (id.ExtensionSupports.Supports(LTMetadata.Support.Name))
            {
                var metadataSize = message.MetadataSize.GetValueOrDefault(0);
                if (Stream == null && metadataSize > 0)
                {
                    Stream = new MemoryStream(new byte[metadataSize], 0, metadataSize, true, true);
                    int size = metadataSize % LTMetadata.BlockSize;
                    if (size > 0)
                    {
                        size = 1;
                    }
                    size    += metadataSize / LTMetadata.BlockSize;
                    bitField = new BitField(size);
                }

                // We only create the Stream if the remote peer has sent the metadata size key in their handshake.
                // There's no guarantee the remote peer has the metadata yet, so even though they support metadata
                // mode they might not be able to share the data.
                if (Stream != null)
                {
                    RequestNextNeededPiece(id);
                }
            }
        }
        public HttpResponseMessage Post()
        {
            var          doc    = _htmlToPdfDocumentGenerator.Generate();
            MemoryStream?stream = null;

            _ = _pdfConverter.ConvertAsync(
                doc,
                length =>
            {
#pragma warning disable IDISP003 // Dispose previous before re-assigning.
                stream = _recyclableMemoryStreamManager.GetStream(
                    Guid.NewGuid(),
                    "wkhtmltox",
                    length);
#pragma warning restore IDISP003 // Dispose previous before re-assigning.
                return(stream);
            },
                CancellationToken.None).GetAwaiter().GetResult();
            stream !.Position = 0;
            var httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
            httpResponseMessage.Content = new ByteArrayContent(stream.ToArray());
            httpResponseMessage.Content.Headers.ContentLength      = stream.Length;
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "sample.pdf",
            };
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            return(httpResponseMessage);
        }
Beispiel #6
0
 private Response(bool success, int requestID, string?errorMsg, MemoryStream?successPayload)
 {
     Success        = success;
     RequestID      = requestID;
     ErrorMsg       = errorMsg;
     SuccessPayload = successPayload;
 }
Beispiel #7
0
        public void Finish()
        {
            if (_toDeflateStream == null)
            {
                ThrowDisposedException();
            }
            if (_linesWritten < _height)
            {
                throw new InvalidOperationException($"Written {_linesWritten:n0} lines, expected {_height:n0}");
            }

            using (var deflateBackingStream = new MemoryStream())
            {
                using (var deflateStream = new ZlibStream(deflateBackingStream, CompressionMode.Compress, true))
                {
                    _toDeflateStream.Position = 0;
                    _toDeflateStream.CopyTo(deflateStream);
                }
                var deflatedBuffer = deflateBackingStream.GetBuffer().AsSpan().Slice(0, (int)deflateBackingStream.Length);
                WriteChunk(datType, deflatedBuffer);
            }
            _toDeflateStream.Dispose();
            _toDeflateStream = null;

            WriteEnd();
            Stream.Position = 0;
        }
Beispiel #8
0
        public void Check_ReusableMemoryStream()
        {
            var cache = new ReusableMemoryStreams();

            Assert.IsTrue(cache.Count == 0);
            MemoryStream?rememberedMemoryStreamFirst = null;

            using (cache.UseMemoryStream(out var memoryStreamFirst, 256))
                using (var streamWriter = new StreamWriter(memoryStreamFirst))
                {
                    streamWriter.WriteLine("Test01");
                    streamWriter.WriteLine("Test02");
                    rememberedMemoryStreamFirst = memoryStreamFirst;
                }

            Assert.IsTrue(cache.Count == 1);
            MemoryStream?rememberedMemoryStreamSecond = null;

            using (cache.UseMemoryStream(out var memoryStreamSecond))
            {
                Assert.IsTrue(memoryStreamSecond.Length == 0);
                Assert.IsTrue(memoryStreamSecond.Capacity == 256);
                Assert.IsTrue(memoryStreamSecond != rememberedMemoryStreamFirst);
                rememberedMemoryStreamSecond = memoryStreamSecond;
            }

            Assert.IsTrue(rememberedMemoryStreamFirst.GetBuffer() == rememberedMemoryStreamSecond.GetBuffer());
            Assert.IsTrue(cache.Count == 1);
        }
Beispiel #9
0
        private ITcpSession ConnectSync(string host, int port)
        {
            var          remove_mes = new List <int>();
            MemoryStream?mstream    = null;

            foreach (var(id, stream) in streams)
            {
                if (!stream.CanRead)
                {
                    remove_mes.Add(id);
                    continue;
                }
                if (id == port)
                {
                    mstream = stream;
                }
            }
            foreach (var remove in remove_mes)
            {
                streams.Remove(remove);
            }

            if (mstream is null)
            {
                mstream = new MemoryStream();
                streams.Add(port, mstream);
            }

            var session = new MockTcpSession(mstream, Config.TcpConnectionTimeoutTicks);

            return(session);
        }
        public override MemoryStream Draw(MemoryStream stream)
        {
            var c = "0000004D74455874436F707972696768740047656E657261746564207769746820426172636F64652042616B65727920666F72202E4E455420687474703A2F2F7777772E626172636F646562616B6572792E636F6DFB518FC3";

            // We can only have one stream at a time.
            this.Dispose();

            byte[] buffer = new byte[8];
            this.stream = new MemoryStream((int)stream.Length + c.Length / 2);

            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(buffer, 0, 8);
            if (BCGDraw.ByteArrayCompare(buffer, new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }))
            {
                stream.Seek(0, SeekOrigin.Begin);
                BCGDraw.CopyToStream(stream, this.stream, 33);
                var i = 0;
                while (i < c.Length)
                {
                    buffer[0] = (byte)Convert.ToInt32(c.Substring(i, 2), 16);
                    this.stream.Write(buffer, 0, 1);
                    i += 2;
                }

                BCGDraw.CopyToStream(stream, this.stream);
            }
            else
            {
                stream.Seek(0, SeekOrigin.Begin);
                BCGDraw.CopyToStream(stream, this.stream);
            }

            return(this.stream);
        }
        public static void VerifyRoundTrip(
            MemoryStream peStream,
            MemoryStream?pdbStream,
            string assemblyFileName,
            ImmutableArray <SyntaxTree> syntaxTrees,
            ImmutableArray <MetadataReference> metadataReferences,
            CancellationToken cancellationToken = default)
        {
            using var peReader = new PEReader(peStream);
            var embeddedPdbReader = peReader.GetEmbeddedPdbMetadataReader();
            var portablePdbReader = pdbStream is not null?MetadataReaderProvider.FromPortablePdbStream(pdbStream).GetMetadataReader() : null;

            Assert.True(embeddedPdbReader == null ^ portablePdbReader == null);

            var pdbReader     = embeddedPdbReader ?? portablePdbReader ?? throw ExceptionUtilities.Unreachable;
            var factory       = LoggerFactory.Create(configure => { });
            var logger        = factory.CreateLogger("RoundTripVerification");
            var optionsReader = new CompilationOptionsReader(logger, pdbReader, peReader);

            VerifyMetadataReferenceInfo(optionsReader, metadataReferences);

            var compilationFactory = CompilationFactory.Create(
                assemblyFileName,
                optionsReader);

            using var rebuildPeStream  = new MemoryStream();
            using var rebuildPdbStream = optionsReader.HasEmbeddedPdb ? null : new MemoryStream();
            var emitResult = compilationFactory.Emit(rebuildPeStream, rebuildPdbStream, syntaxTrees, metadataReferences, cancellationToken);

            Assert.True(emitResult.Success);
            Assert.Equal(peStream.ToArray(), rebuildPeStream.ToArray());
            Assert.Equal(pdbStream?.ToArray(), rebuildPdbStream?.ToArray());
        }
            bool IEqualityComparer <MemoryStream> .Equals(MemoryStream?x, MemoryStream?y)
            {
                if (ReferenceEquals(x, y))
                {
                    return(true);
                }

                if (x != null && y != null)
                {
                    if (x.Length != y.Length)
                    {
                        return(false);
                    }

                    byte[] xBytes = x.ToArray();
                    byte[] yBytes = y.ToArray();

                    for (int i = 0; i < xBytes.Length; i++)
                    {
                        if (xBytes[i] != yBytes[i])
                        {
                            return(false);
                        }
                    }

                    return(true);
                }

                return(false);
            }
Beispiel #13
0
        private async Task LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
        {
            try
            {
                await serializeToStreamTask.ConfigureAwait(false);
            }
            catch (Exception e)
            {
                tempBuffer.Dispose(); // Cleanup partially filled stream.
                Exception we = GetStreamCopyException(e);
                if (we != e)
                {
                    throw we;
                }
                throw;
            }

            try
            {
                tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data.
                _bufferedContent = tempBuffer;
            }
            catch (Exception e)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(this, e);
                }
                throw;
            }
        }
Beispiel #14
0
        public void GlobalSetup()
        {
            _Stream = new MemoryStream();
            var transport = new TStreamTransport(_Stream, _Stream, null);

            _Protocol = new TCompactProtocol(transport);
        }
        private static CommandResult ConnectPhase_2(string user, out MemoryStream?ms, out NetworkStream ns, out byte[]?_sendBytes, out byte[]?resBytes, out int resSize, ref string connectedJson)
        {
            chat       = new TcpClient(Program.addr, port[0]);
            ns         = chat.GetStream();
            ms         = new MemoryStream();
            _sendBytes = Encoding.UTF8.GetBytes("{ \"exec\": \"join\", \"name\": \"" + user + "\", \"token\": \"" + tokenResponse.Token + "\" }\r\n");
            ns.Write(_sendBytes, 0, _sendBytes.Length);
            _sendBytes = null;
            resBytes   = new byte[1024];
            do
            {
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                if (resSize == 0)
                {
                    Console.WriteLine("Server closed.");
                    return(CommandResult.Error);
                }
                ms.Write(resBytes, 0, resSize);
            } while (ns.DataAvailable || (resBytes[resSize - 2] != '\r' && resBytes[resSize - 1] != '\n'));
            connectedJson = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            connectedJson = connectedJson.TrimEnd('\n');
            connectedJson = connectedJson.TrimEnd('\r');
            tokenResponse = JsonConvert.DeserializeObject <JoinParser>(connectedJson);

            Program.phase = 2;
            Console.WriteLine("Chat server successfly connected.\nType 'next' or 'connect -s command' to Connect command server.");
            return(CommandResult.Success);
        }
Beispiel #16
0
        public async Task <IHttpActionResult> Post()
        {
            var          doc    = _htmlToPdfDocumentGenerator.Generate();
            MemoryStream?stream = null;

            _ = await _pdfConverter.ConvertAsync(
                doc,
                length =>
            {
#pragma warning disable IDISP003 // Dispose previous before re-assigning.
                stream = _recyclableMemoryStreamManager.GetStream(
                    Guid.NewGuid(),
                    "wkhtmltox",
                    length);
#pragma warning restore IDISP003 // Dispose previous before re-assigning.
                return(stream);
            },
                HttpContext.Current.Request.GetOwinContext().Request.CallCancelled).ConfigureAwait(false);

            stream !.Position = 0;
#pragma warning disable CA2000   // Dispose objects before losing scope
#pragma warning disable IDISP001 // Dispose created.
            var httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
#pragma warning restore IDISP001 // Dispose created.
#pragma warning restore CA2000   // Dispose objects before losing scope
            httpResponseMessage.Content = new ByteArrayContent(stream.ToArray());
            httpResponseMessage.Content.Headers.ContentLength      = stream.Length;
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "sample.pdf",
            };
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            return(ResponseMessage(httpResponseMessage));
        }
Beispiel #17
0
    public CompiledAssemblyResult Compile()
    {
        CollectibleAssemblyLoadContext context = new();

        var compilation = GetSharpCompilation();

        using var peStream            = new MemoryStream();
        using MemoryStream? symStream = _useDebug ? new MemoryStream() : null;

        var emitResult = compilation.Emit(peStream, symStream);

        if (emitResult.Success)
        {
            peStream.Seek(0, SeekOrigin.Begin);
            symStream?.Seek(0, SeekOrigin.Begin);
            var assembly = context.LoadFromStream(peStream, symStream);
            return(new CompiledAssemblyResult(context, assembly));
        }

        var error = PrettyPrintCompileError(emitResult);

        _logger.LogError("Failed to compile applications\n{Error}", error);

        context.Unload();
        // Finally do cleanup and release memory
        GC.Collect();
        GC.WaitForPendingFinalizers();
        throw new InvalidOperationException();
    }
        private Stream?ProcessFile(string id, string appFile)
        {
            Console.WriteLine($"Attempting to read {appFile}");
            if (!_rootDictionary.ContainsKey(id))
            {
                Console.WriteLine($"Cannot process {appFile} id {id} not found...");
                return(null);
            }

            _rootDictionary[id].FileDictionary[appFile] = (null, new ManualResetEventSlim());
            _rootDictionary[id].FileCollection.Writer.WriteAsync(appFile);

            _rootDictionary[id].FileDictionary[appFile].resetEvent.Wait();
            MemoryStream?stream = _rootDictionary[id].FileDictionary[appFile].stream;

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

            stream.Position = 0;

            if (Path.GetFileName(appFile) == Path.GetFileName(_rootDictionary[id].HtmlHostPath))
            {
                using StreamReader sr = new StreamReader(stream);
                var contents = sr.ReadToEnd();

                contents = contents.Replace("framework://blazor.desktop.js", "remote.blazor.desktop.js");

                contents = Regex.Replace(contents, "<base.*href.*=.*(\"|').*/.*(\"|')", $"<base href=\"/{id}/\"", RegexOptions.Multiline);
                stream   = new MemoryStream(Encoding.ASCII.GetBytes(contents));
            }
            Console.WriteLine($"Successfully read {appFile}");
            return(stream);
        }
Beispiel #19
0
        public static string GetRequestBodyAsString(Request request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            string       result = string.Empty;
            MemoryStream?ms     = null;

            if (request.Body.Position != 0)
            {
                request.Body.Seek(0, SeekOrigin.Begin);
            }

            try
            {
                ms = ReadIntoMemoryStream(request);

                using var reader = new StreamReader(ms);
                ms     = null;
                result = reader.ReadToEnd();
            }
            finally
            {
                ms?.Dispose();
            }

            return(result);
        }
 public override void Dispose()
 {
     if (this.stream != null)
     {
         this.stream.Dispose();
         this.stream = null;
     }
 }
        public override int FinalizeHashAndReset(Span <byte> destination)
        {
            int written = GetCurrentHash(destination);

            _buffer = null;

            return(written);
        }
Beispiel #22
0
 public void Dispose()
 {
     GC.SuppressFinalize(this);
     if (Stream != null)
     {
         Stream.Dispose();
         Stream = null;
     }
 }
Beispiel #23
0
        public override void AppendHashData(ReadOnlySpan <byte> data)
        {
            if (buffer == null)
            {
                buffer = new MemoryStream(1000);
            }

            buffer.Write(data);
        }
Beispiel #24
0
        public static string DecryptString(string str)
        {
            if (MyCommon.IsNullOrEmpty(str))
            {
                return("");
            }

            //DESCryptoServiceProviderオブジェクトの作成
            using var des = new DESCryptoServiceProvider();

            //共有キーと初期化ベクタを決定
            //パスワードをバイト配列にする
            var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");

            //共有キーと初期化ベクタを設定
            des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
            des.IV  = ResizeBytesArray(bytesKey, des.IV.Length);

            //Base64で文字列をバイト配列に戻す
            var bytesIn = Convert.FromBase64String(str);

            MemoryStream?    msIn        = null;
            ICryptoTransform?desdecrypt  = null;
            CryptoStream?    cryptStreem = null;

            try
            {
                //暗号化されたデータを読み込むためのMemoryStream
                msIn = new MemoryStream(bytesIn);
                //DES復号化オブジェクトの作成
                desdecrypt = des.CreateDecryptor();
                //読み込むためのCryptoStreamの作成
                cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read);

                //Disposeが重複して呼ばれないようにする
                msIn       = null;
                desdecrypt = null;

                //復号化されたデータを取得するためのStreamReader
                using var srOut = new StreamReader(cryptStreem, Encoding.UTF8);

                //Disposeが重複して呼ばれないようにする
                cryptStreem = null;

                //復号化されたデータを取得する
                var result = srOut.ReadToEnd();

                return(result);
            }
            finally
            {
                msIn?.Dispose();
                desdecrypt?.Dispose();
                cryptStreem?.Dispose();
            }
        }
Beispiel #25
0
 // create on save from ipersist stream
 internal State(MemoryStream memoryStream, int storageType, AxHost control, PropertyBagStream propertyBag)
 {
     Type         = storageType;
     _propertyBag = propertyBag;
     // dangerous?
     _length       = (int)memoryStream.Length;
     _memoryStream = memoryStream;
     _manualUpdate = control.GetAxState(s_manualUpdate);
     _licenseKey   = control.GetLicenseKey();
 }
Beispiel #26
0
        public static string EncryptString(string str)
        {
            if (MyCommon.IsNullOrEmpty(str))
            {
                return("");
            }

            //文字列をバイト型配列にする
            var bytesIn = Encoding.UTF8.GetBytes(str);

            //DESCryptoServiceProviderオブジェクトの作成
            using var des = new DESCryptoServiceProvider();

            //共有キーと初期化ベクタを決定
            //パスワードをバイト配列にする
            var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");

            //共有キーと初期化ベクタを設定
            des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
            des.IV  = ResizeBytesArray(bytesKey, des.IV.Length);

            MemoryStream?    msOut      = null;
            ICryptoTransform?desdecrypt = null;

            try
            {
                //暗号化されたデータを書き出すためのMemoryStream
                msOut = new MemoryStream();

                //DES暗号化オブジェクトの作成
                desdecrypt = des.CreateEncryptor();

                //書き込むためのCryptoStreamの作成
                using var cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write);

                //Disposeが重複して呼ばれないようにする
                var msTmp = msOut;
                msOut      = null;
                desdecrypt = null;

                //書き込む
                cryptStream.Write(bytesIn, 0, bytesIn.Length);
                cryptStream.FlushFinalBlock();
                //暗号化されたデータを取得
                var bytesOut = msTmp.ToArray();

                //Base64で文字列に変更して結果を返す
                return(Convert.ToBase64String(bytesOut));
            }
            finally
            {
                msOut?.Dispose();
                desdecrypt?.Dispose();
            }
        }
        private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback?cback, object?state)
        {
            if (_closed)
            {
                HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this);
                ares._callback = cback;
                ares._state    = state;
                ares.Complete();
                return(ares);
            }

            byte[]? bytes = null;
            MemoryStream?ms      = GetHeaders(false);
            bool         chunked = _response.SendChunked;

            if (ms != null)
            {
                long start = ms.Position;
                ms.Position = ms.Length;
                if (chunked)
                {
                    bytes = GetChunkSizeBytes(size, false);
                    ms.Write(bytes, 0, bytes.Length);
                }
                ms.Write(buffer, offset, size);
                buffer = ms.GetBuffer();
                offset = (int)start;
                size   = (int)(ms.Position - start);
            }
            else if (chunked)
            {
                bytes = GetChunkSizeBytes(size, false);
                InternalWrite(bytes, 0, bytes.Length);
            }

            try
            {
                return(_stream.BeginWrite(buffer, offset, size, cback, state));
            }
            catch (IOException ex)
            {
                if (_ignore_errors)
                {
                    HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this);
                    ares._callback = cback;
                    ares._state    = state;
                    ares.Complete();
                    return(ares);
                }
                else
                {
                    throw new HttpListenerException(ex.HResult, ex.Message);
                }
            }
        }
Beispiel #28
0
        public async Task AsyncServerStreamingCall_SuccessAfterRetry_RequestContentSent()
        {
            // Arrange
            var          syncPoint      = new SyncPoint(runContinuationsAsynchronously: true);
            MemoryStream?requestContent = null;

            var callCount  = 0;
            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                Interlocked.Increment(ref callCount);

                var s  = await request.Content !.ReadAsStreamAsync();
                var ms = new MemoryStream();
                await s.CopyToAsync(ms);

                if (callCount == 1)
                {
                    await syncPoint.WaitForSyncPoint();

                    await request.Content !.CopyToAsync(new MemoryStream());
                    return(ResponseUtils.CreateHeadersOnlyResponse(HttpStatusCode.OK, StatusCode.Unavailable));
                }

                syncPoint.Continue();

                requestContent = ms;

                var reply = new HelloReply {
                    Message = "Hello world"
                };
                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var serviceConfig = ServiceConfigHelpers.CreateHedgingServiceConfig(maxAttempts: 2, hedgingDelay: TimeSpan.FromMilliseconds(50));
            var invoker       = HttpClientCallInvokerFactory.Create(httpClient, serviceConfig: serviceConfig);

            // Act
            var call = invoker.AsyncServerStreamingCall <HelloRequest, HelloReply>(ClientTestHelpers.GetServiceMethod(MethodType.ServerStreaming), string.Empty, new CallOptions(), new HelloRequest {
                Name = "World"
            });
            var moveNextTask = call.ResponseStream.MoveNext(CancellationToken.None);

            // Wait until the first call has failed and the second is on the server
            await syncPoint.WaitToContinue().DefaultTimeout();

            // Assert
            Assert.IsTrue(await moveNextTask);
            Assert.AreEqual("Hello world", call.ResponseStream.Current.Message);

            requestContent !.Seek(0, SeekOrigin.Begin);
            var requestMessage = await ReadRequestMessage(requestContent).DefaultTimeout();

            Assert.AreEqual("World", requestMessage !.Name);
        }
Beispiel #29
0
 internal void Encode(short senderId = 0)
 {
     headerByteStream = new MemoryStream(header);
     using var mw     = new BinaryWriter(headerByteStream);
     mw.Write(senderId);
     mw.Write(QueryId);
     while (headerByteStream.Position < headerByteStream.Length)
     {
         mw.Write((byte)0xff);
     }
 }
Beispiel #30
0
 public async Task Initialize()
 {
     if (file.Exists())
     {
         stored = new MemoryStream(2 + (int)file.Size);
         using (var input = await file.OpenRead())
         {
             await input.CopyToAsync(stored);
         }
     }
 }